How do I add an exception for invalid input? - python

I am new to Python, so this is probably a dumb question to many here, but in the following code, how would I go about adding an exception, so that should someone enter say a word for instance, that would handle the invalid input and continue to ask, 'Take a guess.'?
import random
secretNumber = random.randint(1, 100)
print('I am thinking of a number between 1 and 100.')
for guessesTaken in range(1, 11):
print('Take a guess.')
guess = int(input())
if guess < secretNumber:
print('Your guess is too low.')
elif guess > secretNumber:
print('Your guess is too high.')
else:
break # This condition is the correct guess!
if guess == secretNumber:
print('Good job! You guessed mu number in ' + str(guessesTaken) + ' guesses!')
else:
print('Nope. The number I was thinking of was ' + str(secretNumber))

I believe what you are trying to do can be accomplished with the input as follows:
guess = None
while guess is None:
try:
print('Take a guess.')
guess = int(input())
except ValueError:
pass

Related

some syntax issues im facing with python

Hey so i have started with python recently and im facing a syntax error when im trying to activate this code with python 3.1
This code is from the Automate the Boring Stuff and it's exactly the same as the author used and mine is facing an Error, any idea ?
btw the Error is with the elif condition
import random
print('Hello. What is your name?')
name = input()
print('Well, ' + name + ', I am thinking of a number between 1 to 20 ')
secretNumber = random.randint(1, 20)
for guessesTaken in range(1, 7):
print('Take a guess.')
guess = int(input())
if guess < secretNumber:
print('Your guess is too low.')
elif guess > secretNumber:
print ('Your guess is too high.')
else:
break
if guess == secretNumber:
print('Good job, ' + name + '! You guessed my number in ' + str(guessesTaken) + ' guesses')
else:
print(' Nope, that number i was thinking of was ' + str(secretNumber))
code with identation fixed which ran on my machine
import random
print('Hello. What is your name?')
name = input()
print('Well, ' + name + ', I am thinking of a number between 1 to 20 ')
secretNumber = random.randint(1, 20)
for guessesTaken in range(1, 7):
print('Take a guess.')
guess = int(input())
if guess < secretNumber:
print('Your guess is too low.')
elif guess > secretNumber:
print ('Your guess is too high.')
else:
break
if guess == secretNumber:
print('Good job, ' + name + '! You guessed my number in ' + str(guessesTaken) + ' guesses')
else:
print(' Nope, that number i was thinking of was ' + str(secretNumber))
Here is the correct indentation:
import random
print('Hello. What is your name?')
name = input()
print('Well, ' + name + ', I am thinking of a number between 1 to 20 ')
secretNumber = random.randint(1, 20)
for guessesTaken in range(1, 7):
print('Take a guess.')
guess = int(input())
if guess < secretNumber:
print('Your guess is too low.')
elif guess > secretNumber:
print ('Your guess is too high.')
else:
break
if guess == secretNumber:
print('Good job, ' + name + '! You guessed my number in ' + str(guessesTaken) + ' guesses')
else:
print(' Nope, that number i was thinking of was ' + str(secretNumber))
Indentation is a very important concept of Python!
You have indentation errors on your code, elif and else should be indented at the same level of if. Same for the second 'else'.
import random
print('Hello. What is your name?')
name = input()
print('Well, ' + name + ', I am thinking of a number between 1 to 20 ')
secretNumber = random.randint(1, 20)
for guessesTaken in range(1, 7):
print('Take a guess.')
guess = int(input())
if guess < secretNumber:
print('Your guess is too low.')
elif guess > secretNumber:
print ('Your guess is too high.')
else:
break
if guess == secretNumber:
print('Good job, ' + name + '! You guessed my number in ' + str(guessesTaken) + ' guesses')
else:
print(' Nope, that number i was thinking of was ' + str(secretNumber))
I think you are looking for this. Note the indentation of the if/else statements.
import random
print('Hello. What is your name?')
name = input()
print('Well, ' + name + ', I am thinking of a number between 1 to 20 ')
secretNumber = random.randint(1, 20)
for guessesTaken in range(1, 7):
print('Take a guess.')
guess = int(input())
if guess < secretNumber:
print('Your guess is too low.')
elif guess > secretNumber:
print ('Your guess is too high.')
else:
break
if guess == secretNumber:
print('Good job, ' + name + '! You guessed my number in ' + str(guessesTaken)
+' guesses')
else:
print(' Nope, that number i was thinking of was ' + str(secretNumber))
Disclaimer:
I'm a bit of a newb myself so there could be better answers out there.
Python is all about indentation. The indentations of the if/elif/else should be all on the same level. See below:
if guess < secretNumber:
print('Your guess is too low.')
elif guess > secretNumber:
print ('Your guess is too high.')
else:
break

How to continue with number of guesses after ValueError in guessing game?

I'm going through the Automate the Boring Stuff with Python videos on youtube. I finished the one about random number guessing game and am now adding some stuff to it to make it more complete.
I added some code that makes it so that if you don't enter an integer (which creates a ValueError) the program tells you that you didn't enter an integer. However, the point of the game is that you only get 6 guesses, but when the error comes up it, it resets the number of guesses.
How can I make it so that the error doesn't reset the number of cases?
Here's the code:
# This is a guess the number game.
import random
print ('Hello, what is your name?')
name = input ()
name = name.strip()
print ('Well, ' + name + ' I am thinking of a number between 1 and 20.')
secretNumber = random.randint (1, 20)
print ('DEBUG: Secret number is ' + str(secretNumber))
while True:
try:
for guessesTaken in range (1, 7):
print ('Take a guess.')
guess = int (input ())
if guess < secretNumber:
print ('Your guess is too low.')
elif guess > secretNumber:
print ('Your guess is too high.')
else:
break # This condition is for the correct guess
if (guess == secretNumber and guessesTaken == 1):
print ('Good job, ' + name + '! You guessed my number in ' + str(guessesTaken) + ' guess.')
break
elif (guess == secretNumber and guessesTaken > 1):
print ('Good job, ' + name + '! You guessed my number in ' + str(guessesTaken) + ' guesses.')
break
else:
print ('Nope. The number I was thinkig of was ' + str(secretNumber))
break
except ValueError:
print ('You did not enter a number.') # This condition is for if a non-integer is entered.
I feel like I've tried every combination of where I can but the try and for loop, but can't seem to figure it out.
The outer while loop seems unnecessary because it allows you to try even after 6 attempts.
Therefore the break in the last three conditions will also be deleted.
You should put the try into the for loop so that if an exception is raised, the program will continue to count the number of attempts.
I would do something like:
# This is a guess the number game.
import random
print('Hello, what is your name?')
name = input()
name = name.strip()
print('Well, ' + name + ' I am thinking of a number between 1 and 20.')
secretNumber = random.randint(1, 20)
print('DEBUG: Secret number is ' + str(secretNumber))
for guessesTaken in range(1, 7):
try:
print('Take a guess.')
guess = int(input())
if guess < secretNumber:
print('Your guess is too low.')
elif guess > secretNumber:
print('Your guess is too high.')
else:
break # This condition is for the correct guess
except ValueError:
print('You did not enter a number.') # This condition is for if a non-integer is entered.
if (guess == secretNumber and guessesTaken == 1):
print('Good job, ' + name + '! You guessed my number in ' + str(guessesTaken) + ' guess.')
elif (guess == secretNumber and guessesTaken > 1):
print('Good job, ' + name + '! You guessed my number in ' + str(guessesTaken) + ' guesses.')
else:
print('Nope. The number I was thinkig of was ' + str(secretNumber))
The except block also should be moved, to be related to the try block, under the block of the loop because we don't want to stop the for loop as I mentioned before.
This is a guess the number game.
import random
print ('Hello, what is your name?')
name = input ()
guess = 0
name = name.strip()
print ('Well, ' + name + ' I am thinking of a number between 1 and 20.')
secretNumber = random.randint (1, 20)
print ('DEBUG: Secret number is ' + str(secretNumber))
while True:
for guessesTaken in range (1, 7):
try:
print ('Take a guess.')
guess = int (input ())
if guess < secretNumber:
print ('Your guess is too low.')
elif guess > secretNumber:
print ('Your guess is too high.')
else:
break # This condition is for the correct guess
except ValueError:
print ('You did not enter a number.') # This condition is for if a non-integer is entered.
if (guess == secretNumber and guessesTaken == 1):
print ('Good job, ' + name + '! You guessed my number in ' + str(guessesTaken) + ' guess.')
break
elif (guess == secretNumber and guessesTaken > 1):
print ('Good job, ' + name + '! You guessed my number in ' + str(guessesTaken) + ' guesses.')
break
else:
print ('Nope. The number I was thinkig of was ' + str(secretNumber))
break

How do I get this game to end when the input is no without going back to the top?

How do I get this game to end when the input is no without going back to the top and looping through or getting an error code? Note I put "End" in so that it would not iterate again
import random
it's a simple guessing game that I want to start over if yes but end if no
def main():
y_games = 2
for y in range(y_games):
play_guessingGame_()
def play_guessingGame_():
guessesTaken = 0
print('Hello Friend,\n')
print('What is your name?\n')
name = input()
print(name + ' ,It is good to meet you!\n')
print("Let's play a game!\n ")
print('I am thinking of a number between 1 and 10. . . what is my number?\n')
try:
answer = random.randint(1,10)
while guessesTaken < 5:
print("Start guessing!\n")
guess = input()
guess = int(guess)
guessesTaken = guessesTaken + 1
if guess > answer:
print('Too high! Try again!\n')
elif guess < answer:
print('Too low! Try again!\n')
elif guess == answer:
break
while guess == answer:
guessesTaken = str(guessesTaken)
if guessesTaken == str(1):
print('AND ON THE FIRST TRY!!! IMPRESSIVE!!!!')
print('There is no beating you\n')
break
if guessesTaken > str(1):
print('Good job! You guessed my number in ' + guessesTaken + ' guesses')
print('There is no beating you\n')
break
if guess != answer:
print("I'm sorry, you have run out of guess.\n")
print('Better luck next time!\n')
except ValueError:
print('Please enter whole numbers only')
print('\nDo you want to try again? ')
response = input()
if response == 'yes':
print("Great! Let's do this!")
if response == 'no':
print('\nWell, all good things must come to end!')
Exit
main()
i added import random to your code and also changed Exit to exit() and there was no error and the game performed right, i hope i got your problem right..

Python making a number guessing game

The code I have:
import random
guessesTaken = 0
print('Hello! What is your name?')
myName = input()
number = random.randint(1, 20)
print('Well, ' + myName + ', I am thinking of a number between 1 and 20.')
while guessesTaken < 5:
print('Take a guess.')
guess = input()
guess = int(guess)
guessesTaken = guessesTaken + 1
guessesTaken = print('Thats a guess gone.')
if guess < number:
print('Your guess is too low.')
if guess > number:
print('Your guess is too high.')
if guess == number:
print('You won at life!')
break
if guess == number:
print('idk, ' + myName + '! You guessed my number in ' + guessesTaken + ' guesses!')
print('Again? Again.')
Need help with:
1.This error - Traceback (most recent call last):
File "\\wbs-fs01\2013$\13CDyke\Guessing game.py", line 12, in <module>
while guessesTaken < 5:
TypeError: unorderable types: NoneType() < int()
2.Need to fix it and display how many guesses you got the answer in.
The problem is this line:
guessesTaken = print('Thats a guess gone.')
print returns None, so that's the value your variable gets. Remove the assignment and it'll work:
print('Thats a guess gone.')

Python random number generator

The code works fine, but I can't figure out how to completely restart the program. I put continue in the code and I know that is not correct, because I want it to restart completely after you guess the correct number and it displays 'Congratulations! You guessed my number in _ guesses.
import random
guesses = 0
number = random.randint(1, 100)
print('I am thinking of a number between 1 and 100.')
while guesses < 100:
guess = int(input('Guess? '))
guesses = guesses + 1
if guess < number:
print('Your guess is too low.')
if guess > number:
print('Your guess is too high.')
if guess == number:
continue
if guess == number:
guesses = str(guesses)
print('Congratulations! You guessed my number in ' + guesses + ' guesses!')
If you want to keep on guessing and start the game automatically, you need to do a recursive call:
import random
def guess_func():
number = random.randint(1, 100)
guesses = 0
while True:
guess = int(raw_input("Enter your guess: "))
if guess < number:
print('Your guess is too low.')
guesses += 1
if guess > number:
print('Your guess is too high.')
guesses += 1
if guess == number:
print "Congratulations! You guessed my number in [{}] guesses".format(guesses)
print "Let's keep on guessing!"
return guess_func()
guess_func()
so like this:
while True:
guesses = 0
while guesses < 100:
if guesses == 100:
break
...
if guess == number:
print ...
yorn = input "do you want to try again?")
if yorn == 'n':
break
so just wrap your code in an outer while, obviously i skipped a lot of your code

Categories

Resources