User input accepting str and int (python) - python-3.x

I am new to programming and trying to make the user input accept both integer and strings. I have tried the following coding.. but not sure where I am going wrong. Any suggestions?
noAdults = input("Please enter the number of adults:")
while noAdults.isalpha():
print("Number must be valid and >= 0")
if noAdults.isdigit() and noAdults < 0:
print("Error")
noAdults = input("Please enter the number of adults:")
ValueError: invalid literal for int() with base 10:
I am guessing there is a ValueError because I have used the variable noAdults with isalpha and is making an error because it is in an int?

You need to verify that the input string is valid integer before you can check if it is non-negative
while True:
noAdults = input("Please enter the number of adults:")
try:
noAdults = int(noAdults)
except ValueError:
print("Not a valid number")
continue
if noAdults >= 0:
break
else:
print("Number must be >= 0")

It's throwing the exception before you handle the bad case of string inputs, it fails on the first line. You can check isalpha() before attempting the int(), or you can catch the ValueError exception.
To expand on chepner's solution, with a few extra print lines to show you what is going on:
while True:
noAdults = input("Please enter the number of adults:")
try:
noAdults = int(noAdults)
except ValueError:
print("Not a valid number")
continue
if noAdults >= 0:
break
else:
print("Not greater than 0")
print(noAdults)
This is a fully working version in Python 3.

Related

Is there a possibility to add "less than" exception to this piece of code in Python?

I'm quite new to coding and I'm doing this task that requires the user to input an integer to the code. The function should keep on asking the user to input an integer and stop asking when the user inputs an integer bigger than 1. Now the code works, but it accepts all the integers.
while True:
try:
number = int(input(number_rnd))
except ValueError:
print(not_a_number)
else:
return number
You can do something like this:
def getPositiveInteger():
while True:
try:
number = int(input("enter an integer bigger than 1: "))
assert number > 1
return number
except ValueError:
print("not an integer")
except AssertionError:
print("not an integer bigger than 1")
number = getPositiveInteger()
print("you have entered", number)
while True:
# the input return value is a string
number = input("Enter a number")
# check that the string is a valid number
if not number.isnumeric():
print(ERROR_STATEMENT)
else:
if int(number) > 1:
print(SUCCESS_STATEMENT)
break
else:
print(NOT_BIGGER_THAN_ONE_STATEMENT)
Pretty simple way to do it, of course you must define ERROR_STATEMENT, SUCCESS_STATEMENT and NOT_BIGGER_THAN_ONE_STATEMENT to run this code as it is, I am using them as place-holder.

Why is my function returning 0 after a try-except clause?

This code works as intended if valid input is received the first time around. If the input received is incorrect, it will prompt you to try again, and when valid input is finally received it will go on to return 0.
def string_num_query():
string_num = 0
try:
string_num = int(input("Enter number of strings (1-6): "))
if string_num < 1 or string_num > 6:
print("Value must be between 1 and 6.")
string_num_query()
except ValueError:
print("User input must be a number.")
string_num_query()
return string_num
I've tried following the flow of it and just can't see where I've gone wrong. Any help is much appreciated!
Your recursive function isn't returning the value of the recursive call, but rather the hard-coded value of string_num each time.
But, you shouldn't be using recursion to implement a possibly infinite loop at all. Use a while loop instead and break out of the loop when the value of num is valid.
def string_num_query():
while True:
string_num = input("Enter number of strings (1-6): ")
try:
num = int(string_num)
except ValueError:
print("User input must be a number")
continue
if 1 <= num <= 6:
break
return num
def string_num_query():
string_num = 0
try:
string_num = int(input("Enter number of strings (1-6): "))
if string_num < 1 or string_num > 6:
print("Value must be between 1 and 6.")
return string_num_query()
except ValueError:
print("User input must be a number.")
return string_num_query()
return string_num

Is there a way to automatically input the value “1” when the user decides to press 'enter' without giving a value?

How do I pre-set the system to give the display the value '1' if they do not enter any value (i.e., user just press enter). I kept having the error whereby the system forces me to have a number.
def get_variance():
while True:
variance = input("Please enter variance which must be greater than 0! ")
try:
value = int(variance)
if value > 0:
print(f"Variance inserted is: {value}.")
break
else:
print("You have entered a value less than 0, try again!")
except ValueError:
print("Amount must be a number, try again")
get_variance()
You first :
pip install pynput
Then you can use the following code:
from pynput.keyboard import Key, Controller
def get_variance():
while True:
variance = input("Please enter variance which must be greater than 0! ")
keyboard = Controller()
keyss = "enter"
if keyss =='enter':
print('You must enter the number one')
else:
try:
value = int(variance)
if value > 0:
print(f"Variance inserted is: {value}.")
break
else:
print("You have entered a value less than 0, try again!")
except ValueError:
print("Amount must be a number, try again")
get_variance()
Yes. Using the EAFP strategy of "easier to ask forgiveness than permission".
while True:
try:
value = int(input("Enter something >>"))
if value > 0:
break
else:
continue
except EOFError:
value = 1
except ValueError:
continue

How to show invalid input

My task is:
Write a program that repeatedly prompts a user for integer numbers until the user enters 'done'. Once 'done' is entered, print out the largest and smallest of the numbers. If the user enters anything other than a valid number catch it with a try/except and put out an appropriate message and ignore the number. Enter 7, 2, bob, 10, and 4 and match the output below.
I want to ignore any invalid integer and print 'Invalid Output' message after calculating the maximum and minimum number.But it always prints the invalid message right after user input. How am i supposed to solve this?
Thanks in advance.
Code:
largest = None
smallest = None
while True:
num = input("Enter a number: ")
if num == "done":
break
try:
n = int(num)
except:
print('Invalid input')
if largest is None:
largest=n
elif n>largest:
largest=n
elif smallest is None:
smallest=n
elif n<smallest:
smallest=n
print("Maximum", largest)
print('Minimum', smallest)
You could store that invalid output as a boolean variable
largest = None
smallest = None
is_invalid=False
while True:
num = input("Enter a number: ")
if num == "done":
break
try:
n = int(num)
except:
is_invalid=True
if largest is None:
largest=n
elif n>largest:
largest=n
elif smallest is None:
smallest=n
elif n<smallest:
smallest=n
print("Maximum", largest)
print('Minimum', smallest)
if is_invalid:
print('Invalid Input')
This can be one solution
largest = None
smallest = None
errors = False
while True:
num = input('Please type a number : ')
if num == 'done':
break
try:
number = int(num)
#your logical operations and assignments here
except ValueError:
errors = True
continue
if errors:
print('Invalid input')
else:
print('Your Results')
Hope this helps :)
If you are familiar with lists,you can use list to solve your problem effectively,
here is a modified version of your code which uses list,
num1=[]
while True:
num = input("Enter a number: ")
num1.append(num)
if num == "done":
break
for i in num1:
try:
i = int(i)
except:
print('Invalid input:',i)
num1.remove(i)
print("Maximum", max(num1))
print('Minimum', min(num1))
output:
Enter a number: 34
Enter a number: 57
Enter a number: 89
Enter a number: ds
Enter a number: 34
Enter a number: do
Enter a number: done
Invalid input: ds
Invalid input: do
Maximum 89
Minimum 34
hope this helps,let me know if anything is incorrect.
Try removing the (int) in try block. Because you want only integer input in try block so if does not satisfy the condition of integer input it will execute the except block.
Your code should look like this in try block:
try:
n = num

How to check if a integer input is a string without valueError

while True:
Check = isinstance(Age, str)
Age = (int(input("Ok, How old are you: ")))
if 100 <= Age:
print("try again")
if Check == True:
print("try again")
else:
break
I'm trying to cause it to loop back through if the input is a string while printing "try again", but when I do this, it causes a ValueError
If you execute your code, the first error will be NameError, because you are using it before the input.
But if you want to check if the user input is a number without ValueError, you can use isdigit function. With a little modifications, you can achieve what you are trying to do with:
while True:
age = input("Ok, How old are you: ")
if age.isdigit() and int(age) <= 100:
break
print("try again")
The error comes in before your if check. You're casting the input to int which may not be possible, hence you're getting a ValueError.
You need to instead do something like:
while True:
age = input("How old are you?")
try:
age = int(age)
except ValueError:
print('try again')
continue
if age >= 100:
print('try again')
continue
break

Resources