Python while _ValueError - python

In this program if user enter a str input, the program won't run and user will get an error.
how can I develope my program to tell the user that input is wrong?
Could you help me with this problem please?
summation = 0
while True:
user_input = input("Enter your input \n")
if user_input == "done":
break
else:
summation = summation + float(user_input)
print("End \n", "SUMMATION = ", summation)
"conention.py/while.py"
Enter your input
Hi
Traceback (most recent call last):
File "c:\Users\ASUS\Desktop\python\name conention.py\while.py", line 7,
in <module> summation = summation + float(user_input)
ValueError: could not convert string to float: 'Hi'
PS C:\Users\ASUS\Desktop\python>

You run float("Hi") and this makes problem.
You should use try/except to catch error and do something or skip it.
For example.
summation = 0
while True:
user_input = input("Enter your input \n")
if user_input.lower() == "done":
break
try:
summation = summation + float(user_input)
print("End \n", "SUMMATION = ", summation)
except ValueError:
print('It is not float value:', user_input)

Related

How to exit a while True loop using a different format condition in Python?

I found the following code example online, which exits a while True loop by using a specific integer:
while True:
i = int(input('Please enter an integer (or 0 to exit):\n'))
if i == 0:
print("Exiting the Program")
break
print(f'{i} square is {i ** 2}')
I would like to know how to exit the loop using a str input (like "exit"), instead of a specific int (0 in this example).
I messed around by creating one input per type:
while True:
i_str = input('Please enter an integer ( or "exit" to exit): ')
if i_str == "exit":
print("Exiting the Program")
break
i_int = int(input('Please enter an integer (or "exit" to exit): '))
print(f'{i_int} square is {i_int ** 2}')
...but it prints out smth every other try, and throws a ValueError when computing 'exit' on the wrong try.
I basically can't figure out how to implement this properly, neither am I sure that I should even be using two different input formats to solve this.
You can use if-else and convert to int if it is not exit as:
while True:
i_str = input('Please enter an integer ( or "exit" to exit): ')
if i_str == "exit":
print("Exiting the Program")
break
else:
i_int = int(i_str)
print(f'{i_int} square is {i_int ** 2}')
you can just cast it to a string first and validate it then cast it to int and then put that all in a try-catch to catch any exceptions you can use the example below
while True:
try:
i = str(input('Please enter an integer (or 0 to exit):\n'))
if "exit" in i:
print("Exiting the Program")
break
else:
i = int(i)
if i == 0:
print("Exiting the Program")
break
print(f'{i} square is {i ** 2}')
except:
print("Exiting the Program")
You can just use try-except, program will raise an exception if it is unable to convert the entered number to integer.
while True:
try:
i = int(input('Please enter an integer ( or "exit" to exit): '))
print(f'{i} square is {i ** 2}')
except:
print("Exiting the Program")
break

How can I get print except statement printed instead of an error below in try/except syntax in Python

I am new to Python programming. Following is the code written and it works fine when I print any numeric digit and give me the desired result as expected but the problem comes when I enter string (anything other than integer/float) instead of giving me just the except statement, it also gives me an error which I don't want. So, what I want is when a user enter anything other than numeric digits, he should be prompted with a message i.e., "Invalid input. Enter a number please" instead of an error which I am getting after the except print statement in the end. Please help.
hours_string = input("Enter Hours: ")
rate_string = input("Enter Rate: ")
try:
hours_float = float(hours_string)
rate_float = float(rate_string)
except:
print("Invalid input. Enter a number please.")
result = hours_float * rate_float
print("Pay",result)
This is the error I am getting. If I enter string, I should simply get an except statement. That's it. Not any other error. How can I accomplish to get there?
Enter Hours: 9
Enter Rate: entered string by mistake
Invalid input. Enter a number please.
Traceback (most recent call last):
File "<string>", line 9, in <module>
NameError: name 'rate_float' is not defined
For a particular Error you can do a particular Exeption like in the Code below. Also note that each question is in a whileloop that you need to acomplish the task before you get to the next one.
while True:
try:
hours_string = input("Enter Hours: ")
hours_float = float(hours_string)
except ValueError:
print("Invalid input. Enter a number please.")
else:
break
while True:
try:
rate_string = input("Enter Rate: ")
rate_float = float(rate_string)
except ValueError:
print("Invalid input. Enter a number please.")
else:
break
result = hours_float * rate_float
print("Pay",result)
hours_float = None
rate_float = None
while hours_float is None:
hours_string = input("Enter Hours: ")
try:
hours_float = float(hours_string)
except ValueError:
print("Invalid input. Enter a number please.")
while rate_float is None:
rate_string = input("Enter Rate: ")
try:
rate_float = float(rate_string)
except ValueError:
print("Invalid input. Enter a number please.")
result = hours_float * rate_float
print("Pay", result)
In the while loop we repeatedly ask user for input, while they don't enter a valid number, separately for hours and rate.
Valid input changes the initially set None value to something else, which finishes the corresponding loop.
Since this is a expected situation and it can be treated as a test I would recommend instead of trying to execute the operation with wathever input the user provided you could ask the user for the input and while it is not an integer you ask for the input again.
def get_input(name, var_type):
userin = None
while userin is None:
userin = input(f'Input {name}: ')
try:
userin = var_type(userin)
except ValueError:
print(f'{name} must be {str(var_type)}, not {str(type(userin))}')
userin = None
return userin
hours = get_input('hours', int)
rate = get_input('rate', float)
result = hours * rate
print('Pay', result)
The function get_input tries to cast the input input value to the type you want and if it is not as desired it will keep asking until the type matches.

About quitting the factorial program in an endless loop [duplicate]

This question already has answers here:
Asking the user for input until they give a valid response
(22 answers)
Closed 2 years ago.
My goal is creating a factorial program in python that asks infinite user input to find factorial of the number user type, until I would like to quit the program. But there is probably discrepancy between the lines of the code to works for exit the program and integer numbers below it.
1) I tried to solve this to not write int(input) I wrote just
input('Enter a number. Type exit to stop:> ')
both above or below the while True statement but it didn't work.
2) I also want to use lower() function to quit the program but when I use it, the discrepancy happens again because I ask user input for an integer but when I turn it to a normal input and type it the above while True statement, problem occurs.
3) Also I want to user input as a number with using that isdigit() function tried to use like this but it didn't work well:
factorial = 1
user_input = input('Enter a number: ')
while user_input.lower() != 'exit':
while not user_input.isdigit():
print('This is not a number. Please try again:> ')
user_input = int(input('Try again:> '))
user_input = int(input('Enter a new number: '))
.
.
.
and this, too didn't work
My actual code is this:
while True:
factorial = 1
user_input = int(input('Enter a number. Type exit to stop:> '))
if user_input == 'exit':
print('You are quitting the program')
break
elif user_input < 0:
print("Sorry, factorial does not exist for negative numbers")
elif user_input == 0:
print("The factorial of 0 is 1")
else:
for i in range(1, user_input + 1):
factorial = factorial * i
print("The factorial of", user_input, "is", factorial)
The program works like this:
Enter a number. Type exit to stop:> 4
The factorial of 4 is 24
Enter a number. Type exit to stop:> 5
The factorial of 5 is 120
Enter a number. Type exit to stop:> 6
The factorial of 6 is 720
and when I type 'exit' to quit from program I am receiving this kind of error:
Traceback (most recent call last):
File "E:/Kodlar/Python/Taslak projeler/taslak177.py", line 5, in <module>
user_input = int(input('Enter a number. Type exit to stop:> '))
ValueError: invalid literal for int() with base 10: 'exit'
As you can see, code blocks work instead of quitting the program with user input. How can I fix this?
Can anyone help? Thanks already!
Edit: I reorganized the code and it works perfectly fine. Thanks for your all responses!
while True:
user_input = input("Enter a number:> ")
if user_input == "exit":
print('You are quitting the program...')
break
else:
try:
factorial = 1
user_input = int(user_input)
if user_input < 0:
print("Sorry, factorial does not exist for negative numbers")
elif user_input == 0:
print("The factorial of 0 is 1")
else:
for i in range(1, user_input + 1):
factorial = factorial * i
print(f'The factorial of {user_input} is {factorial}')
except ValueError:
print("Please provide a valid number")
You should check if the input is exit before converting it to int and if so, break the loop.
Try this instead:
while True:
user_input = input("Enter a number:")
if user_input == "exit":
print('You are quitting the program')
break
else:
try:
user_number = int(user_input)
if user_number < 0:
print("Sorry, factorial does not exist for negative numbers")
elif user_number == 0:
print("The factorial of 0 is 1")
else:
# calc factorial here
except ValueError:
print("Please provide a valid number")
Your program get int inputs,
user_input = int(input('Enter a new number: '))
try this instead, get string input
user_input = input('Enter a new number: ')
and convert it into int later
user_input = int(user_input)
Because you are casting the user's response (a string) into an int in both cases.
user_input = int(input('Enter a new number: '))
and later
user_input = int(input('Enter a number. Type exit to stop:> '))
Perhaps try a little tweak:
while True:
factorial = 1
user_input = input('Enter a number. Type exit to stop:> ')
if user_input.lower().strip() == 'exit':
print('You are quitting the program')
break
elif user_input.isnumeric() and user_input < 0:
print("Sorry, factorial does not exist for negative numbers")
elif user_input.isnumeric() and user_input == 0:
print("The factorial of 0 is 1")
elif user_input.isnumeric():
for i in range(1, user_input + 1):
factorial = factorial * i
print("The factorial of", user_input, "is", factorial)
else:
print("Please enter an integer or 'exit'")
You could also wrap another if so you don't duplicate the isnumeric() tests

How to handle ValueError while if int() is provided non-integer

Python reads function input() as string.
Before passing it to my function for division, variables are typecasted into int using int().
If one variable is non-int (eg "a") then how to catch it?
def divideNums(x,y):
try:
divResult = x/y
except ValueError:
print ("Please provide only Integers...")
print (str(x) + " divided by " + str(y) + " equals " + str(divResult))
def main():
firstVal = input("Enter First Number: ")
secondVal = input("Enter Second Number: ")
divideNums (int(firstVal), int(secondVal))
if __name__ == "__main__":
main()
How to handle typecast of firstVal / secondVal ?
You can use isdigit function to check if the input values are integer or not
def main():
firstVal = input("Enter First Number: ")
secondVal = input("Enter Second Number: ")
if firstVal.isdigit() and secondVal.isdigit():
divideNums (int(firstVal), int(secondVal))
else:
print ("Please provide only Integers...")
You are right about using a try/except ValueError block, but in the wrong
place. The try block needs to be around where the variables are converted to
integers. Eg.
def main():
firstVal = input("Enter First Number: ")
secondVal = input("Enter Second Number: ")
try:
firstVal = int(firstVal)
secondVal = int(secondVal)
except ValueError:
# print the error message and return early
print("Please provide only Integers...")
return
divideNums (firstVal, secondVal)

Calculator exercise in Python

this is my first post so PLEASE let me know if I'm not doing this correctly! Also, please don't roast me too hard for my code, I'm (very) new!
I'm trying to create a basic 'calculator' that takes two numbers as input and spits the summation back at the user. If the user types 'quit', I want the program to break, and if they enter a string rather than an integer I want the program to respond telling them to enter a number. I'd also like the program to continue after the numbers are added so that the user can continue to add numbers until they choose to type 'quit'.
My problem is this:
The program runs, and asks the user for the first and second numbers, however, if the user types in a string, it STILL produces a traceback error. I'm assuming I didn't type the exception properly somehow. Also, the loop never ends so it returns a constant string of the two numbers entered.
number1 = int(input("Enter a number: "))
number2 = int(input("Enter another number: "))
error_msg = print("That isn't a number. Please enter a number")
flag = True
while flag == True:
try:
print(number1)
except ValueError:
print(error_msg)
try:
print(number2)
except ValueError:
print(error_msg)
summation = number1 + number2
print(summation)
if number1 or number2 == 'quit':
flag == False
Here's my error message:
Enter a number: 3
Enter another number: f
Traceback (most recent call last):
File "errors.py", line 2, in <module>
number2 = int(input("Enter another number: "))
ValueError: invalid literal for int() with base 10: 'f'
EDIT - The error message, Thank you, larsks.
Any help would be greatly appreciated!
You almost got it but your inputs are in the wrong place, here's a more pythonic approach.
import sys
flag = True
while flag:
number1 = input("Enter a number: ")
if number1 == 'quit':
sys.exit(1)
number2 = input("Enter another number: ")
if number2 == 'quit':
sys.exit(1)
try:
number1 = int(number1)
number2 = int(number2)
except (ValueError, AttributeError):
print("That isn't a number. Please enter a number")
else:
summation = number1 + number2
print(summation)
You are asking for input there:
number1 = int(input("Enter a number: "))
number2 = int(input("Enter another number: "))
Then you are, at the same time, converting the user input to an integer using int(...). If you type in a non-integer value, you get the exception:
Traceback (most recent call last):
File "calc.py", line 1, in <module>
number1 = int(input("Enter a number: "))
ValueError: invalid literal for int() with base 10: 'hello'
There is no try/except block around these lines, so the traceback causes the program to exit.
You have some try/except blocks later on in your code, but they don't do anything:
try:
print(number1)
except ValueError:
print(error_msg)
print(number1) is never going to raise a ValueError exception (because print doesn't care if you give it a number or a string or something else).

Categories

Resources