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).
Related
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)
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.
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
Could you please advise what is wrong with the below code please?
def add(x, y):
return x + y
while True:
try:
num1 = float(input('Enter first number: ')
except:
print ('num1 is a complex/string. Only Integers or Float is allowed. Please key in again')
try:
num2 = float(input("Enter first number: ")
except:
print ('num2 is a complex/string. Only Integers or Float is allowed. Please key in again')
break
print(num1,"+",num2,"=", add(num1,num2))
input("Press enter to exit ;)")
(apart from the syntax errors - missing brackets...)
The break statement escapes the while loop, so by putting it at the end of the iteration, you will break out on the very first iteration so if the enter invalid inputs, they won't be asked again since you will have broken out.
In addition, the logic is wrong in terms of having only one loop. If they enter a valid num1 and then an invalid num2, they will (if you move the break) be asked to enter both num1 and num2 again - rather than just num2 again.
To remedy these issues, you could compartmentalise your code - moving the inputting logic to a function:
def get_float(prompt):
while True:
try:
return float(input(prompt))
break
except ValueError:
print('sorry, invalid input')
Then your main code is much easier to understand:
def add(x, y):
return x + y
num1 = get_float('Enter first number: ')
num2 = get_float('Enter second number: ')
result = add(num1, num2)
print(num1, '+', num2, '=', result)
input('press enter to exit')
And a trial run shows its good:
Enter first number: one
sorry, invalid input
Enter first number: bob
sorry, invalid input
Enter first number: 20
Enter second number: nine
sorry, invalid input
Enter second number: 8.89
20.0 + 8.89 = 28.89
press enter to exit
You need to use raw_input to accept just an enter prompt.
def add(x, y):
return x + y
while True:
try:
num1 = float(raw_input('Enter first number: '))
except:
print ('num1 is a complex/string. Only Integers or Float is allowed. Please key in again')
try:
num2 = float(raw_input("Enter second number: "))
except:
print ('num2 is a complex/string. Only Integers or Float is allowed. Please key in again')
break
print(num1,"+",num2,"=", add(num1,num2))
raw_input("Press enter to exit ;)")
import sys
looptwo = True
while looptwo == True:
print("Welcome to the junior maths program, this program helps you do maths problems and acts as a calulator.")
try:
name = input("What is your name? ")
number = int(input("Enter your first number: "))
number2 = int(input("Enter your second number: "))
except ValueError:
print("that is not an option")
looptwo == False
when i run this code, it says that number isn't defined.
Your logic is backwards, you should only break if there is no error, you set looptwo equal to False in the except presuming that == is a typo which breaks the loop. So whenever you try to access name etc.. outside when the loop after an exception you will get an undefined error.
The only way your code breaks is when an exception is raised:
Use while True and only break if there were no exceptions.
while True:
print("Welcome to the junior maths program, this program helps you do maths problems and acts as a calulator.")
try:
name = input("What is your name? ")
number = int(input("Enter your first number: "))
number2 = int(input("Enter your second number: "))
break
except ValueError:
print("that is not an option")