Syntax for else statement in Python - python

I am very new to python and my else statement keeps on getting a syntax error.
I'll comment the else where the syntax is.
print("""
(A)ddition
(S)subtraction
(D)ivision
(M)multiplication
""")
operation = input("select an operation from above (initials) = ")
if(operation == "A","S","D","M"):
#this is where i am getting syntax
else:
print("select valid operation.")
number1 = int(input("first number = "))
number2 = int(input("second number = "))
if(operation == "A","M","D","S"):
if operation == "A":
print("this is the result = ", number1+number2)
elif operation == "S":
print("this is the final result", number1 - number2)
elif operation == "M":
print("this is the final result", number1 * number2)
elif operation == "D":
print("this is the final result", number1/number2, ".And this is the remainder = ",number1&number2)

you do not have to indent the else sentece.
if:
else:

You need to put something in the if statement above and the else statement should be at the same indentation.

As others have pointed out, you can't have a blank space after an if or an else.
Since you only want the else part, you have to negate the if criteria, so it becomes the if part.
So:
if(operation == "A","S","D","M"):
do_nothing = True
else:
print("select valid operation.")
becomes:
if operation not in ("A","S","D","M"):
print("select valid operation.")
(And yes, your == isn't going to work either on a list like that, you need in)

Related

This calculator program does not give an answer it just repeats. How do I fix it?

I wrote this simple calculator program to ask for two numbers and then perform a certain action on them like dividing the first by the second etc. I implemented it in a big while loop that is repeated if the user chooses to repeat it after a calculation. However, after the user enters the operation they want to perform the program does not give the answer but asks the user if they want to repeat. What did I do wrong?
import random, time
valid_operations = ("/", "*", "+", "-")
valid = 3
repeat = "y"
while repeat == "y":
number_1 = input('Enter first number \n')
if number_1.isdigit() == True:
num_1 = number_1
else:
print("that is not a valid integer")
exit()
number_2 = input('Enter second number \n')
if number_2.isdigit() == True:
num_2 = number_2
else:
print("that is not a valid integer")
exit()
operation = input("what operation would you like? \nvalid operations include:\n/ - divide\n* - multiply\n+ - add\n- - subtract\n")
while valid > 0:
if operation in valid_operations:
if operation == "/":
print(f"Answer = {int(num_1) / int(num_2)}")
valid -= 3
elif operation == "*":
print(f"Answer = {int(num_1) * int(num_2)}")
valid -= 3
elif operation == "+":
print(f"Answer = {int(num_1) + int(num_2)}")
valid -= 3
elif operation == "-":
print(f"Answer = {int(num_1) - int(num_2)}")
valid -= 3
else:
print(f"that is not a valid operation you have {valid} more attmepts to type a valid operation")
valid -= 1
time.sleep(2)
want_rep = input("would you like to do another calculation? y/n\n")
if want_rep == "y":
repeat = "y"
elif want_rep == "n":
repeat = "n"
else:
print("that is not a valid response, please choose either yes - y or no - n")
exit()
Problem lies in the valid variable.
You define it as 3 before the first iteration.
Then, inside the second while loop, it is reduced to 0 by
valid -= 3
And you never restore the starting value. So, the program comes back to the operation input, reads the loop condition:
while valid > 0:
And omits it, as valid equals 0.

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:

Beginner python: Rerunning a function automatically after getting the return value

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

How can I add an exit for users with int inputs

I need users to be able to type x to exit if they get a question wrong.
I've tried changing the input to a string and then if the answer isn't x then convert the string to an integer with int(user_ans) and even making another value and with ans_string == int(user_ans). Is there any way to add a break to the end if they type x?
if level == 1:
solution = number_one + number_two
print("What is", number_one, "plus", number_two)
user_ans = int(input())
if user_ans == solution:
print("Correct")
number_one = random.randrange(1,10)
number_two = random.randrange(1,10)
rounds = rounds + 1
else:
print("Try again")
I expect the program to still function but also be for the user to quit.
Just use a try block to see whether the input is a number and change what you do. Something like this:
is_int = false
user_ans = input()
try:
ans_int = int(user_ans)
is_int = true
except:
is_int = false
if is_int:
# Do what you need with the integer
if ans_int == 1:
solution = number_one + number_two
print("What is", number_one, "plus", number_two)
user_ans = int(input())
elif user_ans == solution:
print("Correct")
number_one = random.randrange(1,10)
number_two = random.randrange(1,10)
rounds = rounds + 1
elif user_ans == "x":
# Do what you need to do if it is an "x"
else:
print("Try again")
You can first get the user's input into a variable, like with inStr = input('Enter input: '). Then, you can check it to see if it's 'x'; if it is, you can use sys.exit() (or some other function), and if it's not, you can then cast it to a number and use it. inNum = int(inStr)
By checking the variable first and then casting it, you don't have to worry about what happens if your code tries to run int('x').
If you really want to cast your input to int right away, though, you can use try and except to catch a ValueError, which is what int() will throw if you give it a non-number input. This won't specifically check for 'x' - just for some invalid input.

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