This question already has answers here:
How to test multiple variables for equality against a single value?
(31 answers)
Closed 1 year ago.
see this is my code
print("""1. ADD
2. SUBTRACT
3. MULTIPLY
4. DIVIDE
5. SQUARE
6. SQUARE ROOT
7. CUBE
8. CUBE ROOT
9. POWER OF A NUMBER
10. FACTORIAL
11. TRIANGLE'S PERIMETER
12. TRIANGLE'S AREA
13. QUADRILATERAL'S PERIMETER
14. PARALLELOGRAM'S AREA
15. RHOMBUS'S AREA
17. RECTANGLE'S AREA
18. SQUARE'S AREA
19. TRAPEZIUM'S AREA
20. CIRCLE'S CIRCUMFERENCE
21. CIRCLE'S AREA
22. QUADRATIC EQUATION
23. SIMPLE INTEREST
24. COMPOUND INTEREST""")
while True:
user = str(input("Enter GO to continue or Q to exit: "))
if user == 'GO':
user_input = str(input("Enter here the serial number or the name in capital for what you want to calculate: "))
if user_input == 'ADD' or 1 :
add()
elif user_input == 'SUBTRACT' or 2 :
sub()
elif user_input == 'MULTIPLY' or 3 :
mlt()
elif user_input == 'DIVIDE' or 4 :
div()
elif user_input == 'SQUARE' or 5 :
sqr()
elif user_input == 'SQUARE ROOT' or 6 :
sqrt()
elif user_input == 'CUBE' or 7 :
cube()
elif user_input == 'CUBE ROOT' or 8 :
cube_root()
elif user_input == 'POWER OF A NUMBER' or 9 :
power()
elif user_input == "TRIANGLE'S PERIMETER" or 11 :
triangle_perimeter()
elif user_input == "QUADRILATERAL'S PERIMETER" or 13 :
quadrilateral_perimeter()
elif user_input == "PARALLELOGRAM'S AREA" or 14 :
parallelogram_area()
elif user_input == 'FACTORIAL' or 10 :
factorial()
elif user_input == "RHOMBUS'S AREA" or 15 :
rhombus_area()
elif user_input == "RECTANGLE'S AREA" or 17 :
rectangle_area()
elif user_input == "SQUARE'S AREA" or 18 :
square_area()
elif user_input == "CIRCLE'S AREA" or 21 :
circle_area()
elif user_input == "CIRCLE'S CIRCUMFERENCE" or 20 :
circle_circumference()
elif user_input == "QUADRATIC EQUATION" or 22 :
qaudratic_solver()
elif user_input == "SIMPLE INTEREST" or 23 :
simple_interest()
elif user_input == "COMPOUND INTEREST" or 24 :
compound_interest()
elif user_input == "TRIANGLE'S AREA" or 12 :
triangle_area()
elif user_input == "TRAPEZIUM'S AREA" or 19 :
trapezium_area()
else:
print("Invalid input!!")
elif user == 'Q':
break
else:
print("Invalid input!!")
and when I run it when I put any number or name in the input line instead of calling out the function with respect to the number or name it calls out to the add() function which relates number 1 and and name "ADD"
Why is this happening? Please help me...
PS: I had done this in google colab so the actual functions are written in a separate "cell" if you know google colab you'll know :) but anyways here are functions too
import cmath
import functools
def add():
while True:
user_input = str(input("Enter GO to continue or Q to exit: "))
if user_input == 'GO':
val1 = float(input("Enter the first number: "))
val2 = float(input("Enter the second number: "))
print("The result is: ", val1 + val2)
elif user_input == 'Q':
break
else:
print("Invalid input!!")
def sub():
while True:
user_input = str(input("Enter GO to continue or Q to exit: "))
if user_input == 'GO':
val1 = float(input("Enter the first number: "))
val2 = float(input("Enter the second number: "))
print("The result is: ", val1 - val2)
elif user_input == 'Q':
break
else:
print("Invalid input!!")
def mlt():
while True:
user_input = str(input("Enter GO to continue or Q to exit: "))
if user_input == 'GO':
val1 = float(input("Enter the first number: "))
val2 = float(input("Enter the second number: "))
print("The result is: ", val1*val2)
elif user_input == 'Q':
break
else:
print("Invalid input!!")
def div():
while True:
user_input = str(input("Enter GO to continue or Q to exit: "))
if user_input == 'GO':
val1 = float(input("Enter the first number: "))
val2 = float(input("Enter the second number: "))
print("The result is: ", val1/val2)
elif user_input == 'Q':
break
else:
print("Invalid input!!")
def sqrt():
while True:
user_input = str(input("Enter GO to continue or Q to exit: "))
if user_input == 'GO':
val1 = float(input("Enter the number: "))
print("The result is: ", cmath.sqrt(val1))
elif user_input == 'Q':
break
else:
print("Invalid input!!")
def sqr():
while True:
user_input = str(input("Enter GO to continue or Q to exit: "))
if user_input == 'GO':
val1 = float(input("Enter the number: "))
print("The result is: ", val1**2)
elif user_input == 'Q':
break
else:
print("Invalid input!!")
def power():
while True:
user_input = str(input("Enter GO to continue or Q to exit: "))
if user_input == 'GO':
val1 = float(input("Enter the number: "))
val2 = float(input("Enter the power of the number: "))
print("The result is: ", val1**val2)
elif user_input == 'Q':
break
else:
print("Invalid input!!")
def square_area():
while True:
user_input = str(input("Enter GO to continue or Q to exit: "))
if user_input == 'GO':
val1 = float(input("Enter the value of the side: "))
print("The area of the square is: ", val1**2)
elif user_input == 'Q':
break
else:
print("Invalid input!!")
def rectangle_area():
while True:
user_input = str(input("Enter GO to continue or Q to exit: "))
if user_input == 'GO':
val1 = float(input("Enter the value of the length: "))
val2 = float(input("Enter the value of the breadth: "))
print("The area of the square is: ", val1*val2)
elif user_input == 'Q':
break
else:
print("Invalid input!!")
def circle_circumference():
while True:
user_input = str(input("Enter GO to continue or Q to exit: "))
if user_input == 'GO':
val1 = float(input("Enter the radius of the circle: "))
print("The circumference of the circle is: ", (val1*44)/7)
elif user_input == 'Q':
break
else:
print("Invalid input!!")
def circle_area():
while True:
user_input = str(input("Enter GO to continue or Q to exit: "))
if user_input == 'GO':
val1 = float(input("Enter the radius of the circle: "))
print("The area of the circle is: ", (val1*val1*22)/7)
elif user_input == 'Q':
break
else:
print("Invalid input!!")
def rhombus_area():
while True:
user_input = str(input("Enter GO to continue or Q to exit: "))
if user_input == 'GO':
val1 = float(input("Enter the value of first diagonal: "))
val2 = float(input("Enter the value of the second diagonal: "))
print("The area of the rhombus is: ", 0.5*val1*val2)
elif user_input == 'Q':
break
else:
print("Invalid input!!")
def parallelogram_area():
while True:
user_input = str(input("Enter GO to continue or Q to exit: "))
if user_input == 'GO':
val1 = float(input("Enter the value of height: "))
val2 = float(input("Enter the value of the correspondent base: "))
print("The area of the parallelogram is: ", 0.5*val1*val2)
elif user_input == 'Q':
break
else:
print("Invalid input!!")
def quadrilateral_perimeter():
while True:
user_input = str(input("Enter GO to continue or Q to exit: "))
if user_input == 'GO':
a = float(input("Enter the first side of the quadrilateral: "))
b = float(input("Enter the second side of the quadrilateral: "))
c = float(input("Enter the third side of the quadrilateral: "))
d = float(input("Enter the foruth side of the quadrilateral: "))
if ((a + b + c> d) and (a + b + d> c) and (b + c + d> a) and (a + d + c> b)) :
print("The perimeter of the qaudrilateral is : ", a+b+c+d)
else :
print("Quadrilateral is not valid.")
elif user_input == 'Q':
break
else:
print("invalid input")
def trapezium_area():
while True:
user_input = str(input("Enter GO to continue or Q to exit: "))
if user_input == 'GO':
par1 = float(input("Enter the value of the first parallel side: "))
par2 = float(input("Enter the value of the second parallel side: "))
hei1 = float(input("Enter the the value of the height: "))
print("The area of the trapezium is: ", 0.5*hei1*(par1+par2))
elif user_input == 'Q':
break
else:
print("Invalid input!!")
def triangle_perimeter():
while True:
user_input = str(input("Enter GO to continue or Q to exit: "))
if user_input == 'GO':
a = float(input("Enter the first side of the triangle: "))
b = float(input("Enter the second side of the triangle: "))
c = float(input("Enter the third side of the triangle: "))
if ((a + b > c) and (a + c > b) and (b + c > a)) :
print("The perimeter of the traingle is: ", a+b+c)
else :
print("Triangle is not valid.")
elif user_input == 'Q':
break
else:
print("invalid input")
def triangle_area():
while True:
user_input = str(input("Enter GO to continue or Q to exit: "))
if user_input == 'GO':
area_method = str(input("Enter Heron or Traditional(0.5*height*base): "))
if area_method == 'Heron':
a = float(input("Enter the first side of the triangle: "))
b = float(input("Enter the second side of the triangle: "))
c = float(input("Enter the third side of the triangle: "))
if ((a + b > c) and (a + c > b) and (b + c > a)) :
s = (a+b+c)*0.5
print("The area of the triangle is ", cmath.sqrt((s-a)*(s-b)*(s-c)*(s)))
else:
print("Triangle is not valid!!")
elif user_input == 'Traditional':
a = float(input("Enter the value of the height: "))
b = float(input("Enter the value of the correspondent base: "))
print("The area of the triangle is ", 0.5*a*b)
else:
print("Invalid input!!")
elif user_input == 'Q':
break
else:
print("Invalid input!!")
def qaudratic_solver():
while True:
user_input = str(input("Enter the GO to continue or Q to exit: "))
if user_input == 'GO':
a = float(input("Enter the coeffiecient of x^2: "))
b = float(input("Enter the coeffiecient of x: "))
c = float(input("Enter the constant: "))
D = cmath.sqrt(b*b - 4*a*c)
F = 2*a
X1 = (-b + D)/(F)
X2 = (-b - D)/(F)
print("The values of x are: ", X1, ", ", X2)
elif user_input == 'Q':
break
else:
print("Invalid input!!")
def cube():
while True:
user_input = str(input("Enter GO to continue or Q to exit: "))
if user_input == 'GO':
val1 = float(input("Enter the number: "))
print("The result is: ", val1**3)
elif user_input == 'Q':
break
else:
print("Invalid input!!")
def cube_root():
while True:
user_input = str(input("Enter GO to continue or Q to exit: "))
if user_input == 'GO':
val1 = float(input("Enter the number: "))
print("The result is: ", val**1/3)
elif user_input == 'Q':
break
else:
print("Invalid input!!")
def compound_interest():
while True:
user_input = str(input("Enter GO to continue or Q to exit: "))
if user_input == 'GO':
P = float(input("Enter the principal amount: "))
IR = float(input("Enter the interest rate: "))
T = float(input("Enter the time period: "))
N = float(input("Enter the number of times interest is compunded per unit time 't': "))
A = P*((1+((IR/100)/N))**(N*T))
CI = A-P
print("The final amount will be ", A, " and the compund interest will total up to ", CI)
elif user_input == 'Q':
break
else:
print("Invalid input!!")
def simple_interest():
while True:
user_input = str(input("Enter GO to continue or Q to exit: "))
if user_input == 'GO':
P = float(input("Enter the principal amount: "))
R = float(input("Enter the interest rate: "))
T = float(input("Enter the time period: "))
SI = (P*R*T)/100
A = P + SI
print("The final amount will be ", A, " and the simple interest will total up to ", SI)
elif user_input == 'Q':
break
else:
print("Invalid input!!")
def factorial():
while True:
user_input = str(input("Enter GO to continue or Q to exit: "))
if user_input == 'GO':
a = int(input("Enter the number: "))
print(functools.reduce(lambda x,y : x * y, range(1,a+1)))
elif user_input == 'Q':
break
else:
print("Invalid input!!")
The condition in:
if user_input == 'ADD' or 1:
doesn't quite do what you think it does.
Each side of an or is usually a separate sub-expression that is evaluated independently, then the results are or'ed together. The proper expression for your case would be:
if user_input == 'ADD' or user_input == '1':
Note the quoted '1' in my version, the string '1' is not the same as the integer 1, and you are working with strings here.
However, a more Pythonic way would be:
if user_input in ['ADD', '1']:
which would allow you to keep code much shorter for things like:
if number in [2, 3, 5, 7, 11, 13, 17, 19]:
print(f"{number} is a prime under twenty")
Interestingly enough, the result of an expression False or something is not necessarily True or False, it's actually something. You can see this with the following transcript:
>>> True or 'hello'
True
>>> False or 'hello'
'hello'
More detail can be found here:
The expression x and y first evaluates x; if x is false, its value is returned; otherwise, y is evaluated and the resulting value is returned.
The expression x or y first evaluates x; if x is true, its value is returned; otherwise, y is evaluated and the resulting value is returned.
Note that neither and nor or restrict the value and type they return to False and True, but rather return the last evaluated argument. This is sometimes useful, e.g., if s is a string that should be replaced by a default value if it is empty, the expression s or 'foo' yields the desired value.
When the something is an expression like a == b, it is a boolean value that comes out. But that's not the or doing that, it's the comparison.
That means the result of the expression you've used, user_input == 'ADD' or 1, will be True if the input was ADD, or 1 if not.
And it's not until you evaluate that 1 in a truthy context that it gets forced to True. Python's truthiness rules are basically everything is truthy except for:
empty strings.
empty collections (lists, tuples, dictionaries, sets, frozensets, and ranges).
zero of any numeric type (integer, floating point, or complex).
None.
user defined classed that implement the __bool__ method and decide to return a falsey value.
and, of course, False itself.
And, just as an aside, you should probably be aware that input() already gives you a string, there's no need to call str() on it.
In other words, the expression str(input("What? ")) is about as useful as int(42), harmless but unnecessary :-)
The or statement is to check for another condition. Here with your or 1 you are checking if 1 != 0 (because in boolean is 0 is false and everything else is true).
So what you need in the end is to check if user_input is 1.
You need to change your conditions line to if user_input == 'ADD' or user_input == '1' :
EDIT: as paxdiablo said if user_input in ['ADD', '1'] would be a more pythonic way to do it.
Hope this helps and you understood your mistake.
if user_input == 'ADD' or 1 :
The above condition is evaluates to true due to 1.
Related
I would like for the input to remember the first number given to it even if you type something silly on the second input. While right now obviously the loop starts again and asks for both of the inputs again. Is there an easy way to do this?
Calculator
Give a number: 124
Give a number: dwa
This input is invalid.
Give a number: 12
Give a number:
while I would like it to do this:
Calculator
Give first number: 124
Give second number: dwa
This input is invalid.
Give second number: 12
And this is the entire code:
import math
import sys
print("Calculator")
def main():
while True:
try:
kek1 = int(input('Give a number: '))
kek2 = int(input('Give a number: '))
while True:
print('(1) +')
print('(2) -')
print('(3) *')
print('(4) /')
print('(5) sin(number1/number2')
print('(6) cos(number1/number2)')
print('(7) Change numbers')
print('(8) Quit')
print(f'Current numbers are: {kek1} {kek2}')
kaka = input("Please select something (1-6):")
plus = kek1 + kek2
minus = kek1 - kek2
times = kek1 * kek2
divide = kek1 / kek2
sin = math.sin(kek1/kek2)
cos = math.cos(kek1/kek2)
if kaka == "1":
print(f'The result is: {plus}')
if kaka == "2":
print(f'The result is: {minus}')
if kaka == "3":
print(f'The result is: {times}')
if kaka == "4":
print(f'The result is: {divide}')
if kaka == "5":
print(f'The result is: {sin}')
if kaka == "6":
print(f'The result is: {cos}')
if kaka == "7":
kek1 = int(input('Give a number: '))
kek2 = int(input('Give a number: '))
if kaka == "8":
print("Thank you!")
sys.exit(0)
except SystemExit:
sys.exit(0)
except:
print("This input is invalid.")
if __name__=="__main__":
main()
If you have any ideas on how to do this it would be a great help.
Use separate try statements for each input with their own loops
while True:
try:
kek1 = input("First number")
kek1 = int(kek1)
break
except:
print("Invalid")
continue
while True:
try:
kek2 = input("Second number")
kek2 = int(kek2)
break
except:
print("Invalid")
continue
And then go into the rest of your loop.
Sorry for a brief answer but I'm on my phone :P
instead of using try catch, you may use .isnumeric() :
kek1 = input("First number")
while not kek1.isnumeric() :
print("This input is invalid.")
kek1 = input("First number")
kek1 =int(kek1)
kek2 = input("First number")
while not kek2.isnumeric() :
print("This input is invalid.")
kek2 = input("Second number")
kek2 =int(kek1)
Hello I'm trying to add two natural numbers and I wanted the program to continue and have an option to break.
This is my code:
num1 = int(input("Enter first number: "))
num2 = int(input("Enter second number:"))
sum = num1 + num2
if (sum % 2) == 0:
print(sum, "is Even")
else:
print(sum," is Odd")
You can do this using a while loop. So for example:
while True:
play = input("Do you want to play (type no to stop)?")
if play == 'no':
break
num1 = int(input("Enter first number: "))
num2 = int(input("Enter second number:"))
sum = num1 + num2
if (sum % 2) == 0:
print(sum, "is Even")
else:
print(sum," is Odd")
Put all of this code in a loop and add option to continue/ break before taking input from the user.
while(True):
option = int(input("Enter 0 to break. Else, continue")
if option == 0:
break
num1 = int(input("Enter first number: "))
num2 = int(input("Enter second number:"))
sum = num1 + num2
if (sum % 2) == 0:
print(sum, "is Even")
else:
print(sum," is Odd")
print('entry "quit" when you want toe terminate the program')
# infinite loop
while 1:
# input validation
try:
num1 = int(input("Enter first number: "))
num2 = int(input("Enter second number:"))
except ValueError:
print('Please entry a number')
print()
# continue would restart the while loop
continue
if(num1 == 'quit' or num2 == 'quit'):
# break will terminate the while loop
break
sum = num1 + num2
if (sum % 2) == 0:
print(sum, "is Even")
else:
print(sum," is Odd")
You can always nest these statements in a while loop and break on some condition.
def process_results():
num1 = int(input("Enter first number: "))
num2 = int(input("Enter second number:"))
sum = num1 + num2
if (sum % 2) == 0:
print(sum, "is Even")
else:
print(sum,"is Odd")
def get_choice():
print("Enter R to run program or Q to quit:")
choice = input()
return choice
def main():
while(True):
choice = get_choice()
if choice == 'R' or choice == 'r':
process_results()
elif choice == 'Q' or choice == 'q':
print("This program has quit")
else:
print("You must enter R to run program or Q to quit")
main()
Until this semester I didn't even know a while True was a thing. I have to write a while True loop to loop until the user enters 'n' to break. My problem is restarting the loop if the user enters anything other than 'y' or 'n'. Currently, I can loop with any character besides 'n'. I need a way to catch the if say 'q' was entered, "please enter 'y' or 'n'" and prompt the user again. I have considered doing another while loop within the loop but I feel like there is a more optimal way to achieve this.
def main():
userinput = "y"
display_title()
while True:
userinput.lower() == "y"
choice = ""
display_menu()
choice = str(input("Select a conversion (a/b): "))
while choice == "a" or "b":
if choice == "a":
print()
feet = int(input("Enter feet: "))
meters = conversions.to_meters(feet)
print(str(round(meters, 2)) + " meters")
print()
break
elif choice == "b":
print()
meters = int(input("Enter Meters: "))
feet = conversions.to_feet(meters)
print(str(round(feet, 2)) + " feet")
print()
break
elif choice != "a" or "b":
print("Please enter a valid option a or b")
choice = str(input("Select a conversion (a/b): "))
userinput = input("Would you like to perform another conversion? (y/n): ")
if userinput == "n":
print()
print("Thanks, Bye!")
break
You don't need another while loop. You could just need to put the input check to the beginning of the loop and add a check for any other character than 'y' and 'n', e.g.:
def main():
userinput = "y"
display_title()
while True:
if userinput == "n":
print()
print("Thanks, Bye!")
break
elif userinput != "y":
userinput = input("Please select yes (y) or no (n)").lower()
continue
### If you get this far, userinput must equal 'y'
choice = ""
display_menu()
choice = str(input("Select a conversion (a/b): "))
while choice == "a" or "b":
if choice == "a":
print()
feet = int(input("Enter feet: "))
meters = conversions.to_meters(feet)
print(str(round(meters, 2)) + " meters")
print()
break
elif choice == "b":
print()
meters = int(input("Enter Meters: "))
feet = conversions.to_feet(meters)
print(str(round(feet, 2)) + " feet")
print()
break
elif choice != "a" or "b":
print("Please enter a valid option a or b")
choice = str(input("Select a conversion (a/b): "))
userinput = input("Would you like to perform another conversion? (y/n): ").lower()
continue
Be aware, the way you implemented the inner loop asking for the conversion type doesn't allow you to exit the xcript if you suddenly decide abort the procedure e.g. a Keyboard interrupt.
[Edit]
I've not looked at your inner loop. As someone else has suggested,
while choice == "a" or "b"
will always evaluate to True. Why? beacuse internally python will split this expression:
(choice == "a") or "b"
It doesn't matter if choice == "a", as "b" is a non-empty string and thus evaluates to True.
If you were to rewrite yout inner loop as follws:
while choice: # Will evaluate to True as long as choice isn't an empty string.
if choice == "a":
print()
feet = int(input("Enter feet: "))
meters = conversions.to_meters(feet)
print(str(round(meters, 2)) + " meters")
print()
break
elif choice == "b":
print()
meters = int(input("Enter Meters: "))
feet = conversions.to_feet(meters)
print(str(round(feet, 2)) + " feet")
print()
break
else:
print("Please enter a valid option a or b")
choice = input("Select a conversion (a/b): ")
you'll be able to give the user an option to exit the inner loop by inputing nothing and you'll remove an uneccessary double-check if the choice equals a or b.
Tip: If you want to check if one variable matches one of some different options in a while statement, you could use the following:
while var in [opt1, opt2 ...]:
...
Okay, this is my code, it is in python 3.4.3 and I do not know how I would go about allowing user inputs to be floats. Any help would be greatly appreciated.
It is a calculator and works perfectly but it does not allow user inputs to be floats(have decimal places) and a lot of calculations take place with inputs of decimal numbers so it kinda needs it. Thanks if you take the time to read that!
import time
def cls(): print ("\n"*100)
def add():
cls()
print("you have selected addition")
a = input("Enter your first number: ")
while a.isdigit() == False:
print("Enter a numerical interger")
a = input("Enter your first number: ")
if a.isdigit() == True:
a = int(a)
b = input("Enter your second number: ")
while b.isdigit() == False:
print("Enter a numberical interger")
b = input ("enter your second number: ")
if b.isdigit() == True:
b = int(b)
print ("\n")
print ("ANSWER:",a,"+",b,"=",a+b)
print ("\n")
def sub():
cls()
print("you have selected subtraction")
a = input("Enter your first number: ")
while a.isdigit() == False:
print("Enter a numerical interger")
a = input("Enter your first number: ")
if a.isdigit() == True:
a = int(a)
b = input("Enter your second number: ")
while b.isdigit() == False:
print("enter a numerical interger")
b = input("Enter your second number: ")
if b.isdigit() == True:
b = int(b)
print("\n")
print ("ANSWER:",a,"-",b,"=",a-b)
print("\n")
def multi():
cls()
print ("you have selected multiplication")
a = input("Enter your first number: ")
while a.isdigit() == False:
print("Enter a numerical interger")
a = input("Enter your first number: ")
if a.isdigit() == True:
a = int(a)
b = input("Enter your second number: ")
while b.isdigit() == False:
print("enter a numerical interger")
b = input("Enter your second number: ")
if b.isdigit() == True:
b = int(b)
print("\n")
print("ANSWER:",a,"*",b,"=",a*b)
print("\n")
def divide():
cls()
print ("you have selected division")
a = input("Enter your first number: ")
while a.isdigit() == False:
print("Enter a numerical interger")
a = input("Enter your first number: ")
if a.isdigit() == True:
a = int(a)
b = input("Enter your second number: ")
while b.isdigit() == False:
print("enter a numerical interger")
b = input("Enter your second number: ")
if b.isdigit() == True:
b = int(b)
c = (a/b)
if a%b ==0 :
print("\n")
print ("ANSWER:",a,"/",b,"=",int(c))
print("\n")
else :
print("\n")
print ("ANSWER:",a,"/",b,"=",float(c))
print("\n")
def indice():
cls()
print ("you have selected indice multiplication")
a = input("Enter your first number: ")
while a.isdigit() == False:
print("Enter a numerical interger")
a = input("Enter your first number: ")
while (int(a)) >=1000000000000:
print("value too high, enter a lower value")
time.sleep(1)
a = input("Enter your first number: ")
if a.isdigit() == True:
a = int(a)
b = input("Enter your second number: ")
while b.isdigit() == False:
print("enter a numerical interger")
b = input("Enter your second number: ")
while (int(b)) >=1000:
print("value too high, enter a lower value")
time.sleep(1)
b = input("Enter your second number: ")
if b.isdigit() == True:
b = int(b)
print("\n")
print("ANSWER:",a,"To the power of",b,"=",a**b)
print("\n")
def Tconv():
cls()
print("You have selected unit conversion")
print("\n")
print("Enter 1 for conversion from celcius")
print("Enter 2 for conversion from kelvin")
print("\n")
a = input("Enter your choice: ")
if a == "1":
cls()
Tcelc()
elif a == "2":
cls()
Tkelv()
else:
print("Not a valid entry, try again")
time.sleep(1)
cls()
Tconv()
def Tcelc():
print("You have selected conversion from celcius")
print("\n")
a = input("Enter your celcius value: ")
if a.isdigit() == False:
print("Not a valid entry")
time.sleep(1)
cls()
Tcelc()
elif a.isdigit() == True:
print("\n")
print("AWNSER = ",(int(a))+273,"Kelvin")
print("\n")
def Tkelv():
print("You have selected conversion from kelvin")
print("\n")
a = input("Enter your kelvin value: ")
if a.isdigit() == False:
print("Not a valid entry")
time.sleep(1)
Tkelv()
elif a.isdigit() == True:
print("ANSWER = ",(int(a))-273,"Celcius")
print("\n")
def OpEx():
cls()
print("what operation would you like to preform?")
print("\n")
print("Enter 1 for addition")
print("Enter 2 for subtraction")
print("Enter 3 for multliplication")
print("Enter 4 for division")
print("Enter 5 for indice multiplication")
print("Enter 6 for unit conversion")
print("\n")
print("Or type 'close' to exit the program")
print("\n")
task = input("enter your choice: ")
print("\n")
if task == "1":
add()
menu()
elif task == "2":
sub()
menu()
elif task == "3":
multi()
menu()
elif task == "4":
divide()
menu()
elif task == "5":
indice()
menu()
elif task == "6":
Tconv()
menu()
elif task == "close":
exit()
else:
print ("not a valid entry")
time.sleep(2)
OpEx()
def menu():
Q1 = input("Type 'yes' to preform a calculation type 'no' to exit: ")
if Q1 == "yes":
OpEx()
if Q1 == "no":
print("sorry I could not be of futher service")
time.sleep(1)
exit()
else:
print("\n")
print("Not a valid entry, try again")
print("\n")
time.sleep(1)
cls()
menu()
cls()
menu()
You're converting user input to integers, which don't handle floating point all that well. Try converting to float instead, e.g.:
a = float(a)
I would be cautious taking the input as a float because python and many other languages floats are not represented as they may seem. I would recommend pulling the input as a string and then casting it later.
This question already has answers here:
How do I restart a program based on user input?
(6 answers)
Closed 4 years ago.
This is a simple calculator i wrote but after finishing it won't restart the application
this is my code:
def add(x, y):
return x + y
def subtract(x, y):
return x - y
def multiply(x, y):
return x * y
def divide(x, y):
return x / y
print("Select from the list bellow which oporation you want the calculator to do.")
print("A.Add")
print("S.Subtract")
print("M.Multiply")
print("D.Divide")
choice = input("Enter choice(a/s/m/d):")
if choice != 'a' and choice != 's' and choice != 'm' and choice != 'd':
print (" the letter you intered is not in our lists!")
num1 = int(input("Enter an interger as your first number: "))
num2 = int(input("Enter an integer as second number: "))
if choice == 'a':
print(num1,"+",num2,"=", add(num1,num2))
elif choice == 's':
print(num1,"-",num2,"=", subtract(num1,num2))
elif choice == 'm':
print(num1,"*",num2,"=", multiply(num1,num2))
elif choice == 'd':
print(num1,"/",num2,"=", divide(num1,num2))
else:
print("Invalid input")
input("press enter to close")
when its finished i want it to ask the user if they want to restart or not . i used different while looping its not working.
Just loop until the user wants to quit:
def main():
print('Select from the list below which operation you want the calculator to do.')
print("A.Add")
print("S.Subtract")
print("M.Multiply")
print("D.Divide")
while True:
choice = input("Enter choice(a/s/m/d) or q to quit:")
if choice not in {"a", "s", "m", "d","q"}:
print (" the letter you entered is not in our lists!")
continue # if invalid input, ask for input again
elif choice == "q":
print("Goodbye.")
break
num1 = int(input("Enter an integer as your first number: "))
num2 = int(input("Enter an integer as second number: "))
if choice == 'a':
print("{} + {} = {}".format(num1, num2, add(num1, num2)))
elif choice == 's':
print("{} - {} = {}".format(num1, num2, subtract(num1, num2)))
I used str.format to print your output, if choice not in {"a", "s", "m", "d","q"} uses in to test for membership replacing the long if statement.
You might want to wrap the int input inside a try/except to avoid your program crashing if the user does not enter the correct input.
try:
num1 = int(input("Enter an interger as your first number: "))
num2 = int(input("Enter an integer as second number: "))
except ValueError:
continue
If you want to do it like the example in your comment:
def main():
print('Select from the list below which operation you want the calculator to do.')
print("A.Add")
print("S.Subtract")
print("M.Multiply")
print("D.Divide")
while True:
choice = raw_input("Enter choice(a/s/m/d)")
if choice not in {"a", "s", "m", "d","q"}:
print (" the letter you entered is not in our lists!")
continue
num1 = int(input("Enter an integer as your first number: "))
num2 = int(input("Enter an integer as second number: "))
if choice == 'a':
print("{} + {} = {}".format(num1, num2, add(num1, num2)))
elif choice == 's':
print("{} - {} = {}".format(num1, num2, subtract(num1, num2)))
inp = input("Enter 1 to play again or 2 to exit")
if inp == "1":
main()
else:
print("thanks for playing")
break
Instead of this:
if choice != 'a' and choice != 's' and choice != 'm' and choice != 'd' and choice != 'e':
print (" the letter you intered is not in our lists!")
else:
num1 = int(input("Enter an interger as your first number: "))
num2 = int(input("Enter an integer as second number: "))
Use this:
if choice != 'a' and choice != 's' and choice != 'm' and choice != 'd' and choice != 'e':
print (" the letter you intered is not in our lists!")
elif choice==e:
print("goodbye")
break
else:
num1 = int(input("Enter an interger as your first number: "))
num2 = int(input("Enter an integer as second number: "))
You'll need to wrap the part that's processing user input in a while loop. You'll also need an option to break that while loop in your selection process. I added an input value of e that handles exiting the loop. Your first if statement and the else statement at the end were redundant, so I switched them around a little as well.
def add(x, y):
return x + y
def subtract(x, y):
return x - y
def multiply(x, y):
return x * y
def divide(x, y):
return x / y
while True:
print("Select from the list bellow which oporation you want the calculator to do.")
print("A.Add")
print("S.Subtract")
print("M.Multiply")
print("D.Divide")
print("E.Exit")
choice = input("Enter choice(a/s/m/d/e):")
if choice != 'a' and choice != 's' and choice != 'm' and choice != 'd' and choice != 'e':
print (" the letter you intered is not in our lists!")
else:
num1 = int(input("Enter an interger as your first number: "))
num2 = int(input("Enter an integer as second number: "))
if choice == 'a':
print(num1,"+",num2,"=", add(num1,num2))
elif choice == 's':
print(num1,"-",num2,"=", subtract(num1,num2))
elif choice == 'm':
print(num1,"*",num2,"=", multiply(num1,num2))
elif choice == 'd':
print(num1,"/",num2,"=", divide(num1,num2))
elif choice == 'e':
print("Goodbye")
break