How to show invalid input - python-3.x

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

Related

Is there any better way to do User Input validation in Python3.x ? or Improve this block of code

I'm trying to validate multiple user inputs, can be of diff. data types.
Is there any better way to do User Input validation in Python3 ? or Improve this block of code.
def validate_number(message):
i = 0
while i < 4:
try:
userInput = int(input(message))
except ValueError:
i += 1
if i == 4:
print('Max try reached !!!')
return False
else:
print("Not an integer! Try again.")
continue
else:
return userInput
break
#------------------------------------------
a = validate_number('Enter 1st No: ')
if a:
b = validate_number('Enter 2nd No: ')
if a and b:
sum = a + b
print('Result is : %s' %(sum))
print('Result is : {} '.format(sum))
print(f'Result is : {sum}')
this is my suggestion:
def validate_number(message):
for i in range(4):
try:
return int(input(message))
except ValueError:
print("Not an integer! Try again.")
print("Max try reached !!!")
a simple for loop in order to count the number of tries.
as it is the function will return None if no valid input is given. you may have to tweak that according to your needs.

Python 3 Count and While Loop

I am trying to figure out an error in the code below. I need the following conditions to be met:
1) If equal to zero or lower, I need python to state "Invalid Input"
2) If greater than zero, ask whether there is another input
3) As long as there is another input, I need the program to keep asking
4) If "done", then I need Python to compute the lowest of inputs. I have not gotten to this part yet, as I am getting an error in the "done" portion.
print ("Lowest Score for the Racer.")
number = float(input("Please enter score: "))
if number < 0 or number == 0:
print ("Input should be greater than zero.")
while True:
number = float(input('Do you have another input? If "Yes" type another score, if "No" type "Done": '))
if number < 0 or number == 0:
print ("Input should be greater than zero. Please enter score: ")
if number == "Done":
print ("NEED TO COUNT")
break
I tried to modify your code according to your desired output. I think this should give you an idea. However there is still small things to deal in code. I suppose you can manage rest of it.
empthy_list = []
print ("Lowest Score for the Racer.")
while True:
number = float(input("Please enter score: "))
if number < 0 or number == 0:
print ("Input should be greater than zero.")
if number > 0:
empthy_list.append(number)
reply = input('Do you have another input? If "Yes" type another score, if "No" type "Done": ')
if reply == "Yes" :
number = float(input("Please enter score: "))
empthy_list.append(number)
if reply == "Done":
print("NEED TO COUNT")
print("Lowest input is: ",min(empthy_list))
break
I wrote an alternative solution which is more robust regarding input errors. It might include some ideas for improving your code but probably isn't the best solution, either.
print ("Lowest score for the racer.")
valid_input = False
num_arr = []
while not valid_input:
foo = input('Please enter score: ')
try:
number = float(foo)
if number > 0:
num_arr.append(number)
valid_input = True
else:
raise ValueError
while foo != 'Done' and valid_input:
try:
number = float(foo)
if number > 0:
num_arr.append(number)
else:
raise ValueError
except ValueError:
print('Invalid input! Input should be number greater than zero or
"Done".')
finally:
foo = input('Do you have another input? If yes type another score,
if no type "Done": ')
except ValueError:
print('Invalid input! Input should be number greater than zero.')
print("Input done! Calculating lowest score...")
print("Lowest score is ", min(num_arr))

collatz sequence infinte loop error

I am getting an infinite loop. I am not sure on how to covert the result as the new number variable and put it back in the while loop.
#Collatz squence
import sys
def collatz():
try:
print('Enter a number')
number = int(input())
except:
ValueError
print('Please type an integer')
while number != 1:
if number %2 == 0:
result = number//2
print(result)
elif number %2 == 1:
result = 3*number + 1
print(result)
**result = number**
while number == 1:
print ('You have arrived at the number itself')
sys.exit()
collatz()
The following works:
#Collatz squence
import sys
def collatz():
try:
print('Enter a number')
number = int(input())
except ValueError:
print('Please type an integer')
sys.exit(1)
while number != 1:
if number %2 == 0:
result = number//2
print(result)
elif number %2 == 1:
result = 3*number + 1
print(result)
number = result # set the number to the result
while number == 1:
print ('You have arrived at the number itself')
sys.exit()
collatz()
Notice that I set the number to the result, in your code the number never changed, and so kept hitting the same block of code over and over. I also added a sys.exit call in the exception, we don't want to continue if someone entered in a bad value.

If statement error: ValueError: invalid literal for int() with base 10: ' ' and out of order int()

My code is as follows:
allnums = []
odds = []
evens = []
number = 0
while True:
number = input("Enter a number or type 'done':")
if number.lower() == 'done':
print("=============================")
print("Your even numbers are", str(evens))
print("Your odds numbers are", str(odds))
print("=============================")
print("Your smallest number is '"+str(allnums[0])+"'")
break
if int(number) % 2 == 0:
evens.append(number)
evens.sort()
allnums.append(number)
allnums.sort()
if int(number) % 2 != 0:
odds.append(number)
odds.sort()
allnums.append(number)
allnums.sort()
else:
print("Invalid input")
I'm trying to create a program that reads a list of numbers and determines the lowest value, while also offering a list of even and odd numbers. I'm running into two issues with my code where the lowest number is not often correct, for example:
Enter a number or type 'done':33
Enter a number or type 'done':4
Invalid input
Enter a number or type 'done':6
Invalid input
Enter a number or type 'done':4
Invalid input
Enter a number or type 'done':6
Invalid input
Enter a number or type 'done':7
Enter a number or type 'done':44
Invalid input
Enter a number or type 'done':88
Invalid input
Enter a number or type 'done':done
=============================
Your even numbers are ['4', '4', '44', '6', '6', '88']
Your odds numbers are ['33', '7']
=============================
Your smallest number is '33'
I also get the following error when I use just a space(' ') as an answer, which I would like to write a print("Invalid input") response to something that is not a number or done, but always results in:
Traceback (most recent call last):
File "XXXX", line 17, in <module>
if int(number) % 2 == 0:
ValueError: invalid literal for int() with base 10: ' '
I know this has mostly to do with order of events, but what am I missing?
allnums = []
odds = []
evens = []
number = 0
while True:
try:
number = input("Enter a number or type 'done':")
if number.lower() == 'done':
print("=============================")
print("Your even numbers are", str(sorted(evens)))
print("Your odds numbers are", str(sorted(odds)))
print("=============================")
print("Your smallest number is '"+str(sorted(allnums)[0])+"'")
break
elif int(number) % 2 == 0:
evens.append(number)
#evens.sort()
allnums.append(number)
#allnums.sort()
elif int(number) % 2 != 0:
odds.append(number)
#odds.sort()
allnums.append(number)
#allnums.sort()
pass
except:
print("Invalid input")
pass
are you sure, this is my output
deathnote#deathnote:~/Desktop/d$ python3 code.py
Enter a number or type 'done':12
Enter a number or type 'done':
Invalid input
Enter a number or type 'done':
Invalid input
Enter a number or type 'done':qwe
Invalid input
Enter a number or type 'done':
Invalid input
Enter a number or type 'done':wqew
Invalid input
Enter a number or type 'done':done
=============================
Your even numbers are ['12']
Your odds numbers are []
=============================
Your smallest number is '12'
The error message is pretty clear: number contains a space, which can't be parsed into an integer. If you want to flag such input as invalid, you have to test it before trying to convert it to an integer (or catch the error that doing so generates).
You have two issues:
Need check for space before you are trying to get a number from it.
Then you are appending number input as string into your list, which will end with wrong sorting result as it will sort string instead of number.
allnums = []
odds = []
evens = []
number = 0
if number.lower() == 'done':
evens.sort()
odds.sort()
allnums.sort()
print("=============================")
print("Your even numbers are", str(evens))
print("Your odds numbers are", str(odds))
print("=============================")
print("Your smallest number is '"+str(allnums[0])+"'")
break
if number.isspace():
print("Invalid input")
else:
number = int(number)
if int(number) % 2 == 0:
evens.append(number)
allnums.append(number)
elif int(number) % 2 != 0:
odds.append(number)
allnums.append(number)
allnums = []
odds = []
evens = []
number = 0
while True:
number = input("Enter a number or type 'done':")
if number.lower() == 'done':
print("=============================")
print("Your even numbers are", str(evens))
print("Your odds numbers are", str(odds))
print("=============================")
print("Your smallest number is '" + sorted(allnums)[0] + "'")
break
if not number.isnumeric():
print("Invalid input")
continue
if int(number) % 2 == 0:
evens.append(number)
evens.sort()
allnums.append(number)
allnums.sort()
if int(number) % 2 != 0:
odds.append(number)
odds.sort()
allnums.append(number)
allnums.sort()

User input accepting str and int (python)

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.

Resources