Disclaimer: I am VERY inexperienced in python(if you couldn't tell by the question)
I made this basic code where you type in a given password. Once you type it in, you can either take a test or change the password. Each choice leads to different dialogue options, and so on(I used a lot of if: else and while: statements).
However, for my code, after getting the test question right, it'll print the "wrong" message WITH the "you got it right" message. Then, when signing in again, you have to type in the password TWICE before it registers your input. Anyone know how to fix this? I'm using Pycharm btw
Code:
k = 1
t = 1
s = 1
passcodes = ["stanley"]
while s == 1:
while k == 1:
ans = input("Enter your password: ")
if ans in passcodes:
while t <= 10:
print("Logging in.. [" + "*" * t + (10 - t) * " " + "]")
t = t + 1
if t > 10:
print("Logged in")
k = 2
else:
print("ACCESS DENIED")
while k == 2:
ans2 = input("Take test(1) or change password(2)? ")
if ans2 == "1":
ans3 = input("What is the square root of 4? ")
if ans3 == "2":
print("Correct. Thanks for participating!")
k = 1
t = 1
if ans3 == "-2":
print("Correct. Thanks for participating!")
k = 1
t = 1
else:
print("Wrong answer. Thanks for participating!")
k = 1
t = 1
if ans2 == "2":
change = input("New password: ")
passcodes.clear()
passcodes.append(change)
print("New password " + change + " saved. Please sign back in.")
k = 1
t = 1
ans = input("Enter your password: ")
else:
print("Signing out..")
Error message:
hi there you have a small mistake in the sequence of the if statement
when the ans3 is 2 the program rechecks if ans3 is -2 and it finds it false so it runs the code in the else statement to fix this you simply need the program to run else just in case that the two if statements are false
this is achieved by using elif statement in the line " if ans3 == "-2":"
it should be "elif ans3 == "-2":"
In this code here you have a small mistake in last if statement. In last if statement you use 'ans' statement its not needed bcz already you use this for printing a new answer so try my code and run it.its give proper output what ever you need.
k = 1
t = 1
s = 1
passcodes = ["stanley"]
while s == 1:
while k == 1:
ans = input("Enter your password: ")
if ans in passcodes:
while t <= 10:
print("Logging in.. [" + "*" * t + (10 - t) * " " + "]")
t = t + 1
if t > 10:
print("Logged in")
k = 2
else:
print("ACCESS DENIED")
while k == 2:
ans2 = input("Take test(1) or change password(2)? ")
if ans2 == "1":
ans3 = input("What is the square root of 4? ")
if ans3 == "2":
print("Correct. Thanks for participating!")
k = 1
t = 1
if ans3 == "-2":
print("Correct. Thanks for participating!")
k = 1
t = 1
else:
print("Wrong answer. Thanks for participating!")
k = 1
t = 1
if ans2 == "2":
change = input("New password: ")
passcodes.clear()
passcodes.append(change)
print(" New password " + change + " saved. Please sign back in.")
k = 1
t = 1
else:
print("Signing out..")
Related
So I've built a simple calculator in Python where the user inputs two numbers and an operator and the answer is given. They also have the option to run the calculator again. I want to number the answers so each answer reads "Answer 1 equals x", "Answer 2 equals x", etc. depending on how many times the calculator is run. Everytime I try to format the counter to count iterations, it won't work and is stuck just labeling them "Answer 1" over and over. Any help would be greatly appreciated. I'm super new to Python.
answer = "y"
while ((answer == "Y") or (answer == "y") or (answer == "Yes") or (answer == "yes")):
numones = input ("Give me a number: ")
numtwos = input ("Give me another number: ")
numone = float(numones)
numtwo = float(numtwos)
operation = input ("Give me an operation (+,-,*,/): ")
counter = 0
for y in answer:
counter += 1
if (operation == "+"):
calc = numone + numtwo
print ("Answer " + str(counter) + " is " + str(calc))
elif (operation == "-"):
calc = numone - numtwo
print ("Answer " + str(counter) + " is " + str(calc))
elif (operation == "*"):
calc = numone * numtwo
print ("Answer " + str(counter) + " is " + str(calc))
elif (operation == "/"):
calc = numone / numtwo
if (numtwo != 0):
print ("Answer " + str(counter) + " is " + str(calc))
else:
print ("You can't divide by zero.")
else:
print ("Operator not recognized.")
answer = input ("Do you want to keep going? ")
if ((answer == "Y") or (answer == "y") or (answer == "Yes") or (answer == "yes")):
print ()
else:
print ("Goodbye.")
break
Remove assigning counter = 0 in your while loop. And move this declaration above your while loop.
also lines:
for y in answer:
counter += 1
are really confusing and sure are wrong, because if you got 'yes' as an answer you would get +3 increase. Just increment(counter += 1) counter without any for-loop.
i am a super beginner to python.
Below is a simple math quiz. The problem is that selecting option 2 (subtraction) then 1 (addition) shuts down the program instead of asking addition problem.
It works from 1 to 2 but it does not work from 2 to 1. Do you guys know what i am missing here? Thanks in advance.
while user_input == 1:
num1 = (random.randrange(0,100))
num2 = (random.randrange(0,100))
answer = num1 + num2
problem = str(num1) + " + " + str(num2)
print("Enter your answer")
print(problem, end="")
result = int(input(" = "))
if result == answer:
print('Correct')
else:
print('Incorrect')
user_input = int(input('Enter your choice: '))
subtraction for choice 2
while user_input == 2:
num1 = (random.randrange(0,100))
num2 = (random.randrange(0,100))
answer = num1 - num2
problem = str(num1) + " - " + str(num2)
print("Enter your answer")
print(problem, end="")
result = int(input(" = "))
if result == answer:
print('Correct')
else:
print('Incorrect')
user_input = int(input('Enter your choice: '))
Exit for choice 3 - the User is done with the quiz
else:
print('See you again')
For good practice and readability, I would implement something like:
choice = input()
while choice != -1:
choice = input()
if choice == 1:
#do something
else if choice == 2:
#do something else
else if choice == -1:
print("bye")
Your code is wrong. You must do something like this:
choice = input()
while choice == "1" or choice == "2":
if choice == "1":
#do add
else:
#do subtraction
choice = input()
print("bye")
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
I'm currently learning Python and am creating a maths quiz.
I have created a function that loops, first creating a random maths sum, asks for the answer and then compares the input to the actual answer; if a question is wrong the player loses a point - vice versa. At the end a score is calculated, this is what I'm trying to return at the end of the function and print in the main.py file where I receive a NameError 'score' is not defined.
I have racked my head on trying to figure this out. Any help / suggestions would be greatly appreciated!
#generateQuestion.py
`def generate(lives, maxNum):
import random
score= 0
questionNumber = 1
while questionNumber <=10:
try:
ops = ['+', '-', '*', '/']
num1 = random.randint(0,(maxNum))
num2 = random.randint(0,10)
operation = random.choice(ops)
question = (str(num1) + operation + str(num2))
print ('Question', questionNumber)
print (question)
maths = eval(str(num1) + operation + str(num2))
answer=float(input("What is the answer? "))
except ValueError:
print ('Please enter a number.')
continue
if answer == maths:
print ('Correct')
score = score + 1
questionNumber = questionNumber + 1
print ('Score:', score)
print ('Lives:', lives)
print('\n')
continue
elif lives == 1:
print ('You died!')
print('\n')
break
else:
print ('Wrong answer. The answer was actually', maths)
lives = lives - 1
questionNumber = questionNumber + 1
print ('Score:', score)
print ('Lives:', lives)
print('\n')
continue
if questionNumber == 0:
print ('All done!')
return score
`
My main file
#main.py
import random
from generateQuestion import generate
#Welcome message and name input.
print ('Welcome, yes! This is maths!')
name = input("What is your name: ")
print("Hello there",name,"!" )
print('\n')
#difficulty prompt
while True:
#if input is not 1, 2 or 3, re-prompts.
try:
difficulty = int (input(' Enter difficulty (1. Easy, 2. Medium, 3. Hard): '))
except ValueError:
print ('Please enter a number between 1 to 3.')
continue
if difficulty < 4:
break
else:
print ('Between 1-3 please.')
#if correct number is inputted (1, 2 or 3).
if difficulty == 1:
print ('You chose Easy')
lives = int(3)
maxNum = int(10)
if difficulty == 2:
print ('You chose Medium')
lives = int(2)
maxNum = int(25)
if difficulty == 3:
print ('You chose Hard')
lives = int(1)
maxNum = int(50)
print ('You have a life count of', lives)
print('\n')
#generateQuestion
print ('Please answer: ')
generate(lives, maxNum)
print (score)
#not printing^^
'
I have tried a different method just using the function files (without the main) and have narrowed it down to the problem being the returning of the score variable, this code is:
def generate(lives, maxNum):
import random
questionNumber = 1
score= 0
lives= 0
maxNum= 10
#evalualates question to find answer (maths = answer)
while questionNumber <=10:
try:
ops = ['+', '-', '*', '/']
num1 = random.randint(0,(maxNum))
num2 = random.randint(0,10)
operation = random.choice(ops)
question = (str(num1) + operation + str(num2))
print ('Question', questionNumber)
print (question)
maths = eval(str(num1) + operation + str(num2))
answer=float(input("What is the answer? "))
except ValueError:
print ('Please enter a number.')
continue
if answer == maths:
print ('Correct')
score = score + 1
questionNumber = questionNumber + 1
print ('Score:', score)
print ('Lives:', lives)
print('\n')
continue
elif lives == 1:
print ('You died!')
print('\n')
break
else:
print ('Wrong answer. The answer was actually', maths)
lives = lives - 1
questionNumber = questionNumber + 1
print ('Score:', score)
print ('Lives:', lives)
print('\n')
continue
if questionNumber == 0:
return score
def scoreCount():
generate(score)
print (score)
scoreCount()
I think the problem is with these last lines in main:
print ('Please answer: ')
generate(lives, maxNum)
print ('score')
You are not receiving the returned value. It should be changed to:
print ('Please answer: ')
score = generate(lives, maxNum) #not generate(lives, maxNum)
print (score) # not print('score')
This will work.
The way it works is not:
def a():
score = 3
return score
def b():
a()
print(score)
(And print('score') will simply print the word 'score'.)
It works like this:
def a():
score = 3
return score
def b():
print(a())
I need help with this program that I'm writing. It asks random mathematical questions. It chooses between +, - and x. Here's my code
import random
def questions():
name=input("What is your name: ")
print("Hello there",name,"!")
choice = random.choice("+-x")
finish = False
questionnumber = 0
correctquestions = 0
while finish == False:
if questionnumber < 10 | questionnumber >= 0:
number1 = random.randrange(1,10)
number2 = random.randrange(1,10)
print((number1),(choice),(number2))
answer=int(input("What is the answer?"))
questionnumber = questionnumber + 1
if choice==("+"):
realanswer = number1+number2
if answer==realanswer:
print("That's the correct answer")
correctquestions = correctquestions + 1
else:
print("Wrong answer, the answer was",realanswer,"!")
if choice==("x"):
realanswer = number1*number2
if answer==realanswer:
print("That's the correct answer")
correctquestions = correctquestions + 1
else:
print("Wrong answer, the answer was",realanswer,"!")
elif choice==("-"):
realanswer = number1-number2
if answer==realanswer:
print("That's the correct answer")
correctquestions = correctquestions + 1
else:
print("Wrong answer, the answer was",realanswer,"!")
else:
finish = True
else:
print("Good job",name,"! You have finished the quiz")
print("You scored " + str(correctquestions) + "/10 questions.")
questions()
The output:
What is your name: s
Hello there s !
6 - 9
What is the answer?-3
That's the correct answer
9 - 8
What is the answer?1
That's the correct answer
9 - 7
What is the answer?2
That's the correct answer
8 - 3
What is the answer?4
Wrong answer, the answer was 5 !
5 - 6
What is the answer?1
Wrong answer, the answer was -1 !
8 - 7
What is the answer?1
That's the correct answer
3 - 5
What is the answer?2
Wrong answer, the answer was -2 !
4 - 5
What is the answer?1
Wrong answer, the answer was -1 !
7 - 2
What is the answer?5
That's the correct answer
7 - 1
What is the answer?6
That's the correct answer
Good job s ! You have finished the quiz
You scored 6/10 questions.
Now the program is running fine but it asks the questions with the same operator (+, -, x) every time I start the program a different operator questions happen but I want to run it so it actually asks different adding, subtracting, multiplication questions inside the program so all the questions that it asks it will be different questions like x, + and - every different question.
It should help if you move the choice part inside the loop:
while not finish: # better than finish == False
choice = random.choice("+-x")
# etc
import random
correct = 0
name = input("Please enter your name: ")
for count in range(10):
num1 = ranom.randint(1, 100)
num2 = radom.randint(1, 100)
symbol = rndom.choice(["+", "-", "*"])
print("Please solve:\n", num1, symbol, num2)
user = int(input(""))
if symbol == "+":
answer = num1 + num2
elif symbol == "-":
answer = num1 - num2
elif symbol == "*":
answer = num1 * num2
if user == answer:
print("Wong u wetard")
correct = correct + 1
else:
print("correct")
print(name, ", You Got", correct, "Out Of 10")
After while finish == false put this !
choice = random.choice("+-x")
I have attempted the same problem that you face, and after looking at your code I made the changes detailed below. the code works and it is (relatively) neat and concise.
def name_enter():
global name
name = ""
while name == "" or len(name) > 25 or not re.match(r'^[A-Za-z0-9-]*$', name):
name = input("Please enter your name: ")
enter_class()
def enter_class():
global class_choice
class_choice = None
while class_choice not in ["1","3","2"]:
class_choice = input("Please enter you class (1, 2, 3): ")
print("\nClass entered was " + class_choice)
mathsquestion()
def mathsquestion():
global qa, score
qa, score = 0, 0
for qa in range(0,10):
qa = qa + 1
print("The question you are currently on is: ", qa)
n1, n2, userans = random.randrange(12), random.randrange(12), ""
opu = random.choice(["-","+","x"])
if opu == "+":
while userans == "" or not re.match(r'^[0-9,-]*$', userans):
userans = input("Please solve this: %d" % (n1) + " + %d" % (n2) + " = ")
prod = n1 + n2
elif opu == "-":
while userans == "" or not re.match(r'^[0-9,-]*$', userans):
userans = input("Please solve this: %d" % (n1) + " - %d" % (n2) + " = ")
prod = n1 - n2
else:
while userans == "" or not re.match(r'^[0-9,-]*$', userans):
userans = input("Please solve this: %d" % (n1) + " x %d" % (n2) + " = ")
prod = n1 * n2
userans = int(userans)
prod = int(prod)
if prod == userans:
score = score + 1
print("Well done, you have got the question correct. Your score is now: %d" % (score))
else:
print("Unfortunatly that is incorrect. The answer you entered was %d" % (userans) + " and the answer is actually %d" % (prod))
print("Your final score is: %d" % (score))
name_enter()
This is a very different code but should do the same thing. It's also much shorter and neater.
import random
correct = 0
name = input("Please enter your name: ")
for count in range(10):
num1 = random.randint(1, 100)
num2 = random.randint(1, 100)
symbol = random.choice(["+", "-", "*"])
print("Please solve:\n", num1, symbol, num2)
user = int(input(""))
if symbol == "+":
answer = num1 + num2
elif symbol == "-":
answer = num1 - num2
elif symbol == "*":
answer = num1 * num2
if user == answer:
print("Correct!")
correct = correct + 1
else:
print("Incorrect")
print(name, ", You Got", correct, "Out Of 10")