Welcome to the Treehouse Community
Want to collaborate on code errors? Have bugs you need feedback on? Looking for an extra set of eyes on your latest project? Get support with fellow developers, designers, and programmers of all backgrounds and skill levels here with the Treehouse Community! While you're at it, check out some resources Treehouse students have shared here.
Looking to learn something new?
Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and join thousands of Treehouse students and alumni in the community today.
Start your free trialsyalih
16,468 Pointswhile loop end but game() wont start again
import random
secret_number = random.randint(1, 20)
guesses = []
def game():
while len(guesses) < 5:
print(secret_number)
print(guesses)
try:
guess = int(input("Guess Number Between 1 to 20: "))
except ValueError:
print("Please enter only number...")
continue
else:
if guess == secret_number:
print("Well done you got it...")
break
elif guess > secret_number:
print("number little higher")
elif guess < secret_number:
print("number little lower")
guesses.append(guess)
else:
print(guesses)
play_again = input("do you wanna play agan Y/n: ")
if play_again.lower() != 'n':
game()
else:
print("bye bye")
game()
in the end yes or no is not working
[MARKDOWN ADDED BY MOD]
2 Answers
Andreas cormack
Python Web Development Techdegree Graduate 33,011 PointsHi syalih
If you put the guesses list inside the function game it will work.
import random
secret_number = random.randint(1, 20)
def game():
guesses = [] # set guesses here
while len(guesses) < 5:
print(secret_number)
print(guesses)
try:
guess = int(input("Guess Number Between 1 to 20: "))
except ValueError:
print("Please enter only number...")
continue
else:
if guess == secret_number:
print("Well done you got it...")
break
elif guess > secret_number:
print("number little higher")
elif guess < secret_number:
print("number little lower")
guesses.append(guess)
else:
print(guesses)
play_again = input("do you wanna play agan Y/n: ")
if play_again.lower() != 'n':
# when you call the function game() length of guesses is still 5 so the else statement gets executed
game()
else:
print("bye bye")
game()
syalih
16,468 PointsThanks :)
tobiaskrause
9,160 Pointstobiaskrause
9,160 PointsCould you please format your code with "
" (look in the Markdwon Cheatsheet) The lines before the "
" must be free it is a pain to format Python code :)