Creating a quiz and summoning questions and answers from extrernal file - python

I have a login system in which students take quizzes at different difficulties. what i need to do is load the question and answers for the quiz from an external .txt file. can someone help me quickly please as i need to have this done very soon. can the coding be simple aswell and available to use on python 3.4 as i am not very good with python

This is my attempt at the code:
def easyMathsQuiz():
score=0
emquiz=open("easymathsquiz.txt","r")
questionNumber=0
for questionNumber,line in enumerate(emquiz):
print (line)
ans=input("Your answer is: ")
if ans == "1":
score=score+1
questionNumber=questionNumber+1
elif ans=="2":
questionNumber=questionNumber+1
elif ans !="1" or ans !="2":
print("You have entered an invalid character")
easyMathsQuiz()
break
for questionNumber,line in enumerate(emquiz):
print(line)
if ans == "2":
score=score+1
questionNumber=questionNumber+1
elif ans=="1":
questionNumber=questionNumber+1
elif ans !="1" or ans !="2":
print("You have entered an invalid character")
easyMathsQuiz()
easyMathsQuiz()
print (score)
This is whats inside the .txt file:
What is 2+2-1? 1)3 2)4
What is 10+10? 1)30 2)20
What is 3*9? 1)27 2)36
What is 100/5? 1)25 2)20
What is 30-17? 1)23 2)13
My problem is:
Each line number basically represnts the question number. the first line i got to print but im just not sure how to make the next line print and i need the system to allow the user to input and of course it needs to check if their answer is correct. And i also have just absolutely no idea how to write code for it to go to the start of the question when they enter an invalid character rather than make the whole thing restart
Btw i cant seem to get the code to indent properly on here everything is indented correctly on my program

Related

For some reason, despite the condition of this while loop being False, the loop is not terminating [closed]

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 months ago.
Improve this question
What I am trying to do is make my code re-executable by placing it all within a while loop and asking the user if they wish to continue. But, for whatever reason, despite start not being 'y', the code continues on. I tried messing around with it but nothing seems to work. Its a really simple problem but I can't put my hand on what's going on. Here is the problematic code:
start = "y"
while start == "y":
holder = input("Create a file? (y/n): ")
while holder != "y" and holder != "n":
print("ERROR: Only enter 'y' or 'n'.")
print()
holder = input("Create a file? (y/n): ")
start = holder
BTW, yes, I know I could use break but I just really want to know what is wrong with this.
While you don't enter "y", or "n", the code stays in the while loop. The code is perfect however. You might also be giving input typos.
This is a simpler design:
while True:
doit = input("Create a file? (y/n): ")
if doit in 'Nn':
break
if doit not in 'Yy':
continue
# Go create the file.

If statement isn't printing [closed]

Closed. This question is not reproducible or was caused by typos. It is not currently accepting answers.
This question was caused by a typo or a problem that can no longer be reproduced. While similar questions may be on-topic here, this one was resolved in a way less likely to help future readers.
Closed 1 year ago.
Improve this question
I'm a beginner in python and coding in general.
I was messing around with if statements and whenever I ran this code, it would never print what I asked it to, it would only print what was in the else statement.
I'm putting my code down below and if someone could help me understand the issue that'd be great, thanks!
canyou = input("Can you make a good meal on your own? ")
canyou1 = input("Can you wash your clothes well? ")
canyou2 = input("Can you clean the house properly? ")
if canyou.upper == "no" and canyou1.upper == "no" and canyou2.upper == "no":
print("You need your mama")
else:
print("You don't need your mama")
You're comparing the uppercase string to a lowercase example. To fix this you can do the following
if canyou.lower() == "no" and canyou1.lower() == "no" and canyou2.lower() == "no":
print("You need your mama")
else:
print("You don't need your mama")
You also need to call the method by adding parenthesis after upper/lower, as shown in my example.
You need to call the method of each string like this:
canyou = input("Can you make a good meal on your own? ")
canyou1 = input("Can you wash your clothes well? ")
canyou2 = input("Can you clean the house properly? ")
if canyou.lower() == "no" and canyou1.lower() == "no" and canyou2.lower() == "no":
print("You need your mama")
else:
print("You don't need your mama")
Also you need to call .lower()

Why is my 'while' loop not working in Python? [duplicate]

This question already has answers here:
Asking the user for input until they give a valid response
(22 answers)
Closed 1 year ago.
I'm a beginner in Python. I've tried using the 'while' loop. I need the code to allow the user to reattempt the question after their previously incorrect guess. After the first correct try, it says what I want it to say but after the first wrong try, the correct answer is given as incorrect. How do I solve this and what am I doing wrong?
key = input("Choose a place and see if your guess is correct! ")
if key == ("bed"):
print("Congratulations! You are correct and will now progress to room 2.")
while key != ("bed"):
input("Unfortunately your guess is incorrect. Try again. ") ```
First of all you need to indent the 2nd line. Second of all the loop can't work because you say that the loop should stop when the key is "bed" but you do not change the key. The 4th line should be: key = input("Unfortunately your guess is incorrect. Try again. ")
Of course you need to put your if statement in the while loop.
while(True):
if key == ("bed"):
print("Congratulations! You are correct and will now progress to room 2.")
False
else:
key = input("Unfortunately your guess is incorrect. Try againg.")
maybe try it like "this"?

Python indenting issue (Number Guess Game) [duplicate]

This question already has answers here:
"inconsistent use of tabs and spaces in indentation" [duplicate]
(29 answers)
Closed 4 years ago.
When I try to run my code it says:
if again == "y":
^
TabError: inconsistent use of tabs and spaces in indentation
My code is:
import random
def game():
wrong_guesses = [1,2,3,4,5]
num = random.randint(0,100)
guess = input("Guess a number bewtween 1 and 100, you have five tries ")
def wrong_guess():
wrong_guesses.remove()
print("That is not the number, You have {} guesses left".format(len(wrong_guesses)))
def right_guess():
if guess == num:
print("Congratulations! You guessed the number. You had {} guesses left".format(len(wrong_guesses)))
play_again()
def game_over():
if len(wrong_guesses) == 0:
break
play_again()
def play_again():
again = input("Would you like to play again? [y/n}")
if again == "y":
game()
elif again == "n":
break
game()
This question has already been answered numerous times, e.g.: "inconsistent use of tabs and spaces in indentation"
So first, please seek out the answer before posting a new question here on StackOverflow.
However, to provide my version of the answer:
The TabError tells you exactly why your code will not run. There is an inconsistency in your use of tabs vs spaces (e.g. you are using both tabs and spaces). The solution is to choose tabs or spaces and switch to it exclusively.
While Python does not require you to use one specifically, the PEP8 style guide advises spaces. You should be able to configure your editor to convert tabs to spaces. PEP8: https://www.python.org/dev/peps/pep-0008/
Also, while syntactically-correct, you should probably change your elif clause in the play_again function to an else (or at least add an else clause after the elif); the reason I say this is you are currently not handling any input other than "y" and "n". Not to mention your code is calling game() recursively as opposed to running in an infinite loop, which is going to cause the program to crash at a certain point; for that I would advise refactoring the game to a while True: loop and then the break would break out of the gameloop--this is traditionally how gameloops work at a high-level.
The error says it all.
TabError: inconsistent use of tabs and spaces in indentation
This means you must have intertwined spaces and tabs in your code. Try removing all the white space and using only spaces (4 to replace a tab).

Python - Can't find syntax error in if statement [closed]

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 6 years ago.
Improve this question
Its been a while since I've written code, so I'm trying to get back into it again, but I'm having trouble with some of my code.
I wanted to write a simple program that takes a user's input and checks to see if it is all letters with no spaces, and has a length less than 12. I keep getting an "Invalid syntax" error on line 17 whenever I run the code, pointing to the colon after the if statement that checks if the username is just letters and less than 12 characters. I know that means there's an error on the line before that, but where?
#import the os module
import os
#Declare Message
print "Welcome to Userspace - Your One-Stop Destination to Greatness!" + "\n" + "Please enter your username below." \
+ "\n" + "\n" + "Username must be at least 12 characters long, with no spaces or symbols." + "\n" + "\n"
#uinput stands for user's input
uinput = raw_input("Enter a Username: ")
#check_valid checks to see if arguement meets requirements
def check_valid(usrnameinput):
if (usrnameinput != usrnameinput.isalpha()) or (len(usrnameinput) >= 12):
os.system('cls')
print "Invalid Username"
return False
else:
os.system('cls')
print "Welcome, %s!" % (usrnameinput)
return True
#Asks for username and checks if its valid
print uinput
check_valid(uinput)
#Checks input to check_valid is correct, and if it is not, then ask for new username input and checks it again
while check_valid(uinput):
return True
break
else:
print uinput
check_valid(uinput)
print "We hope you enjoy your stay here at Userspace!"
UPDATE - I played around with the code a little bit more, and the only thing I changed was the while conditional to an if:
print uinput
check_valid(uinput)
#Checks input to check_valid is correct, and if it is not, then ask for new username input and checks it again
if check_valid(uinput):
print uinput
check_valid(uinput)
print "We hope you enjoy your stay here at Userspace!"
I ran this code, but got this error instead:
File "Refresher In Python.py", line 39
return True
SyntaxError: 'return' outside function
Sorry for being such a noob. Also just joined Stack Overflow today.
I believe this is what you want. I suggest splitting it into two functions, your check_valid() and a general main() function.
def check_valid(usrnameinput):
if (not usrnameinput.isalpha()) or (len(usrnameinput) >= 12):
print("Invalid name")
return False
else:
print("Welcome!")
return True
def main():
uinput = raw_input("Enter a Username: ")
while not check_valid(uinput): #Repeatedly asks user for name.
uinput = raw_input("Enter a Username: ")
main()

Categories