How do I fix the ValueError? - python

I used the Python for Kids book to learn the basics of Python 2.7.14, and there's this Python written game in it. It is a number guessing game, but in line 40 of the code, the ValueError keeps popping up. How do I fix this?
Line 40: if comnum == int(players_guess):
Whole code:
# New constants
QUIT = -1
quit_text = 'q'
quit_message = 'Thanks for playing'
comfirm_quit_message = 'Are you sure you want to quit (Y/N)?'
# New comfirm_quit funtion
def comfirm_quit():
"""Ask user to comfirm that they want to quit
default to yes
Return True (yes, quit) or False (no, don't quit) """
spam = raw_input(comfirm_quit_message)
if spam == 'n':
return False
else:
return True
def do_guess_round():
"""Choose a random number, ask the user for a guess
check wether the guess is true
and repeat until the user is correct"""
comnum = random.randint(1, 100)
numofguess = 0
while True:
players_guess = raw_input('Input your choice:')
# new if clause to test against quit
if players_guess == quit_text:
if comfirm_quit():
QUIT
else:
continue # that is, do next round of loop
numofguess = numofguess + 1
if comnum == int(players_guess):
print('Correct!')
elif comnum > int(players_guess):
print('Too low')
else:
print('Too high')
totalrounds = 0
totalguesses = 0
while True:
totalrounds = totalrounds + 1
print('Starting round number: ' + str(total_rounds))
print('Let the guessing begin!!!')
thisround = do_guess_round()
# new if condition (and clode block) to test against quit
if thisround == 0:
totalrounds = totalrounds - 1
avg = str(totalguesses / float(totalrounds))
if totalrounds == 0:
statsmsg = 'You completed no rounds. ' +\
'Please try again later.'
else:
statsmsg = 'You played ' + str(totalrounds) +\
' rounds, with an averave of ' +\
str(avg)
break
totalguesses = totalguesses + thisround
avg = str(totalguesses / float(totalrounds))
print("You took " + str(thisround) + " guesses")
print("Your guessing average = " + str(avg))
print("")
# Added exit messages
print(statsmsg)
(I have changed the name of the variables in the code, so the variables won't be the same from the book.)
Error Message: Traceback (most recent call last):
File "C:\Users\26benk\Desktop\Programming\PY 2\Programs\Number_guess_game.py", line 40, in <module>
if comnum == int(players_guess):
ValueError: invalid literal for int() with base 10: '0.1'

Please remove the type conversion in the line like this if comnum == int(players_guess): to if comnum == players_guess: and add these lines next to the raw input,
players_guess = raw_input(prompt)
try:
players_guess = int(players_guess)
except ValueError:
players_guess = str(players_guess)
This will definitely solve the case.

That's because you dont have a break statement to pull you out of the loop where you are checking whether the user guesses the number correctly or not.
In this loop,
while True:
players_guess = raw_input(prompt)
# new if clause to test against quit
if players_guess == quit_text:
if comfirm_quit():
QUIT
else:
continue # that is, do next round of loop
numofguess = numofguess+1
if comnum == int(players_guess):
print('Correct!')
elif comnum > int(players_guess):
print('Too low')
else:
print('Too high')
even if the user guesses correctly, he is asked for a raw_input because the loop is still active. If you hit enter, you will get the ValueError because you are trying the int function on an empty string. To avoid that, change your loop to
while True:
players_guess = raw_input(prompt)
# new if clause to test against quit
if players_guess == quit_text:
if comfirm_quit():
QUIT
else:
continue # that is, do next round of loop
numofguess = numofguess+1
if comnum == int(players_guess):
print('Correct!')
break
elif comnum > int(players_guess):
print('Too low')
else:
print('Too high')
There are other problems with this code as well. The first while loop has to be a function of the do_guess_round function

Related

Python guessing game code keeps crashing after 1 guess. How would i fix this?

My code keeps crashing after I put in the 1st guess I make. I've looked at syntax and dont think that's a problem how do I make it so it goes past the 1st guess and executes it. When I put the guess in it just puts in all the prompts at once, and how do I call the function properly at the end? Any help would be appreciated.
Import time,os,random
def get_int(message):
while True:
user_input = input(message)
try:
user_input = int(user_input)
print('Thats an integer!')
break
except:
print('That does not work we need an integer!')
return user_input
def game_loop():
fin = False
while not fin:
a = get_int('give me a lower bound:')
b = get_int('give me a upper bound:')
if a < 0:
print("that doesn't work")
if a > b:
a, b = b, a
print(a,b)
os.system('clear')
print("The number you guess has to be between " + str(a) + "and " + str(b) + '.')
num_guesses = 0
target = random.randint(a,b)
time_in = time.time()
while True:
print('You have guessed ' + str(num_guesses) + " times.")
print()
guess_input = get_int('guess a number')
if guess_input == target:
print("Congrats! You guessed the number!")
time_uin = time.time()
break
elif guess_input < a or guess_input > b:
print("guess was out of range... + 1 guess")
elif guess_input < target:
print("Your guess was too low")
else:
print("Your guess was to high")
num_guesses = num_guesses + 1
if num_guesses<3:
print('Einstein?')
else:
print('you should be sorry')
time_t = time_uin - time_in
print('it took' + str(time_t) + 'seconds for you to guess a number')
print()
time_average = time_t / (num_guesses+1)
print('It took an average of' + str(time_average)+"seconds per question")
print()
while True:
play_again = input ('Type y to play again or n to stop')
print()
if play_again == 'n':
fin = True
print('Thank God')
time.sleep(2)
os.system('clear')
break
elif play_again == 'y':
print('here we go again')
time.sleep(2)
os.system('clear')
break
else:
print('WRONG CHOCICE')
break
game_loop()
If guess_input != target on the first iteration of the loop, time_uin is referenced before assignment. Hence the error:
UnboundLocalError: local variable 'time_uin' referenced before assignment
Solution is to run the following only if guess_input == target.
if num_guesses<3:
print('Einstein?')
else:
print('you should be sorry')
time_t = time_uin - time_in
print('it took' + str(time_t) + 'seconds for you to guess a number')
print()
time_average = time_t / (num_guesses+1)
print('It took an average of' + str(time_average)+"seconds per question")
print()
Please follow coppereyecat's link to learn how to debug a basic Python program.

question regarding secret number python game

I'm wondering what´s happening with my code, because I want to print just in the end if we found the secret number, but I get it every time.
import random
answer = random.randint(1, 101)
user_winner = False
attempts = 0
attempt_word = ""
#Game Loop( the body of the loop inside)
while user_winner != True:
#User input
guess = input("Can you guess a number between 1 and 100? ")
#Check The user Input
try:
guess_number = int(guess)
except:
print("You should write a number!")
quit()
#Increase attempt count
attempts += 1
#check the user answer against the secret number
if guess_number == answer:
user_winner = True
elif guess_number > answer:
print("The number is Smaller!!")
else:
print("The number is Bigger!!")
#Get the spelling of the "attempt" word
if attempts == 1:
attempt_word = " attempt"
else:
attempt_word = " attempts"
#Display the result
print("Congratulations!! You did it in " + str(attempts) + attempt_word)
we should not be able to see it (print) unless we get the right result
If you try to simulate the code in your loop top to bottom, you will see that the final print line is always read at the end, because there's nothing stopping it from reaching that point. You are going to want to either wrap it around a condition (e.g. if/else):
if user_winner == True:
print( "Congratulations!! You did it in " + str( attempts ) + attempt_word )
You can also consider placing the print line under an already existent if statement that you wrote:
if guess_number == answer:
print( "Congratulations!! You did it in " + str( attempts ) + attempt_word )
elif ...
However, since Python reads it from top to bottom, you would also need to move the block of code you have handling the attempt_word variable.
The problem is that the congratulations part is not in an if statement and so prints every time a number is input. You can either move that up to the first if statement or leave it where it is but put it inside a new if statement.
First solution is you move the congratulations part up to where you first test to see if it's correct like this:
#setup
import random
answer = random.randint(1, 101)
user_winner = False
attempts = 0
attempt_word = ""
#Game Loop( the body of the loop inside)
while user_winner != True:
#User input
guess = input("Can you guess a number between 1 and 100? ")
#Check The user Input
try:
guess_number = int(guess)
except:
print("You should write a number!")
quit()
#Increase attempt count
attempts += 1
#check the user answer against the secret number
if guess_number == answer:
user_winner = True
#Get the spelling of the "attempt" word
if attempts == 1:
attempt_word = " attempt"
else:
attempt_word = " attempts"
#Display the result
print("Congratulations!! You did it in " + str(attempts) + attempt_word)
elif guess_number > answer:
print("The number is Smaller!!")
else:
print("The number is Bigger!!")
Or for the second solution you test to see if you get the correct result a second time before printing congratulations like this:
#setup
import random
answer = random.randint(1, 101)
user_winner = False
attempts = 0
attempt_word = ""
#Game Loop( the body of the loop inside)
while user_winner != True:
#User input
guess = input("Can you guess a number between 1 and 100? ")
#Check The user Input
try:
guess_number = int(guess)
except:
print("You should write a number!")
quit()
#Increase attempt count
attempts += 1
#check the user answer against the secret number
if guess_number == answer:
user_winner = True
elif guess_number > answer:
print("The number is Smaller!!")
else:
print("The number is Bigger!!")
#Get the spelling of the "attempt" word
if attempts == 1:
attempt_word = " attempt"
else:
attempt_word = " attempts"
#Display the result
if guess_number == answer:
print("Congratulations!! You did it in " + str(attempts) + attempt_word)

While Loop Stopping

The Code is working, but after 2 trys of the code it will just stop, this is in the section of playagain() when im asking the yes or no question it will display the error but will stop after the trys am i doing it wrong?
import random
import time
import getpass
import sys
def game1():
number = (input("Please Enter Your 3 Digit Code e.g.(0 0 1): "))
if number.isnumeric(): #if its a number
counter = 0
x = True
L = 1
H = 100
while x == True:
time.sleep(0.5)
randomguess = random.randint(L,H)
print("%03d"%randomguess)
if randomguess > int(number):
print("The Passcode is lower")
H = randomguess
elif randomguess < int(number):
print("The Passcode is higher")
L = randomguess
else:
print("The Passcode is Equal")
x = False
counter = counter + 1
if randomguess == int(number):
print("Well Done the Prisoner has Escaped, he did it in",counter,"trys")
return playagain()
if counter > 9:
print("The Prisoner get it wrong",counter,"times he is locked in, Well Done Jailer")
return playagain()
else:
print("This is Invalid, Please Provide a 3 Digit Code")
#This is the Section just for Reference
def playagain():
playagain = input("Do you wish to play again (yes/no): ")
if playagain == "yes":
print("You chose to play again")
return game1()
elif playagain == "no":
print("So you let the prisoner escape, thats it your fired")
time.sleep(2)
print("Thanks for Playing")
time.sleep(2)
#quit("Thanks for Playing") #quit game at this point
sys.exit()
else:
print("Please choose a valid option")
return
Here's a cleaned-up version:
from random import randint
from time import sleep
DELAY = 0.5
def get_int(prompt, lo=None, hi=None):
while True:
try:
val = int(input(prompt))
if (lo is None or lo <= val) and (hi is None or val <= hi):
return val
except ValueError:
# not an int, try again
pass
def get_yn(prompt):
while True:
yn = input(prompt).strip().lower()
if yn in {"y", "yes"}:
return True
elif yn in {"n", "no"}:
return False
def game(tries=100):
code = get_int("Please enter a 3-digit number (ie 091): ", 0, 999)
lo, hi = 0, 999
for attempt in range(1, tries+1):
sleep(DELAY)
guess = randint(lo, hi)
if guess < code:
print("Guessed {:03d} (too low!)".format(guess))
lo = guess + 1
elif guess > code:
print("Guessed {:03d} (too high!)".format(guess))
hi = guess - 1
else:
print("{:03d} was correct! The prisoner escaped on attempt {}.".format(guess, attempt))
return True
print("The prisoner failed to escape!")
return False
def main():
while True:
game()
if get_yn("Do you want to play again? "):
print("You chose to play again.")
else:
print("Alright, bye!")
break
if __name__=="__main__":
main()
def game1():
number = (input("Please Enter Your 3 Digit Code e.g.(0 0 1): "))
if number.isnumeric(): #if its a number
counter = 0
x = True
L = 1
H = 100
while x == True:
time.sleep(0.5)
randomguess = random.randint(L,H)
print("%03d"%randomguess)
if randomguess > int(number):
print("The Passcode is lower")
H = randomguess
elif randomguess < int(number):
print("The Passcode is higher")
L = randomguess
else:
print("The Passcode is Equal")
x = False
counter = counter + 1
if randomguess == int(number):
print("Well Done the Prisoner has Escaped, he did it in",counter,"trys")
x = False
if counter > 9:
print("The Prisoner get it wrong",counter,"times he is locked in, Well Done Jailer")
x = False
else:
print("This is Invalid, Please Provide a 3 Digit Code")
playagain()
#This is the Section just for Reference
def playagain():
playagain = ""
while (playagain != "yes" or playagain != "no"):
playagain = input("Do you wish to play again (yes/no): ")
if playagain == "yes":
print("You chose to play again")
return game1()
elif playagain == "no":
print("So you let the prisoner escape, thats it your fired")
time.sleep(2)
print("Thanks for Playing")
time.sleep(2)
#quit("Thanks for Playing") #quit game at this point
sys.exit()
else:
print("Please choose a valid option")
game1()
See https://repl.it/B7uf/3 for a working example.
Games typically run in a game loop which you have implemented using while x = True. The gameloops exits when the game is over and then user is asked to restart it. The bugs you were experiencing were due to the gameloop prematurely exiting before the user could be asked to restart.
The code below above that problem. There are other things that could be updated to improve the flow, but will leave that to you.
Use try/catch blocks instead of boolean checks
Break the game loop out into a separate method

Trying to create bagel game in python

I am getting this error. Please help me explain the cause and the meaning of the error
Traceback (most recent call last):
File "E:\Python\bagels.py", line 61, in <module>
while len(guess) != NUMDIGITS or not isOnlyDigits(guess):
TypeError: object of type 'builtin_function_or_method' has no len()
I am doing lessons from invent with python and stuck on this lesson
https://inventwithpython.com/chapter11.html
here is my code
import random
def getSecretNum(numDigits):
numbers = list(range(10))
random.shuffle(numbers)
secretNum = ''
for i in range(numDigits):
secretNum += str(numbers[i])
return secretNum
def getClues(guess, secretNum):
if guess == secretNum:
return 'You got it!'
clue = []
for i in range(len(guess)):
if guess[i] == secretNum[i]:
clue.append('fermi')
elif guess[i] in secretNum:
clue.append('Pico')
if len(clue) == 0:
return 'Bagels'
clue.sort()
return ' '.join(clue)
def isOnlyDigits(num):
if num == '':
return False
for i in num:
if i not in '0 1 2 3 4 5 6 7 8 9'.split():
return False
return True
def playAgain():
print('Do you want to play again?(yes or no)')
return input().lower().startswith('y')
NUMDIGITS = 3
MAXGUESS = 10
print('I am thinking of a %s-digit number. Try to guess what it is.' %(NUMDIGITS))
print('here are some clues:')
print('When I say: That means:')
print(' Pico One digit is correct but in the wrong position.')
print(' Fermi One digit is correct and in right position.')
print(' Bagels No digit is correct.')
while True:
secretNum = getSecretNum(NUMDIGITS)
print('I have thought of a number. You have %s guesses to guess it' %(MAXGUESS))
numGuesses = 1
while numGuesses <= MAXGUESS:
guess = ''
while len(guess) != NUMDIGITS or not isOnlyDigits(guess):
print('Guess #%s: ' % (numGuesses))
guess = input
clue = getClues(guess, secretNum)
print(clue)
numGuesses ++ 1
if guess == secretNum:
break
if numGuesses > MAXGUESS:
print('You ran out of guesses. The answer was %s. ' %(secretNum))
if not playAgain():
break
In the while loop you overwrite guess with the builtin function input.
You need to call the input function (please notice the extra pair of parentheses).
while len(guess) != NUMDIGITS or not isOnlyDigits(guess):
print('Guess #%s: ' % (numGuesses))
guess = input()
The problem is here:
guess = input
clue = getClues(guess, secretNum)
guess is now a reference to input, which is a python built-in function (like the error said).
You might want to do
guess = int(input("please enter guess"))

Loop breaking every time in slot machine program

I'm trying to break the loop by saying
if deff <= int(total):
break
but the loop will break regardless of the input being negative or more than the total it will break the loop
any advice of what am i doing wrong?
P.S i know i will new a formula to decide if player won or lost. right now im just trying to figure out the first code before going there
first time on programming and teacher not helpful ):
def intro():
greeting()
print('How much money do you want to start with?')
print('Enter the starting amount of dollars.', end='')
total = int(input())
print('Your current total is '+ str(total)+'\n')
while True:
print('How much money do you want to bet (enter 0 to quit)?', end='');
# Bett will be the amount of money that the player will play with
bett = int(input())
if bett > int(total):
print('ERROR You don\'t have that much left')
if bett < int(0):
print('ERROR: Invalid bet amount\n')
if bett <= int(total)
break
# Function shows results of slot machine after handle being pulled
def random():
import random
num1 = random.randint(1, 5)
num2 = random.randint(1, 5)
num3 = random.randint(1, 5)
print('/---+---+---\ ')
print('|-'+ str (num1)+'-|-'+ str(num2) +'-|-'+ str (num3) +'-|')
print('\---+---+---/ ')
intro()
You need to use elif and else in the successive conditional tests:
bett = int(input())
if bett > total:
print('ERROR You don\'t have that much left')
elif bett < 0:
print('ERROR: Invalid bet amount\n')
else:
break
That way, only one of the statements in executed, instead of more or more.
NB:
It's not necessary to use theint() constructor all the time on something that is already an int
In this block:
if bett <= int(total)
break
You have a syntax error. Add a colon to the end of hte first line:
if bett <= int(total):
break
If it were me, I would use a while loop.
play = True
while play == True:
#all the code
#to be executed
#indented here
#
#Ask user if they want to continue playing
p = input("Play again?[y/n] ")
playAgain = str(p)
if playAgain == "y":
play = True
else:
play = False

Categories

Resources