Exception if user enters a string instead of an integer [duplicate] - python

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 : "))

Related

How to create a exception for a while loop to repeat a input [duplicate]

This question already has answers here:
Asking the user for input until they give a valid response
(22 answers)
Closed 5 months ago.
I am trying to get this bit of code to work to validate the following input. I want to only accept inputs 1,2,or 3. Here is what I have so far:
number = int(input('Enter a number:'))
done = False
while not done:
try:
if number < 3:
done = True
except:
number = input("Please enter a valid number:")
The expected out put that I want if the input to loop until I get either 1,2, or 3.
Right now it won't do anything to when I input something greater than three. I want to use this number as an input to another function. Any help would be great of if you need more information please let me know!
Try this
number = int(input('Enter a number:'))
done = False
while not done:
if number <= 3:
done = True
else:
number = int(input("Please enter a valid number:"))
except block only run when there is an error in try block code.
Use if-else statement.
You can use this one too.
number = int(input('Enter a number:'))
done = False
while number>3:
number = int(input('Please enter a valid number:'))

Getting two inputs in one line, and how to let the code run even if the user gives only one input? [duplicate]

This question already has answers here:
Two values from one input in python? [duplicate]
(19 answers)
Closed 2 years ago.
I want to use one line to get multiple inputs, and if the user only gives one input, the algorithm would decide whether the input is a negative number. If it is, then the algorithm stops. Otherwise, the algorithm loops to get a correct input.
My code:
integer, string = input("Enter an integer and a word: ")
When I try the code, Python returns
ValueError: not enough values to unpack (expected 2, got 1)
I tried "try" and "except", but I couldn't get the "integer" input. How can I fix that?
In order to get two inputs at a time, you can use split(). Just like the following example :
x = 0
while int(x)>= 0 :
try :
x, y = input("Enter a two value: ").split()
except ValueError:
print("You missed one")
print("This is x : ", x)
print("This is y : ", y)
I believe the implementation below does what you want.
The program exits only if the user provides a single input which is a negative number of if the user provides one integer followed by a non-numeric string.
userinput = []
while True:
userinput = input("Enter an integer and a word: ").split()
# exit the program if the only input is a negative number
if len(userinput) == 1:
try:
if int(userinput[0]) < 0:
break
except:
pass
# exit the program if a correct input was provided (integer followed by a non-numeric string)
elif len(userinput) == 2:
if userinput[0].isnumeric() and (not userinput[1].isnumeric()):
break
Demo: https://repl.it/#glhr/55341028

"if" statement not working on input variable [duplicate]

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

Python check if input number is string [duplicate]

This question already has answers here:
How can I read inputs as numbers?
(10 answers)
Closed 4 years ago.
When I run the below code, it always returns Number please no matter what I enter. Why does this happen?
number = input("please type number: ")
if type(number) != int:
print('Number please')
else:
print('number')
Try this, this should work:
string = input()
if string.isalpha():
print("It is a string. You are correct!")
elif string.isdigit():
print("Please enter a string.")
else:
print("Please enter a proper string.")
The .isalpha is used for checking if it's a string. The .isdigit is used for checking if it's a number.
Hope it helps :)

Python IF ELSE statement not working [duplicate]

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.

Categories