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 ;)")
Related
I'm programming a beginner calculator in Python.
I'm stuck trying to rerun the function automatically after getting the return value.
So far it reruns when the except block is triggered.
However, it does not rerun when a sum is entered correctly.
def better_calc():
num1 = float(input("please enter your first number: "))
op = input("please enter an operator: ")
num2 = float(input("please enter your second number: "))
try:
if op == "+":
result = num1+num2
elif op == "-":
result = num1-num2
elif op == "*":
result = num1*num2
elif op == "/":
result = num1/num2
print()
print(num1, op, num2, "=")
return result
better_calc()
print()
except UnboundLocalError:
print("\nError: please enter an established operator")
print()
except ZeroDivisionError:
print("\nError: Can not divide by zero")
print()
better_calc()
print(better_calc())
So I have two questions.
(1) How do I rerun the function after getting the return value?
(2) Should I bother trying to get a return value (is there any benefit?), or just print the answer without a return?
As someone stated in the comments, anything below a return statement is not run because it ends the function, bearing this in mind, my answer to your second question would be no, there is no benefit (in this case) to getting a return value. Instead, I would change your function to this:
def better_calc():
num1 = float(input("please enter your first number: "))
op = input("please enter an operator: ")
num2 = float(input("please enter your second number: "))
try:
if op == "+":
result = num1+num2
elif op == "-":
result = num1-num2
elif op == "*":
result = num1*num2
elif op == "/":
result = num1/num2
print()
print(str(num1)+" "+ str(op)+" "+ str(num2)+ " = " + str(result))
#You just print the result of the calculation above
except UnboundLocalError:
print("\nError: please enter an established operator")
print()
except ZeroDivisionError:
print("\nError: Can not divide by zero")
print()
answer = input("Would you like to enter another calculation?(type \"yes\" if so): ")
return answer
#You are using this return statement to either continue or end the while loop
I would also recommend encasing your file in a while loop like so:
#start of file
#have your better_calc function definition here
startingAnswer = "yes"
while(startingAnswer = "yes"):
startingAnswer = better_calc()
#end of file
This way, you are able to continue doing calculations as long as you want (while not running into infinite loop issues).
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
I am working on a small coding challenge which takes user input. This input should be checked to be a digit. I created a "try: ... except ValueError: ..." block which checks once whether the input is a digit but not multiple times. I would like it to basically checking it continuously.
Can one create a while-exception loop?
My code is the following:
try:
uinput = int(input("Please enter a number: "))
while uinput <= 0:
uinput = int(input("Number is negative. Please try again: "))
else:
for i in range(2, uinput):
if (uinput % i == 0):
print("Your number is a composite number with more than
one divisors other than itself and one.")
break
else:
print(uinput, "is a prime number!")
break
except ValueError:
uinput = int(input("You entered not a digit. Please try again: "))
flag = True
while flag:
try:
uinput = int(input("Please enter a number: "))
while uinput <= 0:
uinput = int(input("Number is negative. Please try again: "))
else:
flag=False
for i in range(2, uinput):
if (uinput % i == 0):
print("Your number is a composite number with more than one divisors other than itself and one.")
break
else:
print(uinput, "is a prime number!")
break
except ValueError:
print('Wrong input')
Output :
(python37) C:\Users\Documents>py test.py
Please enter a number: qwqe
Wrong input
Please enter a number: -123
Number is negative. Please try again: 123
123 is a prime number!
I add flag boolean to not make it repeat even when the input is correct and deleted input in except because it would ask 2 times.
If you press Enter only, the loop terminated:
while True:
uinput = input("Please enter a number: ")
if uinput.strip()=="":
break
try:
uinput=int(uinput)
except:
print("You entered not a digit. Please try again")
continue
if uinput<=0:
print("Not a positive number. Please try again")
continue
for i in range(2, uinput):
pass; # put your code here
This question already has answers here:
Asking the user for input until they give a valid response
(22 answers)
Closed 4 years ago.
I am running into a problem, I am trying to make a calculator as my first program!(I am still a very beginner at programming), and i wan't it to print out a statement when someone enters a string rather than an integer , Here is my code:
add = ["add", "+", "plus"]
minus = ["minus", "-", "subtract"]
multiply = ["multiply", "*", "product"]
divide = ["divide", "/",]
quit = ["quit", "q", "leave", "shut down"]
retry = ["retry", "start again", "start", "r",]
leave = False
while True:
service = input("What would you like to do? ")
if service.lower() in add:
x = int(input("First number... "))
y = int(input("Second number... "))
print(x + y)
elif service.lower() in minus:
x = int(input("First number... "))
y = int(input("Second number... "))
print(x - y)
elif service.lower() in divide:
x = int(input("First number... "))
y = int(input("Second number... "))
print(x / y)
elif service.lower() in multiply:
x = int(input("First number... "))
y = int(input("Second number... "))
print(x * y)
elif service != int:
print("You entered a string , not an integer")
elif service.lower() in quit: #if the user types quit , it'll kill the loop
break
else:
print("Invalid command...Do you want to quit or retry? ")
lastOption = input()
if lastOption.lower() in quit: #If the user writes in quit , it'll kill the loop here
break
elif lastOption.lower() not in retry: #if the user inputs gibberish again, it begins a check otherwise it restarts
while True: #A loop begins if the user has entered an unrecognized input
print("Sorry I did not catch that, can you please repeat? ")
lastOption = input()
if lastOption.lower() in quit:
leave = True #sets leave condition to true as you cannot break two loops in one break statement
break
elif lastOption.lower() in retry:
break
if leave == True: #continuing on from the check loop for unrecognized inputs this allows you to break the loops
break
EDIT: Here is the "try" and "except" code added
while True:
service = input("What would you like to do? ")
if service.lower() in add:
try:
x = int(input("First number... "))
y = int(input("Second number... "))
print(x + y)
except ValueError:
print("You did not enter an integer")
You're taking input, and casting it to int. The casting will raise a ValueError exception if it isn't an integer, you can try catching that exception.
try:
x = int(input("First number... "))
y = int(input("Second number... "))
except ValueError:
print("You should enter a number instead.")
Write a try / catch block. If a string is passed rather than an integer, it will throw an exception (a flag used to denote an error, halts execution). Wrap the block in a try statement. Then write a catch statement to do something (probably print) when it's not an integer. Of course, there are many types of exceptions, and in this case, if a string is passed, a ValueError exception will be thrown.
try:
int (input (">> "))
catch ValueError:
print("Error: string not valid. Try again")
def multiply(): #starts sub program when 'multiply()' is called
num1 = random.randint(1,12) #randomly generates a number between 1 and 12
num2 = random.randint(1,12)
while loop == True: #creates loop, and uses previously defined 'loop'
ans = int(input("What is the answer to " + str(num1) + " x " + str(num2) + " ? ")) #asks question and requires a user input
correct = (ans == num1 * num2)
if correct:
print("You are correct! ")
break #if the answer is correct, it prints 'You are correct!' and breaks to avoid the loop
else:
print("Wrong, please try again. ")
loop == False #if the answer is wrong, it loops back to when 'loop' was last 'True'
I am wondering if there is a way for me to include a line of code that allows me to display "That is not an option!" when a symbol other than a number is entered into the 5th line in the code.
Use an exception to catch unexpected inputs.
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
import random
def multiply():
# Randomly generates a number between 1 and 12
num1 = random.randint(1,12)
num2 = random.randint(1,12)
while True:
i = input("What is the answer to {} x {} ".format(
str(num1), str(num2)))
try:
ans = int(i)
except ValueError:
print('That is not an option!')
continue
if ans == num1 * num2:
print("You are correct!")
break
else:
print("Wrong, please try again.")
if __name__ == "__main__":
multiply()
When you convert to int there is the chance that they will enter a non-integer value so the conversion will fail, so you can use a try/except
def multiply(): #starts sub program when 'multiply()' is called
num1 = random.randint(1,12) #randomly generates a number between 1 and 12
num2 = random.randint(1,12)
while loop == True: #creates loop, and uses previously defined 'loop'
try:
ans = int(input("What is the answer to " + str(num1) + " x " + str(num2) + " ? ")) #asks question and requires a user input
correct = (ans == num1 * num2)
if correct:
print("You are correct! ")
break #if the answer is correct, it prints 'You are correct!' and breaks to avoid the loop
else:
print("Wrong, please try again. ")
loop == False
except ValueError:
print("That is not an option")
Note that your previous code is now nested in a try block. If the int() fails because they entered a bad input, it will throw a ValueError that you can catch and notify them.
As a side note, another way to format your question to them would be
'What is the answer to {} x {}?'.format(num1, num2)
This is a nice way to generate a string with injected variable values.