Python Error on while True loop - python

total = 0
print ("Enter first number")
num1 = input()
print ("Enter 1)Add 2)Minus 3)Multiply 4)Divide")
choice = input()
while True:
print("Wrong Answer Pick Again")
print("Enter 1)Add 2)Minus 3)Multiply 4)Divide")
choice = input()
if choice => 1 and choice =< 4:
break
if choice == 1:
print ('Enter second number')
num2 = input()
total = num1 + num2
elif choice == 2:
print ('Enter second number')
num2 = input()
total = num1 - num2
elif choice == 3:
print ('Enter second number')
num2 = input()
total = num1 * num2
elif choice == 4:
print ('Enter second number')
num2 = input()
total = num1 / num2
print("Total")
print (total)
I`m getting a syntax error on the "if choice => 1 and choice =<4:" can some one please help. I have tried so many different things and nothing have worked.

This script should work for you :
total = 0
print ("Enter 1)Add 2)Minus 3)Multiply 4)Divide")
choice = int(input())
for _ in range(int(input("total test cases"))):
if choice >= 1 and choice <= 4:
if choice == 1:
print ("Enter first number")
num1 = int(input())
print ('Enter second number')
num2 = int(input())
total = num1 + num2
print("Total is: ",total)
choice=int(input("enter choice again"))
elif choice == 2:
print ("Enter first number")
num1 = int(input())
print ('Enter second number')
num2 = int(input())
total = num1 - num2
print("Total is: ",total)
choice=int(input("enter choice again"))
elif choice == 3:
print ("Enter first number")
num1 = int(input())
print ('Enter second number')
num2 = int(input())
total = num1 * num2
print("Total is: ",total)
choice=int(input("enter choice again"))
elif choice == 4:
print ("Enter first number")
num1 = int(input())
print ('Enter second number')
num2 = int(input())
total = num1 / num2
print("Total is: ",total)
choice=int(input("enter choice again"))
else:
print("wrong number entered")
choice=int(input("enter again"))
Note:If you find this answer helpful you can mark this answer correct

Related

How do I repeat a program in Python with this code?

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()

IF statements and Input

I am just practising basic python and attempting to build a calculator with only addition, subtraction, and multiplication functions. When I run the code and input 1, 2, or 3, I get no output.
Here is my code:
question1 = input("Enter 1 to add, 2 to substract, or 3 to multiply: ")
if question1 == 1:
num1 = input("Enter a number: ")
num2 = input("Enter another number: ")
result = float(num1) + float(num2)
print(result)
elif question1 == 2:
num1 = input("Enter a number: ")
num2 = input("Enter another number: ")
result = float(num1) + float(num2)
print(result)
elif question1 == 3:
num1 = input("Enter a number: ")
num2 = input("Enter another number: ")
result = float(num1) + float(num2)
print(result))
When you get some input with input() in Python3, you get a string.
Test it with following:
foo = input()
print(type(foo))
The result will be <class 'str'>(it means foo's type is string) regardless of your input. If you want to use that input as a integer, you will have to change the type to int(integer).
You should use int(input()) to get a integer like the following:
question1 = int(input("Enter 1 to add, 2 to substract, or 3 to multiply: "))
You have to change the number inputs in each of the if-else blocks too:
if question1 == 1:
num1 = int(input("Enter a number: "))
num2 = int(input("Enter another number: "))
result = num1 + num2
print(result)
Or, you can just change it when you want to calculate:
result = int(num1) + int(num2)
You need to convert your input to the integer. Try this code:
question1 = int(input("Enter 1 to add, 2 to substract, or 3 to multiply: "))
if question1 == 1:
num1 = int(input("Enter a number: "))
num2 = int(input("Enter another number: "))
result = num1 + num2
print(result)
elif question1 == 2:
num1 = int(input("Enter a number: "))
num2 = int(input("Enter another number: "))
result = num1 - num2
print(result)
elif question1 == 3:
num1 = int(input("Enter a number: "))
num2 = int(input("Enter another number: "))
result = num1 * num2
print(result)
You are well on your way! As mentioned in the comments, all your statements are False because input() just by itself returns string type which will never be equal to an integer.
You just have to change the all the input() of your code to convert it as an int to be stored. Below is an example:
question1 = int(input("Enter 1 to add, 2 to substract, or 3 to multiply: "))

Error in this python code [closed]

Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
Closed 5 years ago.
This question was caused by a typo or a problem that can no longer be reproduced. While similar questions may be on-topic here, this one was resolved in a way less likely to help future readers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Improve this question
while True:
print ("Options")
print ("Write 'Quit' if you want to exit")
print ("Write '+'if you want to make an addition")
print ("Write '-' if you want to make a sottration")
print ("Write '*' if you want to make a moltiplication")
print ("Write '/' if you wantto make a division")
user_input == input(":")
if user_input == ("+")
num1 = float(input("Enter a number...")
num2 = float(input("Enter the second number...")
result = str(num1+num2)
print("The result is"+ result)
elif user_input == ("-")
num1 = float(input("Enter a number...")
num2 = float(input("Enter the second number...")
result = str(num1-num2)
print("The result is"+ result)
elif user_input == ("*")
num1 = float(input("Enter a number...")
num2 = float(input("Enter the second number...")
result = str(num1*num2)
print("The result is"+ result)
elif user_input == ("/")
num1 = float(input("Enter a number...")
num2 = float(input("Enter the second number...")
print ("The result is"+ result)
This is the code I have created in python 2.7, but it does not work. I think there's an indentation error. Can you help me?
Fix your indentation and add a colon after each if-statement as the following and change user_input == input(':') to user_input = input(':'):
while True:
print ("Options")
print ("Write 'Quit' if you want to exit")
print ("Write '+'if you want to make an addition")
print ("Write '-' if you want to make a sottration")
print ("Write '*' if you want to make a moltiplication")
print ("Write '/' if you wantto make a division")
user_input = input(":") # fix this line
if user_input == ("+"):
num1 = float(input("Enter a number..."))
num2 = float(input("Enter the second number..."))
result = str(num1+num2)
print("The result is"+ result)
elif user_input == ("-"):
num1 = float(input("Enter a number..."))
num2 = float(input("Enter the second number..."))
result = str(num1-num2)
print("The result is"+ result)
elif user_input == ("*"):
num1 = float(input("Enter a number..."))
num2 = float(input("Enter the second number..."))
result = str(num1*num2)
print("The result is"+ result)
elif user_input == ("/"):
num1 = float(input("Enter a number..."))
num2 = float(input("Enter the second number..."))
result = str(num1/num2)
print ("The result is"+ result)
EDIT:
Below is a better version of your code that fixes few errors, like reading string input, avoid dividing by zero exception and removing float() type casting because in python 2.7 input() already does that for you.
while True:
print("Options")
print("Write 'Quit' if you want to exit")
print("Write '+'if you want to make an addition")
print("Write '-' if you want to make a sottration")
print("Write '*' if you want to make a moltiplication")
print("Write '/' if you wantto make a division")
user_input = raw_input(":")
if user_input == '+':
num1 = input("Enter a number...")
num2 = input("Enter the second number...")
print('The result is {}'.format(num1+num2))
elif user_input == '-':
num1 = input("Enter a number...")
num2 = input("Enter the second number...")
print('The result is {}'.format(num1-num2))
elif user_input == '*':
num1 = input("Enter a number...")
num2 = input("Enter the second number...")
print('The result is {}'.format(num1*num2))
elif user_input == '/':
num1 = input("Enter a number...")
num2 = input("Enter the second number...")
if num2 == 0:
print("Can't divide by zero.")
else:
print("The result is {}".format(num1/num2))
Also as suggested by other users here is an improved version:
while True:
print("Options")
print("Write 'Quit' if you want to exit")
print("Write '+'if you want to make an addition")
print("Write '-' if you want to make a sottration")
print("Write '*' if you want to make a moltiplication")
print("Write '/' if you wantto make a division")
user_input = raw_input(":")
num1 = input("Enter a number...")
num2 = input("Enter the second number...")
if user_input == "+":
result = str(num1+num2)
elif user_input == "-":
result = str(num1-num2)
elif user_input == "*":
result = str(num1*num2)
elif user_input == "/":
if num2 == 0:
result = "Can't divide by zero"
else:
result = str(num1/num2)
print("The result is", result)

Simpel Python Calculator - Syntax Error - Indentation errors

I recently started learning Python. I have never coded before, but it seemed like a challenge. The first thing I have made is this calculator. However, I can't seem to get it to work.
while True:
print("Typ 'plus' to add two numbers")
print("Typ 'min' to subtract two numbers")
print("Typ 'multiplication' multiply two numbers")
print("Typ 'division' to divide two numbers")
print("Typ 'end' to abort the program")
user_input = input(": ")
if user_input == "end"
break
elif user_input == "plus":
num1 = float(input("Give a number: "))
num2 = float(input("Give another number: "))
result = str(num1 + num2)
print("The anwser is: " + str(result))
elif user_input == "min":
num1 = float(input("Give a number: "))
num2 = float(input("Give another number: "))
result = str(num1 - num2)
print("The anwser is: " + str(result))
elif user_input == "maal":
num1 = float(input("Give a number:"))
num2 = float(input("Give another number: "))
result = str(num1 * num2)
print("The anwser is: " + str(result))
elif user_input == "deel":
num1 = float(input("Give a number: "))
num2 = float(input("Give another number: "))
result = str(num1 + num2)
print("The anwser is: " + str(result))
else:
print ("I don't understand!")
I know it will probably something stupid, I am still very much learning. Just trying to pickup a new skill instead of bothering my friends who do know how to code.
You missed a colon after an this if statement
if user_input == "end"
break
Should Be:
if user_input == "end":
break

shortening a calculator in python

I have managed to create a small calculator in Python, but I am trying to shorten the code unsucsessfully. Can anyone help please?
elif queencommand == "/calc addition" :
num1 = input("Enter first number")
num2 = input("Enter second number")
Answer = (int(num1) + int(num2))
input(Answer)
elif queencommand == "/calc subtraction" :
num1 = input("Enter first number")
num2 = input("Enter second number")
Answer = (int(num1) - int(num2))
input(Answer)
elif queencommand == "/calc multiplication" :
num1 = input("Enter first number")
num2 = input("Enter second number")
Answer = (int(num1) * int(num2))
input(Answer)
elif queencommand == "/calc division" :
num1 = input("Enter first number")
num2 = input("Enter second number")
Answer = (int(num1) / int(num2))
input(Answer)
I am not able to do two operations at once either.
Use functions from the operator module or simple functions you define yourself to the calculation work, then map the operation name from the queencommand string to those functions:
import operator
ops = {
'addition': operator.add,
'subtraction': operator.sub,
'multiplication': operator.mul,
'division': operator.truediv
}
if queencommand.startswith("/calc"):
operation = queencommand.partition(' ')[-1]
if operation in ops:
num1 = input("Enter first number")
num2 = input("Enter second number")
Answer = ops[operation](int(num1), int(num2))
operator.add could be replaced by lambda a, b: a + b, etc. if you don't want to use a module for those operations.
Here is a fully fledged calculator. See if it helps:
def multiplication():
num1 = int(input("First #: "))
num2 = int(input("Second #: "))
ans = num1 * num2
print(ans)
def addition():
num1 = int(input("First #: "))
num2 = int(input("Second #: "))
ans = num1 + num2
print(ans)
def subtraction():
num1 = int(input("First #: "))
num2 = int(input("Second #: "))
ans = num1 - num2
print(ans)
def division():
num1 = int(input("First #: "))
num2 = int(input("Second #: "))
ans = num1 / num2
print(ans)
def Help():
print("""Welcome to Calculator P1!!!
Type "x" for multiplication.
Type "+" for addition.
Type "-" for subtraction.
Type "/" for division.""")
while True:
print("Type 'help' for introduction or instructions")
choice = input("Operator: ")
if choice == "x" or choice == "muliplication":
multiplication()
elif choice == "+" or choice == "addition":
addition()
elif choice == "-" or choice == "subtraction":
subtraction()
elif choice == "/" or choice == "division":
division()
elif choice == "help":
Help()
answer = input('Run again? (y/n): ')
if answer == 'n':
break
elif answer == 'y':
continue
else:
print("""Unrecognized Input.
<<<<RESTARTING PROGRAM>>>>""")
continue

Categories