How to make an input an answer to 3 different randoms - python-3.x

I am trying to make a simple quiz program. But how do I get the input to be the same as the answer on the code where the user answers the question?
import random
print("what is your name \n")
name=input()
print("hello",name,"you will be asked 10 math questions goodluck")
for i in range(10):
op=["+","-","*"]
num1=random.randint(0,10)
num2=random.randint(0,12)
operation=random.choice(op)
eval(str(num1)+operation+str(num2))
print(num1,operation,num2)
while True:
try:
user= int(input())
if user=answer:
print("correct")
except:
print("invaild")

Avoid using eval, fix indendtation, address comments and you will get something like this.
import random
import operator
operators = {'+': operator.add,
'-': operator.sub,
'*': operator.mul}
print("What is your name?")
name = input()
print("Hello {name} you will be asked 10 math questions, good luck.".format(name=name))
for _ in range(10):
num1 = random.randint(0, 10)
num2 = random.randint(0, 12)
operator = random.choice(operators.keys())
answer = operators[operator](num1, num2)
print("{n1} {op} {n2} = ?".format(n1=num1, op=operator, n2=num2))
try:
user_input = int(input())
if user_input == answer:
print("Correct")
else:
print("Invaild")
except ValueError:
print('Please enter a number!')

Related

Cycle "for" dosent start

class AnonymousSurvey():
def __init__(self, question):
self.question = question
self.responses = []
def show_question(self, question):
print(question)
def store_response(self, new_response):
self.responses.append(new_response)
def show_results(self):
for response in self.responses:
print("Survey results: ")
print('- ' + response)
question = "What language did you first learn to speak?"
my_survey = AnonymousSurvey(question)
my_survey.show_question(question)
print("Enter 'q' at any yime yo quit. \n")
while True:
response = input("Languge: ")
if response == 'q':
break
my_survey.store_response(response)
print("\nThank's everyone ")
my_survey.show_results()
My response in terminal:
What language did you first learn to speak?
Enter 'q' at any yime yo quit.
Languge: Spanish
Languge: English
Languge: q
Thank's everyone
Survey results:
- q
''''''''''''''''In results displayed only value 'q', but i want to displayed values "Spanish", "English". Value 'q' just finish the programm''''''''''''
Fix the placement of your my_survey.store_response(response) it should be in the while loop.
Then, the print("Survey results: ") should be above the for loop
class AnonymousSurvey():
def __init__(self, question):
self.question = question
self.responses = []
def show_question(self, question):
print(question)
def store_response(self, new_response):
self.responses.append(new_response)
def show_results(self):
print("Survey results: ")
for response in self.responses:
print('- ' + response)
question = "What language did you first learn to speak?"
my_survey = AnonymousSurvey(question)
my_survey.show_question(question)
print("Enter 'q' at any yime yo quit. \n")
while True:
response = input("Languge: ")
if response == 'q':
break
my_survey.store_response(response)
print("\nThank's everyone ")
my_survey.show_results()

I'm trying to write a calculator

This is what happens exactly in Mac Terminal:
Enter command to calculate:
+,-,* or/:
after typing the command it asks me for num1 and num2:
type first number: 5
type second number: 5
then it asks me:
do you want to continue?
I type 'yes', the program starts all over again. Now the problem is,
the second time I do a calculation, it doesnt ask me if I want to continue, but it jumps straight to:
Enter command to calculate:
+,-,* or/:
or sometimes:
type first number: 5
type second number: 5
Why does that happen? and how can I make the program ask me every time if I want to continue after each calculation?
loop = True
while loop:
def func():
usr = input('''Enter command to calculate:
+,-,* or/:
''')
if usr not in ("+,-,*,/"):
print("Error! command not allowed. Try again")
func()
num1 = float(input("type first number: "))
num2 = float(input("type second number: "))
if usr == "+":
print("{0} + {1} = {r:0.2f}".format(num1,num2,r=num1+num2))
elif usr == "-":
print("{0} - {1} = {r:0.2f}".format(num1,num2,r=num1-num2))
elif usr == "*":
print("{0} * {1} = {r:0.2f}".format(num1,num2,r=num1*num2))
elif usr == "/":
print("{0} / {1} = {r:0.2f}".format(num1,num2,r=num1/num2))
def func2():
x = input("do you want to continue? ")
if x == "yes":
func()
elif x == "no":
exit()
else:
print("That was not clear. Try again: ")
func2()
func()
func2()
Do you know what I should do in this case?
Depends on what you aim at and what exactly you want to make.
Here's the easiest way to make a powerful console calculator, but at the same time the most insecure:
import os
import sys
import math
def main(argv = sys.argv):
print("EVAL Calculator\nType 'exit' to exit\n")
while True:
exp = input("Type a mathematical expression and press ENTER: ")
if exp.lower() == "exit": return
else: print(eval(exp))
if __name__ == "__main__":
main()
Input: 2 + 2 * 2
Output: 6
If this doesn't work for you, you can just split a string or use regular expressions.
If you just want to get your code to work well, move while True to the end of the code and tabulate the code itself.
It is not recommended to use the above code for those projects that are intended to be used by other people.

I'm trying to make this program repetitive while using all the functions but cannot seem to get it working

So all I want to create is a loop for this program so that it will be able to be used more than once without re-running through the shell, I would like to also learn how to do this with any program involving functions
Everything
print('Welcome to the prime checker!')
num = int(input("Enter any number between 1 - 5000: "))
def is_prime(num):
if num > 1:
for i in range(2, num):
if (num % i) == 0:
print(num, "is not prime")
break
else:
print(num, "is prime")
else:
print(num, "is not a prime number")
is_prime(num)
def print_factors(num):
print("The factors of",num,"are:")
for i in range(1, num + 1):
if num % i == 0:
print(i)
print_factors(num)
def main():
choice = "y"
while choice.lower() == "y":
# get input
#num = int(input("Enter any number between 1 - 5000: "))
# see if the user wants to continue
choice = input("Repeat? (y/n): ")
print()
print("Bye!")
if __name__ == "__main__":
main()
print('Finished!')
I just want it to work when you press y and re-run the entire program like its first time
Structure your code. Create functions. Call functions. Respect indentations.
def check_primes():
print('Welcome to the prime checker!')
num = int(input("Enter any number between 1 - 5000: "))
def is_prime(num):
# do checking -your current code makes not much sense
# and does not do what the methodnames imply
# see f.e. https://stackoverflow.com/questions/1801391/what-is-the-best-algorithm-for-checking-if-a-number-is-prime
print("Did prime checking")
def main():
choice = "y"
while choice.lower() == "y":
check_primes()
# see if the user wants to continue
choice = input("Repeat? (y/n): ")
if __name__ == "__main__":
main()

Displaying answers from a list

In the last line of my code. I am displaying the question, users answer and the correct answer. However, when i add in the answer section at the end it gives me an index out of range error. I can't seem to workout the issue. Can anyone help?
Thank you
import random
counter=0
score = 0
incorrect = 0
name=input("What is your name?")
print("Hi",name,",welcome to your math quiz!")
questions = ["10x2","4-2","6+12","6x4","12-5","6+54","1x0","3-6","4+0","65-9"]
answers=["20","2","18","24",'7','60','0','-3','4','56']
idx_questions = list(enumerate(questions))
idx_answers = list(enumerate(answers))
random.shuffle(idx_questions)
counter=0
inputs = []
for idxq, question in idx_questions:
print()
print("Question",counter+1,":",question)
print()
ans = input("What is the answer? ")
counter=counter+1
inputs.append(ans)
for idxa, answer in idx_answers:
if idxq == idxa and ans == answer:
print("Correct")
score=score+1
print("Correct Answers=",score)
print("Incorrect Answers=",incorrect)
elif idxq == idxa and ans != answer:
print("Incorrect. The answer is", answer)
incorrect=incorrect+1
print("Correct Answers=",score)
print("Incorrect Answers=",incorrect)
print("End of quiz")
print(name,"your score is",score,"out of 10")
print(score*10,"/100")
print(score*10,"%")
counter=0
while counter<10:
for idxq, question in idx_questions:
print("Question",counter+1,":",question,": Your answer =", inputs[counter],"Correct Answer =",answer)
counter=counter+1
Try it like this and don't worry about indexing, you can add flavor text where you intended:
from random import shuffle
questions = ["10x2","4-2","6+12","6x4","12-5","6+54","1x0","3-6","4+0","65-9"]
answers = ["20","2","18","24",'7','60','0','-3','4','56']
combo = dict(zip(questions, answers))
shuffle(questions)
score = 0
listing = []
for q in questions:
print(q)
ans = input()
if ans == combo[q]:
score += 1
listing.append((q, ans, combo[q]))
print(score / 10)
for item in listing:
print('For question {} you answerd {} and correct answer is {}'.format(*item))

How to save user inputs in a list?-Python

I am making a mathematics game which asks a random question from a set list. I want to be able to save user inputs in a new list so i can display their answers at the end of the game.
Can anybody help me figure out how to do this?
import random
counter = 0
score = 0
incorrect = 0
name=input("What is your name?")
print("Hi",name,",welcome to your math quiz!")
questions = ["10*2","4-2","6+12","6*4","12-5","6+54","1*0","3-6","4+0","65-9"]
answers=["20","2","18","24",'7','60','0','-3','4','56']
idx_questions = list(enumerate(questions))
idx_answers = list(enumerate(answers))
random.shuffle(idx_questions)
for idxq, question in idx_questions:
print(question)
ans = input("What is the answer? ")
for idxa, answer in idx_answers:
if idxq == idxa and ans == answer:
print("Correct")
score=score+1
print("Correct Answers=",score)
print("Incorrect Answers=",incorrect)
elif idxq == idxa and ans != answer:
print("Incorrect", answers)
incorrect=incorrect+1
print("Correct Answers=",score)
print("Incorrect Answers=",incorrect)
print("End of quiz")
print(name,"your score is",score,"out of 10")
print(score*10,"%")
This should work:
inputs = []
for idxq, question in idx_questions:
print(question)
ans = input("What is the answer? ")
inputs.append(ans)
for idxa, answer in idx_answers:
# ...

Resources