import random
level = input("Easy gets 10 attempt Hard getse 5 attempt choose a level --> ").lower()
number = random.choice(range(101))
attempt = 0
if level == "easy":
attempt = 10
else:
attempt = 5
def check_number(guess,num):
if guess == num:
return "Correct You Won :)"
win = True
elif guess > num:
return "Too high :("
elif guess < num:
return "Too low :("
win = False
while attempt > 0 and win == False:
guess = int(input("Guess the number "))
print(check_number(guess,number))
attempt -= 1
print(f"You have {attempt} attempt left")
if win == True:
print(f"GOOD JOB YOU HAVE {attempt} LEFT")
else:
print("NEXT TİME :(")
It does not stop when you guess the number, still asks for new guess. I couldn't find the problem. I just started learning python.
CodePudding user response:
This avoids using a global variable at all:
import random
level = input("Easy gets 10 attempt Hard getse 5 attempt choose a level --> ").lower()
number = random.choice(range(101))
attempt = 0
if level == "easy":
attempt = 10
else:
attempt = 5
def check_number(guess,num):
if guess > num:
return False, "Too high :("
elif guess < num:
return False, "Too low :("
return True, "Correct You Won :)"
win = False
while attempt > 0 and not win:
guess = int(input("Guess the number "))
win, msg = check_number(guess,number)
print(msg)
if not win:
attempt -= 1
print(f"You have {attempt} attempt left")
if win:
print(f"GOOD JOB YOU HAVE {attempt} LEFT")
else:
print("NEXT TİME :(")
CodePudding user response:
Your code has two problems:
win
assigned after return and it won't runwin
is inside a function and its like you define a new variablewin
inside the function and can't access it from outside
so you might want to do sth like this:
import random
level = input("Easy gets 10 attempt Hard getse 5 attempt choose a level --> ").lower()
number = random.choice(range(101))
attempt = 0
if level == "easy":
attempt = 10
else:
attempt = 5
def check_number(guess,num):
if guess == num:
return 0
elif guess > num:
return 1
elif guess < num:
return -1
win = False
while attempt > 0 and win == False:
guess = int(input("Guess the number "))
state = check_number(guess,number)
if(state==0):
win = True
print("won")
elif(state==1):
print("is high")
elif(state==-1):
print("is low")
attempt -= 1
print(f"You have {attempt} attempt left")
if win == True:
print(f"GOOD JOB YOU HAVE {attempt} LEFT")
else:
print("NEXT TİME :(")