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 trial
Gary Gibson
5,011 PointsHow do I write the top of this while loop as a try/except/else block?
I can't get the first condition to work as a try/except loop. I have it as
if mode != "1" and mode != "2" and mode != "creator" and mode != "creator 2":
print("Please enter '1' or '2'.")
else:
Is there a way to make it try/except?
import random
wins_e = 0
losses_e = 0
wins_h = 0
losses_h = 0
hole_in_one = 0
guesses = []
print("""
You can make the mode 'easy' or 'hard'.
'Easy' mode will let you know whether you guessed too high or too low; 'Hard" mode will not.
""")
while True:
mode = input("""Enter '1' for easy or '2' for hard. """)
if mode != "1" and mode != "2" and mode != "creator" and mode != "creator 2":
print("Please enter '1' or '2'.")
else:
secret_num = random.randint(1, 20)
print("Guess a number between 1 and 20. You have five tries!")
if mode == "creator" or mode == "creator 2":
print(secret_num)
while len(guesses) < 5:
try:
player_guess = int(input("> "))
except ValueError:
print("Please enter a whole number.")
else:
if mode == "1" or mode == "creator":
if player_guess == secret_num:
print("you win")
wins_e += 1
break
elif player_guess < secret_num and player_guess not in guesses:
guesses.append(player_guess)
if len(guesses) == 5:
print("You're out of guesses. The number was {}.".format(secret_num))
else:
print("You guessed too low! You have {} guesses left.".format(5 - len(guesses )))
elif player_guess > secret_num and player_guess not in guesses:
guesses.append(player_guess)
if len(guesses) == 5:
print("You're out of guesses. The number was {}.".format(secret_num))
else:
print("You guessed too high! You have {} guesses left.".format(5 - len(guesses )))
elif player_guess in guesses:
print("You already guessed that.")
if mode == "2" or mode == "creator 2":
if player_guess == secret_num:
print("you win")
wins_h += 1
break
elif player_guess != secret_num and player_guess not in guesses:
guesses.append(player_guess)
if len(guesses) == 5:
print("You're out of guesses. The number was {}.".format(secret_num))
else:
print("No. You have {} guesses left.".format(5 - len(guesses )))
elif player_guess in guesses:
print("You already guessed that.")
if len(guesses) == 0:
hole_in_one += 1
print("Amazing! On the first try!")
if len(guesses) == 5:
if mode == "1" or mode == "creator":
losses_e += 1
elif mode == "2" or mode == "creator 2":
losses_h += 1
print("Wins: {}, Losses: {}. Mode = Easy".format(wins_e, losses_e))
print("Wins: {}, Losses: {}. Mode = Hard".format(wins_h, losses_h))
play_again = input("Play again? ")
if play_again != 'n':
guesses = []
else:
print("Wins: {}, Losses: {}. Mode = Easy".format(wins_e, losses_e))
print("Wins: {}, Losses: {}. Mode = Hard".format(wins_h, losses_h))
break
Note that I made it so that you can log in to see the answer right away in order to test teh code. ("creator" for the easy mode and "creator 2" for the hard mode.)
1 Answer
Chris Freeman
Treehouse Moderator 68,468 PointsIt's not clear why you would want or need a try/except statement which is used to protect against issues that raise errors. What error are you concerned about being raised?
If you are testing an input is within constraints, an if is appropriate.
You may want to make the if more readable using:
if mode not in ["1", "2", "creator", "creator 2"]:
print("Please enter '1' or '2'.")
else:
#....
Gary Gibson
5,011 PointsGary Gibson
5,011 PointsThanks. I'm STILL on the Python Basics course and I don't think I've seen things expressed that way.
I didn't understand that try/except was only(?) suited for errors. Good to know that if/(then) is more appropriate here.
Also, I edited the code. I forgot to add some parameters to catch and tally the repeated numbers. I had "player_guess not in guesses" as a separate elif when it should have been combined with the comparison elifs to see if the guess was greater than or less than the number (easy mode), or simply not the number (hard mode).
Chris Freeman
Treehouse Moderator 68,468 PointsChris Freeman
Treehouse Moderator 68,468 PointsAh, you'll get to the "
in" keyword soon. It's great for checking if a character is "in" a string, an item is in a list, or a "key" is in a dictionary.Keep in mind that a
try/exceptblock is just a "wrapper" around risky code. The purpose of thetry/exceptis to handle situations that might not go well such as dealing with the real world (user input, file I/O, database query results, questionable index references, ...). If an error does occur, the "exception" block tells the program how to go forward. Without exception handling the program would raise an error and stop.If you don't foresee an unknown conditions (the usual case for most code) then a
try/exceptwrapper is not needed.