MY maths quiz was working but now. It says after 'if ops =='+':' that the colon is an invalid syntax. Please can you help me fix it. If I remove the colon below it the answer variable would come up as an invalid syntax error.
import random
question=0
userInput = int()
LastName = str()
answer = str()
FirstName = str()
Form = str()
def Quiz():
score=0
LastName = input ("Please enter your surname: ").title()
FirstName = input ("Please enter your first name: ").title()
Form = input ("Please enter your form: ").title()
for i in range(10):
print ("What is:")
num1= random.randint(1,12)
num2= random.randint(1,12)
ops = ['+', '-', '*']
operation = random.choice(ops)
Q = int(input(str(num1)+operation+str(num2)
if ops =='+':
answer==num1+num2
if Q == answer:
print ("correct")
score= score+1
else:
print('You Fail')
elif ops =='-':
answer==num1-num2
if Q == answer:
print ("correct")
score= score+1
else:
print("you fail")
else:
answer==num1*num2
if Q == answer:
print ("correct")
score= score+1
else:
print("you fail")
You are missing two parenthesis on this line:
Q = int(input(str(num1)+operation+str(num2)))
,This will lead into a syntax error in the next line.
ALSO:
Remove the double = in lines like this:
answer=num1+num2 #it was == before
Declare "score" before starting the game:
score = 0
Replace "ops" with "operation":
if operation == '+':
Use if operation=='+'. ops is a list, you want to match char (operation).
Related
I am a beginner in Python so kindly do not use complex or advanced code.
contact = {}
def display_contact():
for name, number in sorted((k,v) for k, v in contact.items()):
print(f'Name: {name}, Number: {number}')
#def display_contact():
# print("Name\t\tContact Number")
# for key in contact:
# print("{}\t\t{}".format(key,contact.get(key)))
while True:
choice = int(input(" 1. Add new contact \n 2. Search contact \n 3. Display contact\n 4. Edit contact \n 5. Delete contact \n 6. Print \n 7. Exit \n Enter "))
#I have already tried
if choice == 1:
while True:
try:
name = str(input("Enter the contact name "))
if name != str:
except ValueError:
continue
else:
break
while True:
try:
phone = int(input("Enter number "))
except ValueError:
print("Sorry you can only enter a phone number")
continue
else:
break
contact[name] = phone
elif choice == 2:
search_name = input("Enter contact name ")
if search_name in contact:
print(search_name, "'s contact number is ", contact[search_name])
else:
print("Name is not found in contact book")
elif choice == 3:
if not contact:
print("Empty Phonebook")
else:
display_contact()
elif choice == 4:
edit_contact = input("Enter the contact to be edited ")
if edit_contact in contact:
phone = input("Enter number")
contact[edit_contact]=phone
print("Contact Updated")
display_contact()
else:
print("Name is not found in contact book")
elif choice == 5:
del_contact = input("Enter the contact to be deleted ")
if del_contact in contact:
confirm = input("Do you want to delete this contact Yes or No? ")
if confirm == 'Yes' or confirm == 'yes':
contact.pop(del_contact)
display_contact
else:
print("Name is not found in phone book")
elif choice == 6:
sort_contact = input("Enter yes to print your contact")
if sort_contact in contact:
confirm = input("Do you want to print your contact Yes or No? ")
if confirm == 'Yes' or confirm == 'yes':
strs = [display_contact]
print(sorted(strs))
else:
print("Phone book is printed.")
else:
break
I tried but keep getting errors and I can't fiugre out how to make it only take string or letter as input and not numbers.
if choice == 1:
while True:
try:
name = str(input("Enter the contact name "))
if name != str:
except ValueError:
continue
else:
break
it is not working my code still accepts the ans in integer and string.
I am a beginner so I might have made a lot of mistakes. Your patience would be appreciated.
You can use a regex with re.fullmatch:
import re
while True:
name = input("Enter the contact name ")
if re.fullmatch(r'[a-zA-Z]+', name):
break
Or use the case-insensitive flag: re.fullmatch(r'[a-z]+', name, flags=re.I):
As you noted that you are a beginner, I'm adding this piece of code
as a "custom-made" validation, just so you can check how you would do something like this by your own .
Note: #mozway gave a MUCH BETTER solution, that is super clean, and I recommend it over this one.
def valid_input(input: str):
# Check if any char is a number
for char in input:
if char.isdigit():
print('Numbers are not allowed!')
return False
return True
while True:
name = input("Enter data:")
if valid_input(name):
break
I found this answer from another website:
extracted_letters = " ".join(re.findall("[a-zA-Z]+", numlettersstring))
First, import re to use the re function.
Then let's say that numlettersstring is the string you want only the letters from.
This piece of code will extract the letters from numlettersstring and output it in the extracted_letters variable.
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...")
When there is a wrong answer, I would like a preset message for all the operators to be displayed.
Maybe something like this:
while True:
try:
user_ans = int(input())
except ValueError:
print ("That is not a valid answer")
continue
else:
break
but in a for loop.
My aim is to ask numerical questions then save to a file.
First, I need to ask the user what maths class they are in, then ask 10 randomly generated questions.
#Imports
import random
from time import sleep
#List & Definitions#
operators = ("-","+","X")
score = 0
QA = 0
#Intro#
print ("Hello and Welcome")
print ("What is your name?")
name = input ()
print ("Do you want to Play (Yes/No)?")
choice = input()
if choice =="Yes":
print ("Excellent")
if choice == "No":
print ("Okey, bye...")
end()
quit()
print ("Please input your class")
cn = input ()
print ("Let's start the quiz!")
sleep(2)
#Asking Questions
for QA in range (0, 10):
numb1 = random.randint(1,10)
numb2 = random.randint(1,10)
randOp = random.choice(operators)
#Addition
if randOp == "+" :
print (str(numb1) + "+" + str(numb2))
answer = numb1 + numb2
print ("Please input your answer")
UserAns = int(input ())
if UserAns == answer :
print ("well done that was correct")
score = score + 1
if UserAns != answer:
print("that's wrong")
else:
print ("Oops! That was no valid number. Try again...")
#Subtracting
if randOp == "-" :
if numb2 > numb1 :
print (str(numb2) + "-" + str(numb1))
answer = numb2 - numb1
print ("Please input your answer")
UserAns = int(input ())
if UserAns == answer :
print ("woah again Correct")
if UserAns != answer:
print("that's wrong")
score = score + 1
elif numb1 > numb2 :
print(str(numb1) + "-" + str(numb2))
answer = numb1 - numb2
print ("Please input your answer")
UserAns = int(input ())
if UserAns == answer :
print ("Correct :) ")
score = score + 1
if UserAns != answer:
print("that's wrong")
#Multiplication
if randOp == "*" :
print (str(numb1) + "X" + str(numb2))
ans = numb1 * numb2
sleep(1)
print ("Please input your answer")
UserAns = int(input ())
if ans == UserAns :
print ("Correct")
score = score + 1
if UserAns != answer:
print("that's wrong")
#Displaying Score
QA = QA + 1
if QA == 10 :
print ("Your score is " + str(score) + " out of ten")
#Saving & Writing to File
savePath = "Results\Class " + str(cn) + "\\" + name.lower() +".txt"
file = open(savePath, "a")
file.close()
file = open(savePath, "r")
if file.read() == "":
file.close()
file = open(savePath, "a")
file.write(name + "\n\n")
file.close()
file.close()
file = open(savePath, "a")
file.write(str(score))
file.write("\n")
file.close()
Just make better input functions..
def input_with_choices(prompt, choices):
while True:
choice = input('{} (choices are: {}) '.format(prompt, ','.join(choices)))
if choice in choices:
return choice
else:
print("That's not a valid choice.")
and
def input_int(prompt):
while True:
try:
return int(input(prompt))
except ValueError:
print("That's not an integer.")
etc.
Then you can use those to validate your input in the for loop.
Your question isn't very understandable, however, what I think you are looking for is this:
accepted = False
while not accepted:
try:
UserAns = int(input())
accepted = True
except:
pass
def multiply(): #starts sub program when 'multiply()' is called
num1 = random.randint(1,12) #randomly generates a number between 1 and 12
num2 = random.randint(1,12)
while loop == True: #creates loop, and uses previously defined 'loop'
ans = int(input("What is the answer to " + str(num1) + " x " + str(num2) + " ? ")) #asks question and requires a user input
correct = (ans == num1 * num2)
if correct:
print("You are correct! ")
break #if the answer is correct, it prints 'You are correct!' and breaks to avoid the loop
else:
print("Wrong, please try again. ")
loop == False #if the answer is wrong, it loops back to when 'loop' was last 'True'
I am wondering if there is a way for me to include a line of code that allows me to display "That is not an option!" when a symbol other than a number is entered into the 5th line in the code.
Use an exception to catch unexpected inputs.
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
import random
def multiply():
# Randomly generates a number between 1 and 12
num1 = random.randint(1,12)
num2 = random.randint(1,12)
while True:
i = input("What is the answer to {} x {} ".format(
str(num1), str(num2)))
try:
ans = int(i)
except ValueError:
print('That is not an option!')
continue
if ans == num1 * num2:
print("You are correct!")
break
else:
print("Wrong, please try again.")
if __name__ == "__main__":
multiply()
When you convert to int there is the chance that they will enter a non-integer value so the conversion will fail, so you can use a try/except
def multiply(): #starts sub program when 'multiply()' is called
num1 = random.randint(1,12) #randomly generates a number between 1 and 12
num2 = random.randint(1,12)
while loop == True: #creates loop, and uses previously defined 'loop'
try:
ans = int(input("What is the answer to " + str(num1) + " x " + str(num2) + " ? ")) #asks question and requires a user input
correct = (ans == num1 * num2)
if correct:
print("You are correct! ")
break #if the answer is correct, it prints 'You are correct!' and breaks to avoid the loop
else:
print("Wrong, please try again. ")
loop == False
except ValueError:
print("That is not an option")
Note that your previous code is now nested in a try block. If the int() fails because they entered a bad input, it will throw a ValueError that you can catch and notify them.
As a side note, another way to format your question to them would be
'What is the answer to {} x {}?'.format(num1, num2)
This is a nice way to generate a string with injected variable values.
This question already has answers here:
Asking the user for input until they give a valid response
(22 answers)
Closed 8 years ago.
I'm quite new to coding. I've managed to produce this code which is a little test for children. It works fine I just need to prevent kids from entering letters or other characters when math questions are asked. Something like "please only enter numbers" should come up. I've tried a variety of functions like ValueError but with no luck. Any help will be appreciated!
import time
import random
import math
import operator as op
def test():
number1 = random.randint(1, 10)
number2 = random.randint(1, num1)
ops = {
'+': op.add,
'-': op.sub,
'*': op.mul,
}
keys = list(ops.keys())
rand_key = random.choice(keys)
operation = ops[rand_key]
correctResult = operation(number1, number2)
print ("What is {} {} {}?".format(number1, rand_key, number2))
userAnswer= int(input("Your answer: "))
if userAnswer != correctResult:
print ("Incorrect. The right answer is {}".format(correctResult))
return False
else:
print("Correct!")
return True
username=input("What is your name?")
print ("Hi {}! Wellcome to the Arithmetic quiz...".format(username))
while True:
try:
# try to convert the user's input to an integer
usersClass = int(input("Which class are you in? (1,2 or 3)"))
except ValueError:
# oh no!, the user didn't give us something that could be converted
# to an int!
print("Please enter a number!")
else:
# Ok, we have an integer... is it 1, 2, or 3?
if usersClass not in {1,2,3}:
print("Please enter a number in {1,2,3}!")
else:
# the input was 1,2, or 3! break out of the infinite while...
break
input("Press Enter to Start...")
start = time.time()
correctAnswers = 0
numQuestions = 10
for i in range(numQuestions):
if test():
correctAnswers +=1
print("{}: You got {}/{} {} correct.".format(username, correctAnswers, numQuestions,
'question' if (correctAnswers==1) else 'questions'))
end = time.time()
etime = end - start
timeTaken = round(etime)
print ("You completed the quiz in {} seconds.".format(timeTaken))
if usersClass == 1:
with open("class1.txt","a+") as f:
f.write(" {}:Scored {} in {} seconds.".format(username,correctAnswers,timeTaken))
elif usersClass == 2:
with open("class2.txt","a+") as f:
f.write(" {}:Scored {} in {} seconds.".format(username,correctAnswers,timeTaken))
elif usersClass == 3:
with open("class3.txt","a+") as f:
f.write(" {}:Scored {} in {} seconds.".format(username,correctAnswers,timeTaken))
else:
print("Sorry, we can not save your data as the class you entered is not valid.")
def get_int(prompt):
while True:
try:
return int(input(prompt))
except ValueError:
print("Please enter an integer value!")
Look, in your code:
import operator as op
# DEFINE THE `get_int` FUNCTION HERE
# (in global scope so other functions can call it)
def test():
then use it below:
userAnswer = get_int("Your answer: ") # call the function
# No ValueErrors!