This question already has answers here:
How can I read inputs as numbers?
(10 answers)
Closed 5 years ago.
import random
user_name=("enter your name:")
print("Note: The number lies between 1 to 100")
random_nuber = random.randrange(1, 100, 1)
user_number = input("enter your guess")
dif= user_number - random_nuber
while dif != 0:
if dif > 0:
print("high")
if dif < 0:
print("low")
user_number = input("enter your guess now :")
I am a beginner and everytime I use while or for loop, I get the same kind of error.
the error I get each time I run this code
input("enter your guess") is returning a string, so user_number - random_nuber won't work as they are different types - a number and a string.
EDIT: For anyone who's used to Python2, this normally tries to evaluate the string - so if you input a number, it automatically converts it to a number. In Python3 (as per the question), it is always a string and thus needs to be converted.
You need to convert the number into a string, either by changing it to an integer when you make it: user_number = int(input("enter your guess")), or by changing it when you need it in the operation: dif= int(user_number) - random_nuber
(Personally, I'd recommend the first option)
Related
This question already has answers here:
Asking the user for input until they give a valid response
(22 answers)
Closed 12 months ago.
I'm new to python and I am trying to figure out how do I enter an error message if the user inputs a number less than zero.
Here is my code to give you a better understanding and I thank you all in advance for any advice.
# Python Program printing a square in star patterns.
length = int(input("Enter the side of the square : "))
for k in range(length):
for s in range(length):
if(k == 0 or k == length - 1 or s == 0 or s == length - 1):
print('*', end = ' ')
else:
print('*', end = ' ')
print()
Here is a simple and straight forward way to use a while loop to achieve this. Simple setting an integer object of check to 0. Then the while loop will evaluate check's value, then take user input, if the user input is greater than 0, let's set out check object to 1, so when we get back to the top of the loop, it will end.
Otherwise, if the if check fails, it will print a quick try again message and execute at the top of the loop again.
check = 0
while check == 0:
length = int(input("Enter the side of the square : "))
if length > 0:
check = 1
else:
print("Please try again.")
You can use this code after the input statement and before for loop.
if length < 0 :
Print("invalid length")
Break
This question already has answers here:
Asking the user for input until they give a valid response
(22 answers)
Closed 2 years ago.
I am trying to make my program print(invalid input, try again) if the user types a string instead of an integer.
num_dice = 0
while True:
if num_dice < 3 or num_dice > 5 or num_dice:
num_dice = int(input("Enter the number of dice you would like to play with 3-5 : "))
print("")
print("Please enter a value between 3 and 5.")
print("")
continue
else:
break
You can simply use the isnumeric keyword to check if it is an absolute number or not.
Example:
string1="123"
string2="hd124*"
string3="helloworld"
if string1.isnumeric() is True:
#Proceed with your case.
inputs=string1
Documentation reference : https://www.w3schools.com/python/ref_string_isnumeric.asp
P.S. this will require you changing your input to string format, as isnumeric validates only string.
This below part I mean.
num_dice = str(input("Enter the number of dice you would like to play with 3-5 : "))
This question already has answers here:
How can I read inputs as numbers?
(10 answers)
Closed 4 years ago.
Well, I am a beginner and my variable (guess) input doesn't work with the if statement:
When I put on the input numbers from 0 to 9, I want it prints out Right number!, else it print out the other message:
guess = input("Choose a number between 0-9: ")
if guess <=9 and guess >=0:
print("Right number!")
else:
print("The number you entered is out of range try again!")
The input() function returns a string, not a number (e. g. "127", not 127). You have to convert it to a number, e. g. with the help of int() function.
So instead of
guess = input("Choose a number between 0-9: ")
use
guess = int(input("Choose a number between 0-9: "))
to obtain an integer in guest variable, not a string.
Alternatively you may reach it in 2 statements - the first may be your original one, and the second will be a converting one:
guess = input("Choose a number between 0-9: ")
guess = int(guess)
Note:
Instead of
if guess <=9 and guess >=0:
you may write
if 0 <= guess <= 9: # don't try it in other programming languages
or
if guess in range(10): # 0 inclusive to 10 exclusive
This question already has answers here:
How can I read inputs as numbers?
(10 answers)
Closed 6 years ago.
Here's my code, which executes a simple number guessing game:
i = 1
lower = input('Enter the lower range: ')
upper = input('Enter the upper range: ')
from random import randint
answer = randint(lower, upper)
guess = input("What's the number? ")
while guess != answer:
if ~(guess in range(lower, upper)):
print('Your guess must be in the range', lower, 'to', upper)
i = i - 1
elif guess < answer:
print('Too low!')
elif guess > answer:
print('Too high!')
guess = input("What's the number? ")
i = i + 1
print('Congrats! You correctly guessed the number to be ', answer, '! It took you ', i, ' tries.', sep='')
When I try to run it, the command prompt gives me the following error:
File "C:\Users\username\AppData\Local\Programs\Python\Python36-32\lib\random.py", line 220, in randint
return self.randrange(a, b+1)
TypeError: must be str, not int
EDIT: Thanks for the solutions, changing input(...) to int(input(...)) fixed my code. I'll also add that line 8 also contains an error. It should be: if not (guess in range(lower, upper + 1)):.
You need to convert the input to integer first:
lower = int(input('Enter the lower range: '))
upper = int(input('Enter the upper range: '))
To explain the error: The error message is a bit misleading since it says you need str instead of int and not the other way around. However, it comes from the fact that before the internal randrange function is executed, b is incremented, so you have for example '10'+1 and that generates this error.
You are taking your "numbers" from the input() function.
The input() is coming to you as a string. You need to convert it to numeric form using int(lower) before the values to randint().
(The error stems from the b+1 - randint is trying to do addition, but adding to a string is defined as concatenation, which requires two strings.)
This question already has an answer here:
Simple Python IF statement does not seem to be working
(1 answer)
Closed 6 years ago.
I have my first program I am trying to make using python. The IF ELSE statement is not working. The output remains "Incorrect" even if the correct number is inputted by the user. I'm curious if it's that the random number and the user input are different data types. In saying that I have tried converting both to int with no avail.
Code below:
#START
from random import randrange
#Display Welcome
print("--------------------")
print("Number guessing game")
print("--------------------")
#Initilize variables
randNum = 0
userNum = 0
#Computer select a random number
randNum = randrange(10)
#Ask user to enter a number
print("The computer has chosen a number between 0 and 9, you have to guess the number!")
print("Please type in a number between 0 and 9, then press enter")
userNum = input('Number: ')
#Check if the user entered the correct number
if userNum == randNum:
print("You have selected the correct number")
else:
print("Incorrect")
On Python 3 input returns a string, you have to convert to an int:
userNum = int(input('Number: '))
Note that this will raise a ValueError if the input is not a number.
If you are using Python 3, change the following line:
userNum = input('Number: ')
to
userNum = int(input('Number: '))
For an explanation, refer to PEP 3111 which describes what changed in Python 3 and why.