Try Except in 'for' loop - Python - python

I made a 'guess the number'game, but I wanted to add input validation so the user can only guess an integer. Here is my code, I appreciate any suggestions. I am using python 3.
import random
print('Hello, what is your name?')
name = input()
print('It is nice to meet you ' + name + '.')
secretNumber = random.randint(1, 20)
print('Well ' + name + ', I am thinking of a number between 1 and 20')
for guessTaken 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 %d guesses' %(guessTaken))
else:
print('Nope. My number was ' + str(secretNumber) + '.')

def input_int(prompt=">",error_msg="That is not an int!"):
while True:
try:
return int(input(prompt))
except ValueError:
print(error_msg)
x = input_int("Please Enter an Int:","Wrong Answer!")
print x,x**2
you can abstract this further
def input_type(typeClass=str,prompt="?",error_msg="Wrong Padawan"):
while True:
try:
return typeClass(input(prompt))
except ValueError:
print(error_msg)
input_type(int,"Enter an int:","Thats not an int!")
input_type(float,"Enter a float:","Thats not a float!")
input_type(FunkyChickenClass,"Enter a name for your chicken:","Thats wrong!")
or
def input_int(prompt="Enter Int:",error_msg="Not an int!"):
return input_type(int,prompt,error_msg)

for guessTaken in range(1, 7):
guess = 0
while guess < 1 or guess > 20:
print('Take a guess.')
try:
guess = int(input())
except ValueError:
print("Guess must be a number.")
else:
if guess < 1 or guess > 20:
print("Guess must be between 1 and 20.")
else:
print("Your guess is:", guess)
if guess < secretNumber:
# continue your code

Here is a better way to do this with input validation
import random
name = raw_input('Hello, what is your name?')
print('It is nice to meet you ' + name + '.')
secretNumber = random.randint(1, 20)
print('Well ' + name + ', I am thinking of a number between 1 and 20')
for guessTaken in range(1, 7):
guess = 0
invalid = True
while invalid:
try:
guess = int(raw_input('Take a guess'))
invalid = False
except ValueError:
print 'You must enter an integer'
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 %d guesses' %(guessTaken))
else:
print('Nope. My number was ' + str(secretNumber) + '.')

Related

Is there a way for me to return my code and do a second def function?

GUESS THE NUMBER
Just looking for a way to end this function and then do an aimForTarget game with a menu driven program
import random
```return guessing```
def guessTheNumber(guessing):
secretNumber = random.randint(1, 50)
print('I am thinking of a number between 1 and 50.')
for guessesTaken in range(1, 10):
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! You guessed my number in ' + str(guessesTaken) + ' guesses!')
else:
print('Game Over. You used up all your tries. ' + str(secretNumber))

Break not working inside my if statement

Looking for some help with the following block of code.
## This is a number guessing game!
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.')
for guessesTaken in range(6):
print ('Take a guess.')
guess=input()
guess=int(guess)
if guess < number:
print ('Your guess is too low.')
if guess > number:
print('Your guess is to high!')
if guess == number:
break
if guess == number:
guessesTaken = str(guessesTaken+1)
print('Good job, '+ myName + '! You guessed my number in ' + guessesTaken + ' guesses!')
if guess != number:
number= str(number)
print('Nope. The number I was thinking of was ' + number + '.')
I'm guessing that you want the code beyond break to execute, I would change your code to
## This is a number guessing game!
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.')
for guessesTaken in range(6):
print ('Take a guess.')
guess=input()
guess=int(guess)
if guess < number:
print ('Your guess is too low.')
elif guess > number:
print('Your guess is to high!')
elif guess == number:
# print 'Good job' here instead of beyond the break in a separate if statement
guessesTaken = str(guessesTaken+1)
print('Good job, '+ myName + '! You guessed my number in ' + guessesTaken + ' guesses!')
break
if guessesTaken == 5:
number= str(number)
print('Nope. The number I was thinking of was ' + number + '.')
This way the program checks if your guesses are up - if guessesTaken == 5: and if you guess the number then it breaks after printing good job etc
I think you want to do this: (give it a try)
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.')
print(number)
for guessesTaken in range(6):
print ('Take a guess.')
guess=input()
guess=int(guess)
if guess < number:
print ('Your guess is too low.')
if guess > number:
print('Your guess is to high!')
if guess == number:
break
if guess == number:
guessesTaken = str(guessesTaken+1)
print('Good job, '+ myName + '! You guessed my number in ' + guessesTaken + ' guesses!')
if guess != number:
number= str(number)
print('Nope. The number I was thinking of was ' + number + '.')
You shouldn't indent this:
if guess == number:
guessesTaken = str(guessesTaken+1)
print('Good job, '+ myName + '! You guessed my number in ' + guessesTaken + ' guesses!')
if guess != number:
number= str(number)
print('Nope. The number I was thinking of was ' + number + '.')
import random
maxGuesses = 6
guessed = False
myName = input('Hello! What is your name? ')
number = random.randint(1, 20)
print ('Well, {0}, I am thinking of a number between 1 and 20.'.format(myName))
for guessesTaken in range(1, maxGuesses + 1):
guess = int(input("Guess: "))
if guess < number:
print ('Your guess is too low!')
if guess > number:
print('Your guess is to high!')
if guess == number:
guessed = True
break
if guessed:
print('Good job, {0}! You guessed my number in {1} guesses!'.format(myName, guessesTaken))
print("Congrats you win!")
elif not guessed:
print("Shucks, you lose!")
Your break works but the error you are getting is that when you use break the loop ends and doesn't reach the next condition.
* Above code is a little neater *

Python Guessing game - incomplete code

Can someone please help me re-design this code so that the program prompts the user to choose Easy, Medium or Hard.
Easy: maxNumber = 10
Medium: maxNumber = 50
Hard: maxNumber = 100
It should choose a random number between 0 and the maxNumber.
The program will loop calling a function the get the users guess, and another to check their guess. a function named “getGuess” which will ask the user for their guess and reprompt
if the guess is not between 0 and the maxNumber
r function named “checkGuess” which will check the users guess
compared to the answer.
The function will return “higher” if the number is higher
than the guess; “lower” if the number is lower than the guess and “correct” if thenumber is equal to the guess.
Once the user has guessed the number correctly the program will display all their guesses and
how many guesses it took them. Then the program will ask the user if they would like to try
again and redisplay the difficulty menu.
import random
guessesTaken = 0
print('Hello! Welcome to the guessing game')
myName = input()
number = random.randint(1, 20)
print('Well, ' + myName + ', I am thinking of a number between 1 and 20.')
while guessesTaken < 6:
print('Take a guess.')
guess = input()
guess = int(guess)
guessesTaken = guessesTaken + 1
if guess < number:
print('Your guess is too low.')
if guess > number:
print('Your guess is too high.')
if guess == number:
break
if guess == number:
guessesTaken = str(guessesTaken)
print('Good job, ' + myName + '! You guessed my number in ' + guessesTaken + ' guesses!')
if guess != number:
number = str(number)
print('Nope. The number I was thinking of was ' + number)
You could do something like this:
from random import randint
myName = input("what's your name? ")
def pre_game():
difficulty = input("Choose difficulty: type easy medium or hard: ")
main_loop(difficulty)
def main_loop(difficulty):
if difficulty == "easy":
answer = randint(0, 10)
elif difficulty == "medium":
answer = randint(0, 50)
else:
answer = randint(0, 100)
times_guessed = 0
guess = int()
while times_guessed < 6:
print('Take a guess.')
guess = input()
guess = int(guess)
times_guessed += 1
if guess < answer:
print('Your guess is too low.')
if guess > answer:
print('Your guess is too high.')
if guess == answer:
break
if guess == answer:
guessesTaken = str(times_guessed)
print('Good job, ' + myName + '! You guessed my number in ' + guessesTaken + ' guesses!')
if guess != answer:
print('Nope. The number I was thinking of was ' + str(answer))
next = input("Play again? y/n: ")
if next == "y":
pre_game()
else:
print("Thanks for playing!")
pre_game()

I have made a guess the number game but every time i run it and type a number this it crashes

this is my code:
#This is a guess the number game
import random
print('Hello what is your name')
name = input()
secretNumber = random.randint(1, 20)
print('Well ' + name + ' I am thinking of a number between 1 and 20. You have 6 guesses')
#Ask the player to guess 6 times.
for guessTaken in range(1, 7):
try:
print('Take a guess')
guess = int(input())
except ValueError:
print('That is not a number')
guess = int(input())
guess = str(input())
if guess < secretNumber:
print('Your guess is to low.')
elif guess > secretNumber:
print('Your gues s is to high.')
else:
break # This condition is the correct guess!
if guess == secretNumber:
print('Good job ' + name + '. You guessed my number!')
print('It was ' + str(secretNumber))
print('and you guessed it in ' + str(guessTaken) + ' guesses')
else:
print('Nope. The number I was thinking of was ' + str(secretNumber))
when ever i run it and type a number this comes up: guess = int(input())
ValueError: invalid literal for int() with base 10: ''
I don't think you want
guess = int(input())
guess = str(input())
in your loop. Try getting rid of those (you only need to take user input once during that loop, not three times). Keep the guess = int(input()) inside of the try block, though.
Try this:
#This is a guess the number game
import random
name = input('Hello what is your name: ')
secretNumber = random.randint(1, 20)
print('Well, ' + name + ' I am thinking of a number between 1 and 20. You have 6 guesses')
#Ask the player to guess 6 times.
for guessTaken in range(1, 7):
try:
guess = int(input('Take a guess: '))
except ValueError:
print('That is not a number')
if guess < secretNumber:
print('Your guess is to low.')
elif guess > secretNumber:
print('Your guess is to high.')
else:
break # This condition is the correct guess!
if guess == secretNumber:
print('Good job ' + name + '. You guessed my number!')
print('It was ' + str(secretNumber))
print('and you guessed it in ' + str(guessTaken) + ' guesses')
else:
print('Nope. The number I was thinking of was ' + str(secretNumber))
You didn't need:
guess = int(input())
guess = str(input())

Ending a program in Python

I am struggling to end my program in Python, all I want is to type q or quit to end the program when done. Here is my code
# This is a guess the number game
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, can you guess it?')
while guessesTaken < 6:
print('Take a guess!')
guess = input()
guess = int(guess)
guessesTaken = guessesTaken + 1
if guess < number:
print('Your guess is too low')
if guess > number:
print('Your guess is too high')
if guess == number:
break
if guess == number:
guessesTaken = str(guessesTaken)
print('Good job ' + myName + '!You guessed my number in ' + guessesTaken + ' guesses!')
if guess != number:
number = str(number)
print('Nope. The number I was thinking of was ' + number)
print('Game Over')
choice = input('Press Q to Quit')
if choice == 'q' :
sys.exit()
Please tell me where I am going wrong??
From what I can tell you have two errors.
First you need to import the sys module for sys.exit() to work.
Second, your indentation is incorrect in two places. Here is the correct code. The comments show where the indentation is incorrect:
# This is a guess the number game
import random
import sys
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, can you guess it?')
while guessesTaken < 6:
print('Take a guess!')
guess = input()
guess = int(guess)
guessesTaken = guessesTaken + 1
if guess < number:
print('Your guess is too low')
if guess > number:
print('Your guess is too high')
if guess == number:
break
if guess == number:
guessesTaken = str(guessesTaken)
print('Good job ' + myName + '!You guessed my number in ' + guessesTaken + ' guesses!')
if guess != number: #indentation was off here
number = str(number)
print('Nope. The number I was thinking of was ' + number)
print('Game Over') #and here
choice = input('Press Q to Quit')
if choice == 'q' :
sys.exit() # and here
As #MarkyPython noted, you have some indent error, and you need to import sys if you want to use exit.
Note that given the code that you have, it is actually bad practice to use sys.exit(). I would instead recommend that you use break. This will exit your while loop. Because you have no code after that, your program will graciously exit.
If you add more code later on, you'll probably want to put your code inside a function. At that point, using return will be the way to go.
Using break or return is better practice because it makes it easier to add features to your program later on and makes the flow of your code better (no abrupt exit 'jump').
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, can you guess it?')
while guessesTaken < 6:
print('Take a guess!')
guess = input()
guess = int(guess)
guessesTaken = guessesTaken + 1
if guess < number:
print('Your guess is too low')
if guess > number:
print('Your guess is too high')
if guess == number:
break
if guess == number:
guessesTaken = str(guessesTaken)
print('Good job ' + myName + '!You guessed my number in ' + guessesTaken + ' guesses!')
if guess != number:
number = str(number)
print('Nope. The number I was thinking of was ' + number)
print('Game Over')
choice = input('Press Q to Quit')
if choice == 'q' :
break # instead of exit

Categories