Basic Calculator program not working in Python idle [closed] - python

Closed. This question needs debugging details. It is not currently accepting answers.
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.
Closed 8 years ago.
Improve this question
loop = 1
choice = 0 #holds the user choice for menu
while (loop == 1):
print ("Welcome to calci.py")
print ("your options are:")
print (" ")
print ("1. Addition")
print ("2. Subtraction")
print ("3. Multiplication")
print ("4. Division")
print ("5. Quit calculator.py")
print (" ")
choice = input("Choose your option: ")
if (choice == 1):
add1 = input("Add this: ")
add2 = input("to this: ")
print (add1, "+", add2, "=", add1 + add2)
elif (choice == 2):
sub2 = input("Subtract this: ")
sub1 = input("from this: ")
print (sub1, "-", sub2, "=", sub1 - sub2)
elif (choice == 3):
mul1 = input("Multiply this: ")
mul2 = input("with this: ")
print (mul1, "*", mul2, "=", mul1 * mul2)
elif (choice == 4):
div1 = input("Divide this: ")
div2 = input("by this: ")
print (div1, "/", div2, "=", div1 / div2)
elif (choice == 5):
loop = 0
print ("Thankyou for using calci.py!")
I am new to the python world, I have written and compiled the calculator code, but its not working,Need help!!

Your code:
choice = input("Choose your option: ")
if (choice == 1):
here input will return string output. So in your if condition you will need to do like:
choice = input("Choose your option: ")
if (choice == '1'):
Then it will work. But remember it's will concat two string in above example. So may be you will need to convert that string to integer and then perform your arithmetic.
So you could use like
intchoice = int(choice)
if (intchoice == 1):
similarly you need to follow for your add1/add2 and other input parameters.

I attempted to run your code in Terminal, and it infinitely loops as given.
You initially set choice to zero, but your code does not handle zero, so it doesn't know what to do so it just loops.
Try adding an else block and the end of your elif statements to catch anything that elif doesn't account for.
EX:
else:
print("Error")
loop=0
I see your using a while loop to try and make the program run continually until the user quits.
try using input() or raw_input() to get user choices for the operation. Other then that great job!

Related

How do I repeat the code form the top after a while loop?

I want this code to repeat from the top. Im trying to build a calculator app and when I say "Do you want to continue (y) or go back to home (n): " I want it so that if the user says "n" then it will start the code from the beggining. Here is the code I want to do this in.
# Importing stuff
import math
import random
import time
import numpy as np
def startup():
global ask
print("Welcome to this math python program")
ask = input(
"Do you wnat to solve 1, add, 2, subtract, 3, multiply, divide, or 5 other complex problems? (answer with 1, 2, 3, 4, or 5: "
)
startup()
# Some stuff to make it look better
print(" ")
print(" ")
def add():
print("Addition")
num1 = int(input("First number: "))
num2 = int(input("Second Number: "))
num = num1 + num2
print("The answer is " + str(num))
# Subtract
def subtract():
print("Subtraction")
num3 = int(input("First number: "))
num4 = int(input("Second Number: "))
num5 = num3 - num4
print("The answer is " + str(num5))
print(" ")
def multiply():
print("Multiplication")
num6 = int(input("First number: "))
num7 = int(input("Second Number: "))
num8 = num6 * num7
print("The answer is " + str(num8))
print(" ")
def divide():
print("Division")
num9 = int(input("First number: "))
num10 = int(input("Second Number: "))
num11 = num9 / num10
print("The answer is " + str(num11))
print(" ")
def squareRoot():
print("Square Root")
asksqrt = int(
input("What number would you like to find the square root of: "))
answer1 = math.sqrt(asksqrt)
print("The square root of " + str(asksqrt) + " is: " + str(answer1))
print(" ")
def cubeRoot():
print("Cube root")
num12 = int(input("What number do you want to find the cube root of: "))
cube_root = np.cbrt(num12)
print("Cube root of ", str(num12), " is ", str(cube_root))
print(" ")
def exponent():
print("Exponents")
num13 = int(input("First you are going to tell me the number: "))
num14 = int(input("Next you are going to tell me the exponent: "))
num15 = num13**num14
print(str(num13) + " to the power of " + str(num14) + " is " + str(num15))
print(" ")
# While loops
while ask == "1":
print(" ")
add()
ask4 = input("Do you want to continue (y) or go back to home (n): ")
while ask4 == "y":
add()
while ask == "2":
print(" ")
subtract()
ask5 = input("Do you want to continue (y) or go back to home (n): ")
while ask5 == "y":
add()
while ask == "3":
print(" ")
multiply()
ask6 = input("Do you want to continue? (y/n) ")
while ask6 == "y":
add()
while ask == "4":
print(" ")
divide()
ask7 = input("Do you want to continue (y) or go back to home (n): ")
while ask7 == "y":
add()
while ask == "5":
ask2 = input(
"Do you want to do a 1, square root equation, 2, cube root equation, or 3 an exponent equation? (1, 2, 3): "
)
print(" ")
while ask2 == "1":
print(" ")
squareRoot()
ask8 = input("Do you want to continue (y) or go back to home (n): ")
while ask8 == "y":
add()
while ask2 == "2":
print(" ")
cubeRoot()
ask9 = input("Do you want to continue (y) or go back to home (n): ")
while ask9 == "y":
add()
while ask2 == "3":
print(" ")
exponent()
ask10 = input("Do you want to continue (y) or go back to home (n): ")
while ask10 == "y":
add()
I'm a begginer so I dont know a lot. If you could tell me what I can do better that would be much appreciated.
In this case, it's good to take a step back and think of what your main entrypoint, desired exit scenario and loop should look like. In pseudo-code, you can think of it like this:
1. Introduce program
2. Ask what type of calculation should be conducted
3. Do calculation
4. Ask if anything else should be done
5. Exit
At points 2 and 4, your choices are either exit program or do a thing. If you want to 'do a thing' over and over, you need a way of going from 3 back into 2, or 4 back into 3. However, steps 2 and 4 are basically the same, aren't they. So let's write a new main loop:
EDIT: Decided to remove match/case example as it's an anti-pattern
if __name__ == "__main__": # Defines the entrypoint for your code
current_task = 'enter'
while current_task != 'exit':
current_task = ask_user_for_task() # The user will input a string, equivalent to your startup()
if current_task == 'add': # If its 'add', run add()
add()
elif current_task == 'subtract':
subtract()
else:
current_task = 'exit' # If its 'exit' or anything else not captured in a case, set current_task to 'exit'. This breaks the while loop
ask_user_for_task() will be an input() call where the user gives the name of the function they want to execute:
def ask_user_for_task():
return input("Type in a calculation: 'add', 'subtract', ...")
This answer is not perfect - what if you don't want to exit if the user accidentally types in 'integrate'. What happens if the user types in "Add", not 'add'? But hopefully this gives you a starting point.
What you want to do can be greatly simplified. The number you choose correlates to the index of the operation in funcs. Other than that, the program is so simple that each part is commented.
Using this method eliminates the need for excessive conditions. The only real condition is if it is a 2 argument operation or a 1 argument operation. This is also very easily extended with more operations.
import operator, math, numpy as np
from os import system, name
#SETUP
#function to clear the console
clear = lambda: system(('cls','clear')[name=='posix'])
"""
this is the index in `funcs` where we switch from 2 arg operations to 1 arg operations
more operations can be added to `funcs`
simply changing this number accordingly will fix all conditions
"""
I = 6
"""
database of math operations - there is no "0" choice so we just put None in the 0 index.
this tuple should always be ordered as:
2 argument operations, followed by
1 argument operations, followed by
exit
"""
funcs = (None, operator.add, operator.sub, operator.mul, operator.truediv, operator.pow, math.sqrt, np.cbrt, exit)
#operation ranges
twoarg = range(1,I)
onearg = range(I,len(funcs))
#choice comparison
choices = [f'{i}' for i in range (1,len(funcs)+1)]
#this is the only other thing that needs to be adjusted if more operations are added
menu = """
choose an operation:
1:add
2:subtract
3:multiply
4:divide
5:exponent
6:square root
7:cube root
8:quit
>> """
#IMPLEMENT
while 1:
clear()
print("Supa' Maffs")
#keep asking the same question until a valid choice is picked
while not (f := input(menu)) in choices: pass
f = int(f)
#vertical space
print("")
if f in twoarg: x = (int(input("1st number: ")), int(input("2nd number: ")))
elif f in onearg: x = (int(input("number: ")), )
else : funcs[f]() #exit
#unpack args into operation and print results
print(f'answer: {funcs[f](*x)}\n')
input('Press enter to continue')
if you want to, you can see the code below:
while(input("want to continue (y/n)?") == 'y'):
operation = input("operation: ")
num_1 = float(input("first num: "))
num_2 = float(input("second num: "))
match operation:
case "+":
print(num_1 + num_2)
case "-":
print(num_1 - num_2)
case "*":
print(num_1 * num_2)
case "/":
print(num_1 / num_2)
case other:
pass
make sure you have the version 3.10 or later of python

i want to add code that rejects any invalid answers [duplicate]

This question already has answers here:
Asking the user for input until they give a valid response
(22 answers)
Closed 10 months ago.
#for project 2
# division
def divide(a, b):
return (a / b)
# palindrome
def isPalindrome(s):
return s == s[::-1]
print("Select operation.")
print("1. Divide")
print("2. Palindrome")
print("3. Square root")
while True:
choice = input("Enter choice(1/2/3): ")
if choice == '1':
num1 = float(input("Enter first number: "))
num2 = float(input("Enter second number: "))
print(num1, "/", num2, "=", divide(num1, num2))
elif choice == '2':
def isPalindrome(s):
return s == s[::-1]
s = str(input("Enter word:"))
ans = isPalindrome(s)
if ans:
print (s+" "+"is a palindrome.")
else:
print (s+" "+"is not a palindrome.")
elif choice == '3':
threenumber = float(input("Enter a number: "))
sqrt = threenumber ** 0.5
print ("The square root of " + str(threenumber) + " is " + "sqrt", sqrt)
next_calculation = input("Let's do next calculation? (yes/no): ")
if next_calculation == "no":
break
else:
print("Invalid Input")
When testing it myself, in the beginning, if I entered any other input rather than 1, 2, or 3, it would jump to the "next_calculation" function. I want it to say "That's not an option, silly." instead.
When I select 1 or 3 if I enter anything other than a number the program will stop. I want it to say "That's not a valid number, silly."
How do I do this?
You can do that with continue to ignore the loop and return to the start after checking if the input is in your list of possible values
if choice not in ('1', '2', '3'):
print("Invalid input")
continue
Put that after the input
I'd add right after choice = input("Enter choice(1/2/3): "), this snippet:
while (choice not in ['1','2','3']):
print("That's not a valid number, silly.")
choice = input("Enter choice(1/2/3): ")
In this way, you won't reach the end of the cycle unless you give a correct number.
I think you should try to use Switch in this case, instead of if/elses.
Check out this answer.
Otherwise, #Icenore answer seems to be correct. Also, remember to correctly ident your code, your current else: code is being executed after your while True:

Simple Math quiz in phython

Being an absolute beginner, I'm facing some issues in my simple math quiz in python.
First Issue:
In my programme, the answer is stuck with option d only, i want to swap the correct option between the choice a-d every time.
Second Issue:
i declare a variable "score" and i try to increment it's value on each correct answer, but it's is not updating.
Third Issue :
I want to clear Previous question on selecting correct option and ask a new question.
My code is :
import random
def myFunction():
score=0
num1= random.randint(0,1000)
num2= random.randint(1,1000)
num2=num1
if num1==num2:
num2=num2+random.randint(0,50)
print(num1, "+" , num2, "= ?")
result=num1+num2
option1=result+random.randint(1,25)
option2=result+random.randint(1,25)
option3=result+random.randint(1,25)
d=result
print("(a)", option1)
print("(b)", option2)
print("(c)", option3)
print("(d)", result)
value= input("Select the correct option \n Answer:")
if value=="d":
print("Correct Answer...!!")
score+=1 #update score
myFunction()
else:
result="d"
print("Wrong Answer, Correct option is ","(",result,")")
print("Your Score is : ", score)
exit()
myFunction()
This code works with following changes:
You should use a while loop to iteratively get a response from user (otherwise you will eventually exceed recursion depth)
It continues on wrong answers
Stops on the first correct answer
If you enters a blank line then it also stops (i.e. providing user a way to exit the program)
Code
import platform
import os
import sys
import random
def clear():
'''
Clears console
'''
system_ = platform.system()
print('system_', system_)
if system_ == 'Windows':
os.system('cls')
else:
# Linux or Mac
os.system('clear')
def myFunction():
score=0
# Use while loop rather than recusively calling function
while True:
# Select two numbers
num1= random.randint(0,1000)
num2= random.randint(1,1000)
if num1==num2:
num2=num2+random.randint(0,50)
print('clear the screen')
clear() # Clear console
print(num1, "+" , num2, "= ?")
result = num1 + num2 # the answer for sum
option1 = result + random.randint(1,25)
option2 = result + random.randint(1,25)
option3 = result+random.randint(1,25)
# options for sum
options = [option1, option2, option3, result]
# Place options in random order
random.shuffle(options)
choices = "abcd"
for choice, option in zip(choices, options):
print(f"{choice} {option}")
value= input("Select the correct option (or blank line to quit) \n Answer:")
while value and value not in choices: # checks for blank line and if entry in choices
print("Select letter from ", *choices)
value= input("Select the correct option (or blank line to quit\n Answer:")
if value is None:
# Blank line
print(f'Final score was {score}')
break # done with while loop
index = choices.index(value)
if options[index] == result:
print("Correct Answer...!!")
score += 1 #update score
print(f"Your Score is : {score}")
else:
print(f"Wrong Answer, Correct option is ({result})")
print(f"Your Score is : {score}")
myFunction()
I don't know how you want your code to work. But I edited your code as below. Once you entered wrong answer you will be out of from quiz.
import random
def myFunction():
global score
num1= random.randint(0,1000)
num2= random.randint(1,1000)
# num2=num1
if num1==num2:
num2=num2+random.randint(0,50)
print(num1, "+" , num2, "= ?")
result=num1+num2
option1=result+random.randint(1,25)
option2=result+random.randint(1,25)
option3=result+random.randint(1,25)
d=result
choice = [option1,option2,option3,result]
random.shuffle(choice)
print("(a)", choice[0])
print("(b)", choice[1])
print("(c)", choice[2])
print("(d)", choice[3])
value= input("Select the correct option \n Answer:")
if (value == "a" and d == choice[0]) or (value == "b" and d == choice[1]) or (value == "c" and d == choice[2]) or (value == "d" and d == choice[3]):
print("Correct Answer...!!")
score+=1 #update score
else:
result= d
print("Wrong Answer, Correct option is ","(",result,")")
print("Your Score is : ", score)
exit()
score = 0
while True:
myFunction()
print("Score : ", score)enter code here
This code first stores the answer in a random option, and then the answer variable is given the value of the option, i.e a,b,c or d. I added the score variable as a parameter to the function and every time a correct answer is given the value of the parameter will be set equal to the score
import random
def myFunction(score=0):
num1 = random.randint(0,1000)
num2 = random.randint(1,1000)
if num1==num2:
num2=num2+random.randint(0,50)
print(num1, "+" , num2, "= ?")
result=num1+num2
option1=result+random.randint(1,25)
option2=result+random.randint(1,25)
option3=result+random.randint(1,25)
option4=result+random.randint(1,25)
answer = random.randint(1,5)
if answer==1:
option1 = result
answer = 'a'
if answer==2:
option2 = result
answer = 'b'
if answer==3:
option3 = result
answer = 'c'
if answer==4:
option4 = result
answer = 'd'
print("(a)", option1)
print("(b)", option2)
print("(c)", option3)
print("(d)", option4)
value= input("Select the correct option \n Answer:")
if value==answer:
print("Correct Answer...!!")
score = score + 1 #update score
myFunction(score)
else:
result=answer
print("Wrong Answer, Correct option is ","(",result,")")
print("Your Score is : ", score)
exit()
myFunction()

Why is my code not probing me to the if or elif section?

The code below only skips me to the else: part...
print ("Welcome to my first program")
print ("Do you want to play my game ?")
x = "Start"
z = "Stop"
print("Options are: ")
print ("1",x)
print ("2",z)
Answer = input("Answer here: ")
a = Answer
if a = x :
print (Answer,"So you want to play")
elif a = z :
print (Answer,"So you do not want to play")
else :
print ("Invalid entry...")
print ("Try again next time.")
print ("Doneringo")
There are two errors in your code.
Your if statement is not correct. You have to give == instead of =
You are asking using to answer 1 or 2 but you are checking if the answer is Start or Stop. You need to change that.
Here's the modified code:
print ("Welcome to my first program")
print ("Do you want to play my game ?")
x = "Start"
z = "Stop"
print("Options are: ")
print ("1",x)
print ("2",z)
Answer = input("Answer here: ")
a = Answer
if a == '1' : # changed to == instead of =. Also checking against 1 instead of x
print (Answer,"So you want to play")
elif a == '2' : # changed to == instead of =. Also checking against 1 instead of z
print (Answer,"So you do not want to play")
else :
print ("Invalid entry...")
print ("Try again next time.")
print ("Doneringo")
Results of this will be:
Run #1 with answer = 1
Welcome to my first program
Do you want to play my game ?
Options are:
1 Start
2 Stop
Answer here: 1
1 So you want to play
Doneringo
Run #2 with answer = 2
Welcome to my first program
Do you want to play my game ?
Options are:
1 Start
2 Stop
Answer here: 2
2 So you do not want to play
Doneringo
Run #3 with answer = Start
Welcome to my first program
Do you want to play my game ?
Options are:
1 Start
2 Stop
Answer here: Start
Invalid entry...
Try again next time.
Doneringo
Your code has errors
Change it to this.
x = "Start"
z = "Stop"
print("Options are: {} or {}" .format(x,z))
Answer = input("Answer here: ")
if Answer == x :
print (Answer,"So you want to play")
elif Answer == z :
print (Answer,"So you do not want to play")
else :
print ("Invalid entry...")
print ("Try again next time.")
print ("Doneringo")

How would I assign the list of operators so that the random numbers are worked out to tell the user if they're correct or not?

How would I assign the list of operators so that the random numbers are worked out to tell the user if they're correct or not?
# Controlled Assessment - Basic Times Table Test
import random
score = 0
print ("Welcome to the times table test")
name = input("Please type your name: ")
print ("How to play")
print ("Step 1: When you see a question work out the answer and type it in the space.")
print ("Step 2: Once you have typed your answer press the enter key.")
print ("Step 3: The program will tell you if you're right or wrong.")
print ("Step 4: The next question will load and you can repeat from step 1.")
print ("When you have answered all 10 questions your final score will be printed.")
for q in range(10):
Number1 = random.randint(1,12)
Number2 = random.randint(1,12)
ListOfOperator = ['+','-','*']
Operator =random.choice(ListOfOperator)
print ('what is' ,Number1,Operator,Number2)
Answer= input ("Please Type Your Answer: ")
realanswer = (Number1,Operator,Number2)
if ListOfOperator:
ListOfOperator=['+'] = Number1+Number2
ListOfOperator=['-'] = Number1-Number2
ListOfOperator=['*'] = Number1*Number2
if Answer==realanswer:
print("Your answer is correct")
score = score + 1
print (score)
else:
print("Your answer is incorrect, the correct answer is.",realanswer,".")
print (score)
The code that needs to assign to the list of operators is...
if ListOfOperator:
ListOfOperator=['+'] = Number1+Number2
ListOfOperator=['-'] = Number1-Number2
ListOfOperator=['*'] = Number1*Number2
It should work out the answer to each question using the function I'm telling the program that if the operator from the operator list is * to work out Number1*Number2
The current output for telling them if the answer is correct or not prints
Your answer is incorrect, the correct answer is Number1*Number2.
when if the question is what is 10*3 it should be printing
Your answer is incorrect, the correct answer is 30.
Now that I have this code...
if Operator == '+':
realanswer = Number1+Number2
elif Operator == '-':
realanswer = Number1-Number2
elif Operator == '*':
realanswer = Number1*Number2
if Answer==realanswer:
print("Your answer is correct")
score = score + 1
print (score)
else:
print("Your answer is incorrect, the correct answer is.",realanswer,".")
print (score)
The program always prints that the question is incorrect even with the correct answer inputted, it will then print the correct answer, how would I make it so that It would tell them if it's correct too?
The operator module implements basic operations as functions. Define a dict that maps operator symbols such as "+" to the operator function then use that map to do the calculation.
import random
import operator
op_map = {'+':operator.add, '-':operator.sub, '*':operator.mul}
op_list = list(op_map.keys())
score = 0
print ("Welcome to the times table test")
name = input("Please type your name: ")
print ("How to play")
print ("Step 1: When you see a question work out the answer and type it in the space.")
print ("Step 2: Once you have typed your answer press the enter key.")
print ("Step 3: The program will tell you if you're right or wrong.")
print ("Step 4: The next question will load and you can repeat from step 1.")
print ("When you have answered all 10 questions your final score will be printed.")
for q in range(10):
Number1 = random.randint(1,12)
Number2 = random.randint(1,12)
Operator =random.choice(op_list)
print ('what is' ,Number1,Operator,Number2)
while True:
try:
Answer= int(input("Please Type Your Answer: "))
break
except ValueError:
print("Must be an integer... try again...")
realanswer = op_map[Operator](Number1, Number2)
if Answer==realanswer:
print("Your answer is correct")
score = score + 1
print (score)
else:
print("Your answer is incorrect, the correct answer is.",realanswer,".")
print (score)
To perform multiple check like this you can use if, elif statements:
if Operator == '+':
realanswer = Number1+Number2
elif Operator == '-':
realanswer = Number1-Number2
elif Operator == '*':
realanswer = Number1*Number2
For your reference: Python Docs
...
def realanswer(Num1, Op, Num2):
return {
'+': Num1 + Num2,
'-': Num1 - Num2,
'*': Num1 * Num2,
}[Op]
for q in range(2):
Number1 = random.randint(1,12)
Number2 = random.randint(1,12)
ListOfOperator = ['+','-','*']
Operator =random.choice(ListOfOperator)
print ('what is',Number1,Operator,Number2)
userInput = input("Please Type Your Answer: ")
Answer = 0
try:
Answer = int(userInput)
except ValueError:
print("Input not convertible to int!")
rAnswer = realanswer(Number1,Operator,Number2)
if Answer == rAnswer:
print("Correct!")
else:
print("Incorrect...")

Categories

Resources