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 trialDaniel Propp
30 PointsRepeat an if statement inside a function
Hi,
im currently on the Python Basics course and was tasked to do a number game. I went ahead to build it myself, though it took me over an hour compared to what Kenneth did in 8 minutes. Generally, would you say thats good or bad?
I also did some things differently than in his workspace, such as writing a function for playagain. Im getting a little confused though after the else statement in the playagain function. How would I make it that on the else statement it should jump back to the beginning of the function and redo the input request?
import random
def playagain():
playagain = input("Would you like to play again? Write YES or NO: ")
if playagain.lower() == "yes":
game()
elif playagain.lower() == "no":
print("Ok, Bye!!")
else:
print("That isnt yes or no!")
def game():
#generate number between 1 and 10
secret_num = random.randint(1, 10)
guessTrials = 5
while guessTrials >= 1:
#get number guess from player
#If number isnt an integer
try:
guess = int(input("Guess a number between 1 and 10:"))
except ValueError:
print("Not a whole number!")
else:
#Too low/high
if guess < secret_num:
print("TOO LOW")
elif guess > secret_num:
print("TOO HIGH")
#compare guess to secret number
if guess == secret_num:
print("You got it mate!")
playagain()
else:
guessTrials -= 1
print("Thats not it. You have {} tries left".format(guessTrials))
if guessTrials == 0:
print("My number was {}".format(secret_num))
game()
Thanks :)
2 Answers
Cindy Lea
Courses Plus Student 6,497 PointsYou need a loop of some sort
Daniel Propp
30 PointsFigured it out.... Sorry!
def playagain():
while True:
playagain = input("Would you like to play again? Write YES or NO: ")
if playagain.lower() == "yes":
game()
elif playagain.lower() == "no":
print("Ok, Bye!!")
else:
print("That isnt yes or no!")