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
Related
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:
Asking the user for input until they give a valid response
(22 answers)
Closed 3 years ago.
I'm currently a few weeks into my first programming course. The language is Python and the assignment was to write a program that will take two numbers from user input and provide the sum. If the sum is >100, print a message saying it's a big number and don't print the value. If the sum is <100, add the two numbers the input provides and print the sum value.
Here's my code for that which seems to fit what the assignment asked for:
print("Please enter a number between 1 and 100: ")
num1 = int(input())
if num1 > 99:
print("That number is greater than 100. Please try again.")
elif num1 < 1:
print("That number is less than 1. Please try again.")
print("Again, please type any number between 1-100")
num2 = int(input())
if num2 > 99:
print("That number is greater than 100. Please try again.")
elif num2 < 1:
print("That number is less than 1. Please try again.")
sum = num1 + num2
if sum > 100:
print("They add up to a big number")
elif sum < 100:
print("Sum of ", num1, " and ", num2, " is = ", sum)
With this code however, if I for example input '0' as a value for example, it'll print to try again but of course proceed to the next instruction of num2.
In every programming assignment, the instructor gives bonus points for going the extra mile and learning on your own how to somehow better the code, which I always try and achieve. In this example, I'm trying to make it so that if I for example as stated above input the value '0', it'll print to try again and then loop back to the first input instruction rather than proceeding to num2.
I'm not looking for someone to do my homework, but rather a step in the right direction. I've done some research and am not sure what works best here, but it seems like a while loop might work? I'm unsure how to start implementing it with my code already existing.
In such cases it's better to use boolean flags.
bool lock = true;
while(lock):
print("Please enter a number between 1 and 100: ")
num1 = int(input())
if num1 > 99:
print("That number is greater than 100. Please try again.")
elif num1 < 1:
print("That number is less than 1. Please try again.")
else:
lock = false
It'll make sure that till the time a valid input is not entered the loop iterates and asks the user to input the same number again and again.
You could repeat it for the second number too.
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)
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.
This question already has an answer here:
Python Checking 4 digits
(1 answer)
Closed 1 year ago.
I want to write a program that only accepts a 4-digit input from the user.
The problem is that I want the program to accept a number like 0007 but not a number like 7 (because it´s not a 4 digit number).
How can I solve this? This is the code that I´ve wrote so far:
while True:
try:
number = int(input("type in a number with four digits: "))
except ValueError:
print("sorry, i did not understand that! ")
if number > 9999:
print("The number is to big")
elif number < 0:
print("No negative numbers please!")
else:
break
print("Good! The number you wrote was", number)
But if I input 7 to it it will just say Good! The number you wrote was 7
Before casting the user's input into an integer, you can check to see if their input has 4 digits in it by using the len function:
len("1234") # returns 4
However, when using the int function, Python turns "0007" into simple 7. To fix this, you could store their number in a list where each list element is a digit.
If it's just a matter of formatting for print purposes, modify your print statement:
print("Good! The number you wrote was {:04d}", number)
If you actually want to store the leading zeros, treat the number like a string. This is probably not the most elegant solution but it should point you in the right direction:
while True:
try:
number = int(input("Type in a number with four digits: "))
except ValueError:
print("sorry, i did not understand that! ")
if number > 9999:
print("The number is to big")
elif number < 0:
print("No negative numbers please!")
else:
break
# determine number of leading zeros
length = len(str(number))
zeros = 0
if length == 1:
zeros = 3
elif length == 2:
zeros = 2
elif length == 3:
zeros = 1
# add leading zeros to final number
final_number = ""
for i in range(zeros):
final_number += '0'
# add user-provided number to end of string
final_number += str(number)
print("Good! The number you wrote was", final_number)
pin = input("Please enter a 4 digit code!")
if pin.isdigit() and len(pin) == 4:
print("You successfully logged in!")
else:
print("Access denied! Please enter a 4 digit number!")