Could not convert string to float in input - python

#My code should take a random between 1 and 100 and let you guess it.
#This part works, but I want to add the posibility to reveal the number and then is when I get the error "could not convert string to float"
def reveal(guess):
return secret_number
import random
secret_number = random.random()*100
guess = float(input("Take a guess: ")) #This is the input
while secret_number != guess :
if guess < secret_number:
print("Higher...")
elif guess > secret_number:
print("Lower...")
guess = float(input("Take a guess: ")) #This input is here in order for the program not to print Higher or Lower without ever stopping
else:
print("\nYou guessed it! The number was " ,secret_number)
if guess == "reveal": #This is where I "tried" to make the reveal thingy.
print ("Number was", secret_number)
input("\n\n Press the enter key to exit")
Any help would be a great service. Also I am only programming for just a few weeks so sorry if my code looks wrong.

If you want to use float number to compare, the game may be endless because a float number has many fractional digits. Use int number.
#!/usr/bin/env python3.3
# coding: utf-8
import random
def guess_number():
try:
guess = int(input("Take a guess:"))
except ValueError:
print("Sorry, you should input a number")
guess = -1
return guess
if __name__ == '__main__':
secret_number = int(random.random() * 100)
while True:
guess = guess_number()
if guess == -1:
continue
elif guess < secret_number:
print("Lower...")
elif guess > secret_number:
print("Higher...")
else:
print("\nYou got it! The number was ", secret_number)
input("\n\nPress any key to exit.")
break # or 'import sys; sys.exit(0)'

import random
LOWEST = 1
HIGHEST = 100
def main():
print('Guess the secret number between {} and {}!'.format(LOWEST, HIGHEST))
secret = random.randint(LOWEST, HIGHEST)
tries = 0
while True:
guess = raw_input('Your guess: ').strip().lower()
if guess.isdigit():
tries += 1
guess = int(guess)
if guess < secret:
print('Higher!')
elif guess > secret:
print('Lower!')
else:
print('You got it in {} tries!'.format(tries))
break
elif guess == "reveal":
print('The secret number was {}'.format(secret))
break
else:
print('Please enter a number between {} and {}'.format(LOWEST, HIGHEST))
if __name__=="__main__":
main()

Use random.range instead of random.random.
secret_number = random.range(1,100,1)
And ...,str(secret_number)
...
else:
print("\nYou guessed it! The number was " ,str(secret_number))
if guess == "reveal": #This is where I "tried" to make the reveal thingy.
print ("Number was", str(secret_number))
...
That way you will be concatenating a string with a string. Also, you can keep random.random and only make the second change.
EDIT:
Another thing to do is to use raw_input instead of input. Then use try.
guess = raw_input("Take a guess: ")
try:
guess = float(guess)
except:
pass
This will try to convert guess into a float, and it that fails, then it will remain a string. That should solve your problem.

You could isolate concerns by defining a function that asks user for input until a float is provided:
def input_float(prompt):
while True:
try:
return float(input(prompt))
except ValueError:
print("You should input a float number. Try again.")
Then you could use it in your script:
guess = input_float("Take a guess: ")
If you want to accept 'reveal' as an input in addition to a float number:
def input_float_or_command(prompt, command='reveal'):
while True:
s = input(prompt)
if s == command:
return s
try:
return float(s)
except ValueError:
print("You should input a float number or %r. Try again." % command)

Related

Why does my Python user input code not consider the input correct

I am new to coding and want to train and do my own thing with user inputs. The User Input code does not work. It is a number guessing game. When I guess the right number, it says "Incorrect".
import random
while True:
intro = input("Hello! Want to play a game?(Y or N)")
if intro.lower() == "y" or intro.lower() == "yes":
time.sleep(0.1)
print("Let's play a number-guessing game!")
max_num_in = input("Pick a big number")
max_num = int(max_num_in)
time.sleep(0.1)
min_num_in = input("Now pick a smaller number")
min_num = int(min_num_in)
rndm_num = int(random.randrange(min_num,max_num,1))
print(rndm_num)
rndm_in = input("Guess a number between the maximum and minumum numbers!")
if rndm_num == rndm_in:
print("Whoo hoo! You did it! You guessed the number! The number was" + str(rndm_num))
elif rndm_in != rndm_num:
print("Whoops, wrong number. Please try again.(Trials left = 2)")
rndm_in1 = input("Guess again!")
if rndm_in1 == rndm_num:
print("Whoo hoo! You did it! You guessed the number! The number was" + str(rndm_num))
elif rndm_in1 != rndm_num:
print("You didn't get it right. Please try again (Trials left = 1)")
rndm_in2 = input("Guess again!")
if rndm_in2 == rndm_num:
print("Whoo Hoo! You finally did it! The number was" + str(rndm_num))
elif rndm_in2 != rndm_num:
print("Incorrect. The number was " + str(rndm_num))
elif intro.lower() == "n" or intro.lower() == "no":
print("Alright. Bye")
Your inputs are strings convert them to int by using int() function
"5"!=5
This one looks suspicious:
if rndm_num == rndm_in:
It looks like you getting a str as rndm_in but your rndm_num is an int.
Try:
if rndm_num == int(rndm_in):

How do I correctly use isinstance() in my random number guessing game or is another function needed?

I want this number guessing game to be able to catch every possible exception or error the user enters. I've successfully prevented the use of strings when guessing the number, but I want the console to display a custom message when a float is entered saying something along the lines of "Only whole numbers between 1-20 are allowed". I realize my exception would work to catch this kind of error, but for learning purposes, I want to specifically handle if the user enters a float instead of an int. From what I could find online the isinstance() function seemed to be exactly what I was looking for. I tried applying it in a way that seemed logical, but when I try to run the code and enter a float when guessing the random number it just reverts to my generalized exception. I'm new to Python so if anyone is nice enough to assist I would also appreciate any criticism of my code. I tried making this without much help from the internet. Although it works for the most part I can't get over the feeling I'm being inefficient. I'm self-taught if that helps my case lol. Here's my source code, thanks:
import random
import sys
def getRandNum():
num = random.randint(1,20)
return num
def getGuess(stored_num, name, gameOn = True):
while True:
try:
user_answer = int(input("Hello " + name + " I'm thinking of a number between 1-20. Can you guess what number I'm thinking of"))
while gameOn:
if user_answer >= 21 or user_answer <=0:
print("That is not a number between 1-20. Try again.")
user_answer = int(input())
elif isinstance(user_answer, int) != True:
print("Only enter whole numbers. No decimals u cheater!")
user_answer = int(input())
elif user_answer > stored_num:
print("That guess is too high. Try again " + name + " !")
user_answer = int(input())
elif user_answer < stored_num:
print("That guess is too low. Try again " + name + " !")
user_answer = int(input())
elif user_answer == stored_num:
print("You are correct! You win " + name + " !")
break
except ValueError:
print("That was not a number, try again")
def startGame():
print("Whats Your name partner?")
name = input()
stored_num = getRandNum()
getGuess(stored_num, name)
def startProgram():
startGame()
startProgram()
while True:
answer = input("Would you like to play again? Type Y to continue.")
if answer.lower() == "y":
startProgram()
else:
break
quit()
The only thing that needs be in the try statement is the code that checks if the input can be converted to an int. You can start with a function whose only job is to prompt the user for a number until int(response) does, indeed, succeed without an exception.
def get_guess():
while True:
response = input("> ")
try:
return int(response)
except ValueError:
print("That was not a number, try again")
Once you have a valid int, then you can perform the range check to see if it is out of bounds, too low, too high, or equal.
# The former getGuess
def play_game(stored_num, name):
print(f"Hello {name}, I'm thinking of a number between 1-20.")
print("Can you guess what number I'm thinking of?")
while True:
user_answer = get_guess()
if user_answer >= 21 or user_answer <=0:
print("That is not a number between 1-20. Try again.")
elif user_answer > stored_num:
print(f"That guess is too high. Try again {name}!")
elif user_answer < stored_num:
print(f"That guess is too low. Try again {name}!")
else: # Equality is the only possibility left
print("You are correct! You win {name}!")
break

Function in Python game not breaking and won't continue to next function

For a class we have to make a game where a person will enter an upper integer and a lower integer for a range. Then a random number is picked from in between those two numbers. The player would then guess a number and the game would end when you guessed the right number. In the function for my range I have a loop that will only end when you enter a correct range. It will then clear the console and continue to the guessing part of the game. The problem is once you enter a correct range it will clear the screen, then execute the wrong part of the loop and make it impossible to continue. What I have programmed so far is below, I started Python about 2 months ago.
**import time, os, random
#The beginning where you enter a range
def game_loop():
got_an_int = False
while got_an_int == False:
user_input1 = input("Enter the upper bound integer of the range: ")
user_input2 = input('Enter the lower bound integer of the range: ')
try:
user_input1 = int(user_input1)
user_input2 = int(user_input2)
print("Good job, that is a correct range.")
got_an_int = True
clear()
break
except:
print("That is not a correct range. Try again.")
#To continue after entering a correct range
def clear():
time.sleep(3)
os.system('clear')
time.sleep(1)
game_begin()
#Random Number Generator
def random_num(a,b):
random.randint(user_input1,user_input2)
#Where you begin the game
def game_begin():
guess_right = False
random_num = random_num(user_input1,user_input2)
while random_num != guess_right:
guess = input('Guess an integer in your range: ')
total_guess = [] + 1
try:
guess = int(guess)
if random_num > guess:
print("Too Low.")
guess_right = False
if random_num < guess:
print('Too High.')
guess_right = False
guess = int(guess)
if random_num == guess:
print("You got it! Good job.")
guess_right = True
the_end()
except:
print("That is not an int. Try again")**
You've got multiple problems, but the most glaring one is a combination of a few things:
random_num = random_num(user_input1, user_input2)
First, this line re-assigns the random_num symbol to be the result of calling random_num. After this line happens, any future calls to random_num won't work, because the function is "gone". Second, both user_input1 and user_input2 are not in scope in the game_begin function (they belong to the game_loop function).
Both of these problems are hidden because you're using "naked" excepts:
try:
...
except:
print(...)
You should only catch the Exceptions you're expecting and handle them appropriately, or make it so those exceptions won't happen.
In the end, I was able to get it to mostly work with the following. Additional problems I encountered are mentioned in the comments.
import time, os, random
def game_loop():
got_an_int = False
while got_an_int == False:
user_input1 = input("Enter the upper bound integer of the range: ")
user_input2 = input('Enter the lower bound integer of the range: ')
try:
user_input1 = int(user_input1)
user_input2 = int(user_input2)
print("Good job, that is a correct range.")
got_an_int = True
clear()
# Move game_begin call here and use parameters, so that randint call works
game_begin(user_input1, user_input2)
break
except:
print("That is not a correct range. Try again.")
def clear():
time.sleep(3)
os.system('clear')
time.sleep(1)
# Remove this - not needed
# def random_num(a,b):
# random.randint(user_input1,user_input2)
def game_begin(in1, in2):
guess_right = False
# No longer overwriting variable/func symbol
# Also, reverse order since range is taken Highest first then Lowest
random_num = random.randint(in2, in1)
# Initialize total_guess to 0
total_guess = 0
while random_num != guess_right:
guess = input('Guess an integer in your range: ')
# Can't add list and ints. I assume you wanted to keep a running total?
# Lists aren't how you would do that.
total_guess += 1
try:
guess = int(guess)
if random_num > guess:
print("Too Low.")
guess_right = False
if random_num < guess:
print('Too High.')
guess_right = False
guess = int(guess)
if random_num == guess:
print("You got it! Good job.")
guess_right = True
# This function doesn't exist, so the loop won't ever actually end
# NameError exception is raised
the_end()
except:
print("That is not an int. Try again")

Random number guessing game throws error: > or < cannot be used between str and int

I have the following code for a random number guessing game:
import random
number = random.randint(1,100)
name = input('Hi, Whats your name?')
print ("Well", name, "i am thinking of a number between 1 and 100, take a guess")
guess1 = input()
if guess1 == number:
print ("Good job, you got it!")
while guess1 != number:
if guess1 > number:
print ('your guess is too high')
if guess1 < number:
print ('your guess is too low')
which throws the error that > or < cannot be used between str and int.
What should I do so it doesn't trigger that error?
There are two errors in your code.
You need to convert the input for guess1 from a string (by default) to an integer before you can compare it to the number (an integer).
The while loop will never stop since you are not letting the user input another value.
Try this:
import random
number = random.randint(1,100)
name = input('Hi, Whats your name?')
print ("Well", name, "i am thinking of a number between 1 and 100, take a guess")
guess1 = int(input()) # convert input from string to integer
while guess1 != number:
if guess1 > number:
print ('your guess is too high. Try again.')
elif guess1 < number:
print ('your guess is too low. Try again.')
guess1 = int(input()) # asks user to take another guess
print("Good job, you got it!")
You can make use of a while loop here - https://www.tutorialspoint.com/python/python_while_loop.htm
The logic should be:
answer_is_correct = False
while not answer_is_correct :
Keep receiving input until answer is correct
I hope this works for you:
import random
myname = input('Hello, what is your name?')
print('Well',myname,'am thinking of a number between 1 and 100')
number = random.randint(1,100)
guess = 0
while guess < 4:
guess_number = int(input('Enter a number:'))
guess += 1
if guess_number < number:
print('Your guess is to low')
if guess_number > number:
print('Your guess is to high')
if guess_number == number:
print('Your guess is correct the number is',number)
break
if guess == 4:
break
print('The number i was thinking of is',number)
from random import randint
print("you wanna guess a number between A to B and time of guess:")
A = int(input("A:"))
B = int(input("B:"))
time = int(input("time:"))
x = randint(1, 10)
print(x)
while time != 0:
num = int(input("Enter: "))
time -= 1
if num == x:
print("BLA BLA BLA")
break
print("NOPE !")
if time == 0:
print("game over")
break
Code in Python 3 for guessing game:
import random
def guessGame():
while True:
while True:
try:
low, high = map(int,input("Enter a lower number and a higher numer for your game.").split())
break
except ValueError:
print("Enter valid numbers please.")
if low > high:
print("The lower number can't be greater then the higher number.")
elif low+10 >= high:
print("At least lower number must be 10 less then the higher number")
else:
break
find_me = random.randint(low,high)
print("You have 6 chances to find the number...")
chances = 6
flag = 0
while chances:
chances-=1
guess = int(input("Enter your guess : "))
if guess<high and guess>low:
if guess < find_me:
print("The number you have entered a number less then the predicted number.",end="//")
print("{0} chances left.".format(chances))
elif guess > find_me:
print("The number you have entered a number greater then the predicted number.",end="//")
print("{0} chances left.".format(chances))
else:
print("Congrats!! you have succesfully guessed the right answer.")
return
else:
print("You must not input number out of range")
print("{0} chances left.".format(chances))
print("The predicted number was {0}".format(find_me))
You can conditions within the while loop to check if its right. It can be done the following way.
import random
print('Hello! What is your name?')
myName = input()
number = random.randint(1, 100)
print('Well, ' + myName + ', I am thinking of a number between 1 and 100.')
inputNumber = int(raw_input('Enter the number')
while inputNumber != number:
print "Sorry wrong number , try again"
inputNumber = int(raw_input('Enter the number')
print "Congrats!"
from random import *
def play_game():
print("Let's play a number guessing game")
# Selecting a random number between 1 and 100
number = randint(1, 100)
choice = int(input("I am thinking of a number between 1 and 100. Could you guess what it is? "))
# Guide the user towards the right guess
# Loop will continue until user guesses the right number
while choice != number:
if choice < number:
choice = int(input("Too low. Can you try again? "))
elif choice > number:
choice = int(input("Too high. Can you try again? "))
continue_game = input("You guessed it right! Would you like to play it again? (Y/N) ")
# Restart the game if user wishes to play again
if continue_game == "Y":
print("--" * 42)
play_game()
else:
print("Thanks for playing :)")
exit(0)
play_game()

Python - Checking for an empty input + script troubles

I am very knew to Python, so as expected, I'm encountering problems often when scripting and am usually not sure how to fix them.
I'm making a small game where you try and guess a number which the program has randomly chosen. I've gotten pretty far, but I noticed the program simply displayed an error message when I input nothing. I would like the program to display the text "Enter a number." in this situation, and then prompt the "Your guess: " input again, but after a lot of research, I'm really not sure how to successfully implement that feature into my code. My issue, specifically, is the "try and except" section - I don't really know how to write them properly, but I saw another post on here suggesting to use them.
import random
def question():
print("Guess a number between 1 and 100.")
randomNumber = random.randint(1, 100)
found = False
while not found:
myNumber = int(input("Your guess: "), 10)
try:
myNumber = int(input("Your guess: "), 10)
except ValueError:
print("Enter a number.")
if myNumber == randomNumber:
print("Correct!")
found = True
elif myNumber > randomNumber:
print("Wrong, guess lower!")
else:
print("Wrong, guess higher!")
question()
You should be able to see my intentions in the code I've written, thanks.
You're almost right. Just continue to the next iteration after handling exception.
import random
def question():
print("Guess a number between 1 and 100.")
randomNumber = random.randint(1, 100)
found = False
while not found:
try:
myNumber = int(input("Your guess: "), 10)
except Exception:
print('Enter a number.')
continue
if myNumber == randomNumber:
print("Correct!")
found = True
elif myNumber > randomNumber:
print("Wrong, guess lower!")
else:
print("Wrong, guess higher!")
question()
You can write a function like this:
def input_num(input_string):
""" This function collects user input
Args:
input_string: message for user
Return:
user_input: returns user_input if it is a digit
"""
user_input = raw_input("{}: ".format(input_string))
if not user_input.isdigit():
input_num(input_string)
return int(user_input)
then call this function
user_num = input_num("Enter a number")
It will keep asking a user to provide a valid input until user puts one
I'm confused why you ask for the input twice. You only need to ask them for input once. After that, you need to add a continue to your except statement. Otherwise, it will not repeat and just end the program. This is what your modified while loop should look like.
while not found:
try:
myNumber = int(input("Your guess: "), 10)
except ValueError:
print("Enter a number.")
continue
if myNumber == randomNumber:
print("Correct!")
found = True
elif myNumber > randomNumber:
print("Wrong, guess lower!")
else:
print("Wrong, guess higher!")
Just use the continue keyword in your except to continue the loop.
except ValueError:
print('Enter a number')
continue

Categories