What wrong with this code of the python programming? [duplicate] - python

This question already has answers here:
Asking the user for input until they give a valid response
(22 answers)
Closed 3 years ago.
I am new to python.
The following code should read an integer into the voting rating:
`rating = input('Enter an integer rating between 1 and 10')`
My doubt: The problem with the above code is it allows any values without error. How can I insert error message?

You can try to parse the string to an integer, and if you cannot, print accordingly, but if you can and the integer is between 1 and 10, decide accordingly
def check_int(s):
is_int = False
try:
int(s)
is_int = True
except:
pass
return is_int
rating = input('Enter an integer rating between 1 and 10>>')
#If string can be converted to integer
if check_int(rating):
#Convert it to an integer and compare ranges
r = int(rating)
if 1<=r<=10:
print('Integer is', r)
else:
print('Integer is not between 1 and 10')
#Else print error
else:
print('Not an integer')
The output will be
Enter an integer rating between 1 and 10>>11
Integer is not between 1 and 10
Enter an integer rating between 1 and 10>>6
Integer is 6
Enter an integer rating between 1 and 10>>hello
Not an integer

You use a function like this:
While the imput isn't correct, we ask a new input. We also check the input is an number with cast. If it's not a number, that will raise an exception that we catch in the try ... catch.
def getInputVal():
# Boolean equal to false while the input isn't correct
correct_answer = False
while (not correct_answer):
# Read the input (string)
val = input('Enter an integer rating between 1 and 10: ')
try: # Try to cast the string as an integer
val_int = int(val)
if (val_int >= 1 and val_int <= 10): # If the value is in the right interval
correct_answer = True # We go out of the loop
print("Well done, your value is: ", val_int) # We display the value
except: # If the cast raise an error
print("A number is expected") # An "error" message is shwon

Related

Validating int numbers in a certain range. Python-3.x [duplicate]

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 making this game where the user has to choose from 5 options. So, he must type any number from 1 to 5 to choose an option. Now here is the problem I am facing, I just can't figure out a way in which the user cannot type in any other character except the int numbers from 1 to 5, and if he does type in a wrong character, how should I show his error and make him type in the input again? Here is what I've tried:
def validateOpt(v):
try:
x = int(v)
if int(v)<=0:
x=validateOpt(input("Please enter a valid number: "))
elif int(v)>5:
x=validateOpt(input("Please enter a valid number: "))
return x
except:
x=validateOpt(input("Please enter a valid number: "))
return x
Here validateOpt is to validate the number for the option, i.e., 1,2,3,4,5. It works fine, but whenever I type 33,22, 55, or any other int number from 1 to 5 twice (not thrice or even four times, but only twice), it doesn't show any error and moves on, and that, I suppose, is wrong. I am just a beginner.
You can do this with a while loop, something like this should be a good start:
def getValidInt(prompt, mini, maxi):
# Go forever if necessary, return will stop
while True:
# Output the prompt without newline.
print(prompt, end="")
# Get line input, try convert to int, make None if invalid.
try:
intVal = int(input())
except ValueError:
intVal = None
# If valid and within range, return it.
if intVal is not None and intVal >= mini and intVal <= maxi:
return intVal
Then call it with something like:
numOneToFive = getValidInt("Enter a number, 1 to 5 inclusive: ", 1, 5)
use a while loop instead of recursion, you can check the user data and return if its valid, although you might want to consider a break out clause should the user want to exit or quit without a valid input.
def get_input(minimum, maximum):
while True:
try:
x = int(input(f"please enter a valid number from {minimum} to {maximum}: "))
if minimum <= x <= maximum:
return x
except ValueError as ve:
print("Thats not a valid input")
value = get_input(1, 5)
Use for loop in the range between 1 and 5
Try this code, it will keep prompting user till he enters 5, note that this may cause stackoverflow if recursion is too deep:
def f():
x = input("Enter an integer between 1 and 5:")
try:
x = int(x)
if x<=0 or x>5:
f()
except:
f()
f()

Making sure the user's input is not a string in Python 3 [duplicate]

This question already has answers here:
Asking the user for input until they give a valid response
(22 answers)
Closed 4 years ago.
I try to make a function that at first will check if the input is not a string.
But if the user inputs a float, it gets False.
I need it to accept both Int and Float, bot not a string.
def squat():
value = input("What is your RM1?")
if value.isnumeric():
rm1 = float(value)
print("Your RM1 is: ", rm1)
print(type(value))
else:
print("Error")
squat()
You may use a try..except block in your case
def squat():
value = input("What is your RM1?")
try:
rm1 = float(value)
except ValueError:
print("error")
exit(1)
The input() function always returns a string. You can use a regex to check if the string looks like number:
import re
value = input('What is your RM1? ')
if re.match(r'^\d+(\.\d+)?$', value):
rm1 = float(value)
print('Your RM1 is: ', rm1)
else:
print('Error')

How to check if number is string or integer in python using if else [duplicate]

This question already has answers here:
How can I type-check variables in Python?
(9 answers)
Closed 6 years ago.
I am new to Python (30 minutes). I want to know how to identify whether the number is an integer or a string, and proceed with the result using if else.
My code is:
number = input("enter the number \n")
integer = int(number)
if integer.is_integer():
if integer > 0:
print("positive ", integer)
elif integer < 0:
print("Negative ", integer)
else:
print("Number is", integer)
else:
print("Enter integer value")
number = input("enter the number \n")
try:
integer = int(number)
if integer > 0:
print "positive", integer
elif integer < 0:
print "Negative", integer
else:
print "Number is", integer
except ValueError:
print("Enter integer value")
Python provides doc-typing feature which means no matter if a value defined as a String or Number. So you must only check if the value conforms numerical properties or not using isnumeric(). This method returns true if all characters in the string are numeric, false otherwise.
str = u"hello100";
print str.isnumeric() #returns false
str = u"123900";
print str.isnumeric() #returns true

Python User input [duplicate]

This question already has answers here:
Asking the user for input until they give a valid response
(22 answers)
Closed 6 years ago.
I'm writing a game that prompts the user to input the number of rows. The problem I'm having is how do I get the program to keep prompting the user until they enters a whole number. If the user enters a letter or a float such as 2.5, the int value will not work, and thus I cannot break out of the loop. The program crashes. The int is essential so that I can check the number. The input must be even, it must be greater then or equal to 4 and less then equal to 16. Thanks!
def row_getter()->int:
while True:
rows=int(input('Please specify the number of rows:'))
if (rows%2 == 0 and rows>=4 and rows<=16):
return rows
break
You're on the right path, but you want to use a try/except block to try and convert the input to an integer. If it fails (or if the input is not in the given bounds), you want to continue and keep asking for input.
def row_getter()->int:
while True:
try:
rows=int(input('Please specify the number of rows:'))
except ValueError:
continue
else: # this runs when the input is successfully converted
if (rows % 2 == 0 and >= 4 and rows <= 16):
return rows
# if the condition is not met, the function does not return and
# so it continues the loop
I guess the pythonic way to do it would be:
while True:
try:
rows = int(input('Please specify the number of rows:'))
except ValueError:
print("Oops! Not an int...")
continue
# now if you got here, rows is a proper int and can be used
This idiom is called Easier to Ask Forgiveness than Permission (EAFP).
Could also make isint helper function for reuse to avoid the try/except in main parts of code:
def isint(s):
try:
int(s)
return True
except ValueError:
return False
def row_getter()->int:
while True:
s = input('Please specify the number of rows:')
if isint(s):
rows = int(s)
if (rows % 2 == 0 and rows >= 4 and rows <= 16):
return rows

Loop until an input is of a specific type [duplicate]

This question already has answers here:
Asking the user for input until they give a valid response
(22 answers)
How can I read inputs as numbers?
(10 answers)
Closed 6 months ago.
I'm trying to make a program that repeatedly asks an user for an input until the input is of a specific type. My code:
value = input("Please enter the value")
while isinstance(value, int) == False:
print ("Invalid value.")
value = input("Please enter the value")
if isinstance(value, int) == True:
break
Based on my understanding of python, the line
if isintance(value, int) == True
break
should end the while loop if value is an integer, but it doesn't.
My question is:
a) How would I make a code that would ask the user for an input, until the input is an integer?
b) Why doesn't my code work?
The reason your code doesn't work is because input() will always return a string. Which will always cause isinstance(value, int) to always evaluate to False.
You probably want:
value = ''
while not value.strip().isdigit():
value = input("Please enter the value")
Be aware when using .isdigit(), it will return False on negative integers. So isinstance(value, int) is maybe a better choice.
I cannot comment on accepted answer because of low rep.
input always returns a string, you have to convert it to int yourself.
Try this snippet:
while True:
try:
value = int(input("Please enter the value: "))
except ValueError:
print ("Invalid value.")
else:
break
If you want to manage negative integers you should use :
value = ''
while not value.strip().lstrip("-").isdigit():
value = input("Please enter the value")

Categories

Resources