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()
Related
I'm trying to build a calculator with a loop until I choose to break it or end it.
Can you please suggest?
Thank you in advance,
Max
new_operation = input("press enter to make a new operation or type the word exit to finish")
num1 = int(input("Enter a number: "))
op = input("Enter the operator: ")
num2 = int(input("Enter a second number: "))
while new_operation != ("no"):
if op == ("+"):
print (num1 + num2)
elif op == ("-"):
print (num1 - num2)
elif op == ("*"):
print (num1 * num2)
elif op == ("/"):\
print (num1 / num2)
else:
print ("Invalid operation")
new_operation = input("make a new operation")
Your code looks good, but need some tweak to make it "do while" loop kind of implementation.
while True:
num1 = int(input("Enter a number: "))
op = input("Enter the operator: ")
num2 = int(input("Enter a second number: "))
if op == ("+"):
print (num1 + num2)
elif op == ("-"):
print (num1 - num2)
elif op == ("*"):
print (num1 * num2)
elif op == ("/"):\
print (num1 / num2)
else:
print ("Invalid operation")
new_operation = input("press enter to make a new operation or type the word exit to finish")
if(new_operation == ("no")):
break
Some suggestions:
Check your indentation, as commented above. Python is sensitive to that.
Make sure your inputs and outputs are more consistent and useful. Your prompt says I should type exit, but your code requires them to type no...
Your looping structure is a bit broken. This is to be expected for somebody new to coding. One of my favorites for this case is:
print('Welcome to the calculator!')
do_run = True
while do_run:
...
do_run = input('Would you like to continue [y/n]: ')[0].lower() == 'y'
I am making a python calculator program that asks a user after completing one calculation whether they want to continue or not. If the user says Yes the loop should run or else it should stop. I am Facing a problem where a user says yes or no the loop still executes anyhow. Why is it so ???
print("This is a Calculator In Python. !!!")
print("I Can Do Addition, Subtraction, Multiplication and Division.!!")
def addition():
print("Please Don't Enter Float Values Here.")
num1 = int(input("Enter First Number.!!"))
num2 = int(input("Enter Second Number. !!"))
result = num1 + num2
return result
def subtraction():
print("Please Don't Enter Float Values Here.")
num1 = int(input("Enter First Number.!!"))
num2 = int(input("Enter Second Number.!!"))
result = num1 - num2
return result
def multiplication():
print("You Can Enter Float Values Here.")
num1 = float(input("Enter First Number.!!"))
num2 = float(input("Enter Second Number.!!"))
result = num1 * num2
return result
def division():
print("You Can Enter Float Values Here.")
num1 = float(input("Enter First Number.!!"))
num2 = float(input("Enter Second Number.!!"))
result = num1 / num2
return result
print("""1. a for Addition
2. s for subtraction
3. m for multiplication
4. d for Division""")
select = "Yes"
while select:
choice = str(input("You Choose The Operation."))
if choice == "a":
print(addition())
elif choice == "s":
print(subtraction())
elif choice == "m":
print(multiplication())
elif choice == "d":
print(division())
else:
print("Invalid Input")
select=str(input('Continue Yes or No '))
print("Thank you..!")
You've defined your loop as while select, which means as long as select is considered to not be None, it will continue looping
In your loop, you assign the user input to select, which means as long as the user inputs anything, it will always keep looping.
To fix this, you should have the while loop check if select is "yes":
while select.lower().strip() == "yes":
choice = input("You Choose The Operation. ")
if choice == "a":
print(addition())
elif choice == "s":
print(subtraction())
elif choice == "m":
print(multiplication())
elif choice == "d":
print(division())
else:
print("Invalid Input")
select = input("Continue Yes or No ")
print("Thank you..!")
Also, input() returns a string so you don't need to wrap it in a str() call.
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
Hello I am having a trouble while doing my simple calculator code :D
def cal():
while True:
print ("welcome to my calculator!")
print("choose an operation")
op = input(" +, - ,/ ,*")
if op == "+":
num1 = float(input("enter your first number:"))
num2 = float(input("enter your second number:"))
print(str(num1 + num2)
elif op == "/":
num1 = float(input("enter your first number:"))
num2 = float(input("enter your second number:"))
print(str(num1 / num2)
else:
break
cal()
When ever I run the code it says invalid syntax at the elif
what is wrong here?
You never closed the bracket on the print function. Same goes for the other if statement. You should use indentation of 4 spaces in the future, too.
if op == "+":
num1 = float(input("enter your first number:"))
num2 = float(input("enter your second number:"))
print(str(num1 + num2))
You missed a bunch of brackets. If you want to take your program further use this as a model:
# This function adds two numbers
def add(x, y):
return x + y
# This function subtracts two numbers
def subtract(x, y):
return x - y
# This function multiplies two numbers
def multiply(x, y):
return x * y
# This function divides two numbers
def divide(x, y):
return x / y
print("Select operation.")
print("1.Add")
print("2.Subtract")
print("3.Multiply")
print("4.Divide")
# Take input from the user
choice = input("Enter choice(1/2/3/4):")
num1 = int(input("Enter first number: "))
num2 = int(input("Enter second number: "))
if choice == '1':
print(num1,"+",num2,"=", add(num1,num2))
elif choice == '2':
print(num1,"-",num2,"=", subtract(num1,num2))
elif choice == '3':
print(num1,"*",num2,"=", multiply(num1,num2))
elif choice == '4':
print(num1,"/",num2,"=", divide(num1,num2))
else:
print("Invalid input")
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