How do i convert the input into an int? - python

I tried using int() to convert the input into int, but I just get a TypeError: int() argument must be a string, a bytes-like object or a number, not 'NoneType'. How do i solve this?
import random
number = random.randint(1, 50)
lives = 10
guess = int(print("Enter a number between 1 and 50: "))
while guess != number and lives != 0:
if guess > number:
guess = int(print("Your guess is higher than the secret number. Enter another guess: "))
lives -= 1
else:
guess = int(print("Your guess is lower than the secret number. Enter another guess: "))
lives -= 1
if guess == number:
print("You win!")
else:
print("You lose!")

Doesn't print() just show some text?
Try using:
guess = int(input("Enter a number between 1 and 50: "))
https://www.geeksforgeeks.org/taking-input-in-python/

guess = int(input("Enter a number between 1 and 50: "))
By default input takes everything as a string. And we convert the type afterwards.

guess = int(print("Enter a number between 1 and 50: ")) is wrong.
it should be
guess = int(input('enter a number between 1 and 50: '))

You are attempting to cast the output of print() to int when, as the error message suggests, print() outputs None.
If you replace the line 6 "print" with "input" your code will work (as seems expected) with python 3.

Related

Input validation for number guessing game results in error

This is my first post in this community and I am a beginner of course. I look forward to the day I can help others out. Anyway, this is the a simple code and I would like it so that there is an error if the user enters a string. Unfortunately, it does not execute the way I'd like to, here's the code:
number = 1
guess = int(input('Guess this number: '))
while True:
try:
if guess > number:
print("Number is too high, go lower, try again")
guess = int(input('Guess this number: '))
elif guess < number:
print("Too low, go higher, try again")
guess = int(input('Guess this number: '))
else:
print("That is correct")
break
except (SyntaxError, ValueError):
print("You can only enetr numbers, try again")
When the program gets executed, and it asks me to "Guess this number: ", when I write any string e.g. "d", it gives the error:
Guess this number: d
Traceback (most recent call last):
File "Numberguess.py", line 5, in <module>
guess = int(input('Guess this number: '))
ValueError: invalid literal for int() with base 10: 'd'
Thank you for your time and support.
Welcome to Stack Overflow! Everyone needs to start somewhere
Take a look at the code below:
# import random to generate a random number within a range
from random import randrange
def main():
low = 1
high = 100
# gen rand number
number = gen_number(low, high)
# get initial user input
guess = get_input()
# if user did not guess correct than keep asking them to guess
while guess != number:
if guess > number:
print("You guessed too high!")
guess = get_input()
if guess < number:
print("You guess too low!")
guess = get_input()
# let the user know they guess correct
print(f"You guessed {guess} and are correct!")
def gen_number(low, high):
return randrange(low, high)
# function to get input from user
def get_input():
guess = input(f"Guess a number (q to quit): ")
if guess == 'q':
exit()
# check to make sure user input is a number otherwise ask the user to guess again
try:
guess = int(guess)
except ValueError:
print("Not a valid number")
get_input()
# return guess if it is a valid number
return guess
# Main program
if __name__ == '__main__':
main()
This was a great opportunity to include Python's random module to generate a random number within a range. There is also a nice example of recursion to keep asking the user to guess until they provide valid input. Please mark this answer as correct if this works and feel free to leave comments if you have any questions.
Happy Coding!!!
Take a look at this line:
guess = int(input('Guess this number: '))
You try to convert string to int, it's possible, but only if the string represents a number.
That's why you got the error.
The except didn't worked for you, because you get the input for the variable out of "try".
By the way, there is no reason to input in the if, so your code should look like this:
number = 1
while True:
try:
guess = int(input('Guess this number: '))
if guess > number:
print("Number is too high, go lower, try again")
elif guess < number:
print("Too low, go higher, try again")
else:
print("That is correct")
break
except (SyntaxError, ValueError):
print("You can only enetr numbers, try again")
I would just use .isdigit(). The string would be validated at that point and then you would turn it into an int if validation works.
guess = input('Guess this number: ')
if guess.isdigit():
guess = int(guess)
else:
print("You can only enter numbers, try again")
Also worth to mention that try/excepts are cool and they get the job done, but it's a good habit to try to reduce them to zero, instead of catching errors, validate data beforehand.
The next example would do it:
number = 1
while True:
# Step 1, validate the user choice
guess = input('Guess this number: ')
if guess.isdigit():
guess = int(guess)
else:
print("You can only enter numbers, try again")
continue
# Step 2, play the guess game
if guess > number:
print("Number is too high, go lower, try again")
elif guess < number:
print("Too low, go higher, try again")
else:
print("That is correct")
break
the problem is in the first line. when you convert the input from the user directly to int, when a user inputs a letter, the letter cannot be converted to int, which causes the error message you get.
to solve this you need to do
guess = input('Guess this number: ')
if not guess.isdigit():
raise ValueError("input must be of type int")

"while" logic operator makes program not work

I've been learning Python for about 4 days and I'm just dealing with my first problem.
import random
number=random.randint(1,10)
count=1
guess= int(input("Enter your guess between 1 and 10 : "))
while number != guess:
count = count + 1
if guess == number:
print("That is my number !")
while guess < number:
guess = int(input("Too low :( Guess again ! : "))
if guess == number:
print("That is my number !")
while guess > number:
guess = int(input("Too high :( Guess again ! : "))
if guess == number:
print("That is my number !")
My program just print only first input line and then nothing.
Enter your guess between 1 and 10 :
Why is that?
while number != guess:
count = count + 1
When I delete this two lines, it works perfectly.
In Python whitspace is significant, because the loop was not indented correctly, the your program did not work as expected. The corrected code looks like this:
import random
number = random.randint(1,10)
count = 1
guess = int(input("Enter your guess between 1 and 10 : "))
while number != guess:
count = count + 1
if guess == number:
print("That is my number !")
elif guess < number:
guess = int(input("Too low :( Guess again ! : "))
else:
guess = int(input("Too high :( Guess again ! : "))

Returning error when user inputs space into program [duplicate]

This question already has answers here:
ValueError: invalid literal for int() with base 10: 'stop'
(3 answers)
Closed 6 years ago.
Like many before me, I am brand new at this, so go easy if I haven't given all the information needed, and thank you in advance.
Before I start it's worth mentioning that the program itself is running fine, what i'm worried about is making sure I've thought of every possibly scenario. Here goes.
I'm receiving this error:
File "C:\Users\brand\Desktop\WIP Programs\Guess the number 31.July.py", line 15, in <module>
userGuess = int(input("I guess: "))
ValueError: invalid literal for int() with base 10: ' '
When I press the space bar for input, it returns this. I am not sure how to make it so that the program returns something useful, such as the ability to guess again. Here is my code, for reference:
import random
guessNum = 0
print("Welcome to the guess the number game! Please, tell me your name!")
user = input("My name is: ")
randNum = random.randrange(1, 10, 1) #Generates number
print("Okay, " + user + ", guess the random number, the range is 1 to 10.")
#Guessing phase
while guessNum < 3:
userGuess = int(input("I guess: "))
if userGuess > randNum:
print("Too high! Try again.")
guessNum = guessNum + 1
if userGuess < randNum:
print("Too low! Try again.")
guessNum = guessNum + 1
if userGuess == randNum:
print("Great! You guessed my number!")
break
else:
print("Please choose a valid answer.")
if userGuess == randNum:
print("If you would like to play again, please restart the program.")
if userGuess != randNum:
print("Nope. My number was: " + str(randNum))
If I have any unneeded or am lacking anything I should have, please feel free to correct me!
EDIT!
Going off of the first reply. I added .isdigit() into my code properly:
if (userGuess.isdigit()):
userGuess = input("I guess: ")
if userGuess > randNum:
print("Too high! Try again.")
guessNum = guessNum + 1
It keeps passing an exception saying that 'userGuess' is not defined. Fine! okay, So I define it in the beginning of my code next to user. Which upon running, returns
AttributeError: 'int' object has no attribute 'isdigit'
Also fine, so I add str(0) to userGuess to attempt a fix which then returns:
TypeError: unorderable types: str() > int()
It now lets me input a number, however I cannot figure out how to fix. Any advice?
When the user chooses a number, his input is returned as string.
Afterwards, you try to convert that string to an integer. This works fine for strings as "13" or "4", but doesn't for strings like " 3" or "2a". Therefore an exception is raised in such a case.
As workaround, you can check the string with the "isdigit()" method before converting it. That method will return True for strings containing only digits and False otherwise.
Your issue is that the line userGuess = int(input("I guess: ")) is converting to an integer value without checking if it's possible to do so. When it finds a character value, this will throw an exception since the conversion isn't possible.
You could prevent this with a try...catch but I think a better way is to use the isDigit() method to check if the value is only digits before you try and convert.
while guessNum < 3:
userGuess = input("I guess: ")
if (userGuess.isDigit()):
userGuess = int(userGuess)
if userGuess > randNum:
print("Too high! Try again.")
guessNum = guessNum + 1
...
if userGuess == randNum:
print("Great! You guessed my number!")
break
else:
print("Please choose a valid answer.")

I'm trying to write a number guessing game in python but my program isn't working

The program is supposed to randomly generate a number between 1 and 10 (inclusive) and ask the user to guess the number. If they get it wrong, they can guess again until they get it right. If they guess right, the program is supposed to congratulate them.
This is what I have and it doesn't work. I enter a number between 1 and 10 and there is no congratulations. When I enter a negative number, nothing happens.
import random
number = random.randint(1,10)
print "The computer will generate a random number between 1 and 10. Try to guess the number!"
guess = int(raw_input("Guess a number: "))
while guess != number:
if guess >= 1 and guess <= 10:
print "Sorry, you are wrong."
guess = int(raw_input("Guess another number: "))
elif guess <= 0 and guess >= 11:
print "That is not an integer between 1 and 10 (inclusive)."
guess = int(raw_input("Guess another number: "))
elif guess == number:
print "Congratulations! You guessed correctly!"
Just move the congratulations message outside the loop. You can then also only have one guess input in the loop. The following should work:
while guess != number:
if guess >= 1 and guess <= 10:
print "Sorry, you are wrong."
else:
print "That is not an integer between 1 and 10 (inclusive)."
guess = int(raw_input("Guess another number: "))
print "Congratulations! You guessed correctly!"
The problem is that in a if/elif chain, it evaluates them from top to bottom.
Move the last condition up.
if guess == number:
..
elif other conditions.
Also you need to change your while loop to allow it to enter in the first time. eg.
while True:
guess = int(raw_input("Guess a number: "))
if guess == number:
..
then break whenever you have a condition to end the game.
The problem is that you exit the while loop if the condition of guessing correctly is true. The way I suggest to fix this is to move the congratulations to outside the while loop
import random
number = random.randint(1,10)
print "The computer will generate a random number between 1 and 10. Try to guess the number!"
guess = int(raw_input("Guess a number: "))
while guess != number:
if guess >= 1 and guess <= 10:
print "Sorry, you are wrong."
guess = int(raw_input("Guess another number: "))
elif guess <= 0 and guess >= 11:
print "That is not an integer between 1 and 10 (inclusive)."
guess = int(raw_input("Guess another number: "))
if guess == number:
print "Congratulations! You guessed correctly!"

How to add a loop to my python guessing game?

So I am very new to python as I spend most of my time using HTML and CSS. I am creating a small project to help me practice which is a number guessing game:
guess_number = (800)
guess = int(input('Please enter the correct number in order to win: '))
if guess != guess_number:
print('Incorrect number, you have 2 more attempts..')
guess2 = int(input('Please enter the correct number in order to win: '))
if guess2 != guess_number:
print('Incorrect number, you have 1 more attempts..')
guess2 = int(input('Please enter the correct number in order to win: '))
if guess2 != guess_number:
print()
print('Sorry you reached the maximum number of tries, please try again...')
else:
print('That is correct...')
elif guess == guess_number:
print('That is correct...')
So my code currently works, when run, but I would prefer it if it looped instead of me having to put multiple if and else statements which makes the coding big chunky. I know there are about a million other questions and examples that are similar but I need a solution that follows my coding below.
Thanks.
Have a counter that holds the number of additionally allowed answers:
guess_number = 800
tries_left = 3
while tries_left > 0:
tries_left -= 1
guess = int(input('Please enter the correct number in order to win: '))
if guess == guess_number:
print('That is correct...')
break
else:
print('Incorrect number, you have ' + str(tries_left if tries_left > 0 else 'no') + ' more attempts..')
If you don't know how many times you need to loop beforehand, use a while loop.
correct_guess = False
while not correct_guess:
# get user input, set correct_guess as appropriate
If you do know how many times (or have an upper bound), use a for loop.
n_guesses = 3
correct_guess = False
for guess_num in range(n_guesses):
# set correct_guess as appropriate
if correct_guess:
# terminate the loop
print("You win!")
break
else:
# if the for loop does not break, the else block will run
print("Out of guesses!")
You will get an error, TypeError: Can't convert 'int' object to str implicitly if you go with the answer you have selected. Add str() to convert the tries left to a string. See below:
guess_number = 800
tries_left = 3
while tries_left > 0:
tries_left -= 1
guess = int(input('Please enter the correct number in order to win: '))
if guess == guess_number:
print('That is correct...')
break
else:
print('Incorrect number, you have ' + (str(tries_left) if tries_left > 0 else 'no') + ' more attempts..')

Categories