Hi i wrote some code for a maths program and wanted some help to validate user input. I want the program to, when the user ignores a question and simply presses the enter key for the next question, to show them the exact same question again and notify them saying every question must be attempted. Heres the code i have so far
import time
import random
msg=0
questionsAsked=0
score=0
op = ["-","*","+"]
username= input("What is your name? ")
print("Okay "+username+ " lets begin the test. Good luck!")
praise= ["Well done!","Great job!", "Spot on!", "Perfect!"]
wrong = ["Unlucky!", "Not quite", "Incorrect"]
def actual(num1,num2,operation):
actual=eval(str(num1) + operation + (str(num2)))
return actual
def useranswer(num1,num2,operation):
useranswer=int(input(str(num1)+operation+str(num2)+"= "))
return useranswer
while questionsAsked <10:
num1 = random.randint(0,12)
num2 = random.randint(0,12)
operation = random.choice(op)
praiseMsg= random.choice(praise)
wrongMsg= random.choice(wrong)
if useranswer(num1,num2,operation) != actual(num1,num2,operation):
print(wrongMsg)
else:
print(praiseMsg)
score= score+1
questionsAsked=questionsAsked+1
else:
if score>5:
msg= str("Well done "+username+"! You scored over 50%")
else:
msg=str("Better luck next time " + username)
print("You scored " +str(score)+ " out of 10. \n" +msg )
time.sleep(3)
username = raw_input("What is your name? ")
while not username:
username = raw_input("Not understood. What is your name?")
You could wrap this in a function:
def insist_upon_answer(prompt):
answer = raw_input(prompt)
while not answer:
answer = raw_input("All questions must be answered. {}".format(prompt)
return answer
and call it:
name = insist_upon_answer("What is your name?")
Like triphook's answer, for Python 3:
username = input("Input: ")
while username=="":
username = input("Input (again): ")
Related
I'm a student who is doing my Python assignment. Thing is, our lecturer is really strict on us not using python built ins and also refuses to check our code before submission and I'm having the hardest time trying to get my code to work properly during registration.
My problem currently is that I want the code to prompt an error from the program itself when the user tries to register with a taken username. However, it keeps running different errors regardless of how I try to fix it. Can anyone please point me in the right direction or tell me what's wrong with my code? I'd be really grateful for any help.
def grant():
print("Helllooooo")
def begin():
while True:
print("Welcome to the Freshco Groceries App!")
option = input("Are you a new or returning user?\n"
"Enter 1 if you would like to LOGIN\n"
"Enter 2 if you would like to register\n"
"Enter 3 if you would like to exit the program\n")
if option=="1":
access(option)
break
elif option=="2":
access(option)
break
elif option=="3":
print("Thank you! Have a good day.")
exit()
else:
continue
def access(option):
if(option=="1"):
name = input("Please enter your username:\n")
password = input("Please enter your password:\n")
login(name,password)
else:
print("First step: Please choose a username and a unique password.")
name = input("Please enter your username:\n")
password = input("Please enter your password:\n")
register(name,password)
newuser()
def login(name,password):
success=False
file = open("user_details.txt","r")
for line in file:
a,b = line.split(",")
if (name in a) and (password in b):
success=True
break
file.close()
if(success):
print("You have successfully logged in! Happy shopping!")
grant()
else:
print("Wrong username or password entered.")
def register(name,password):
exist = False
while True:
file = open("user_details.txt", "r")
for line in file:
line = line.rstrip()
if (name == line):
exist = True
break
else:
pass
file.close()
if (exist):
print("Username has been taken. Please try again with a new one.")
break
else:
file = open("user_details.txt","a")
file.write("\n" + name + "," + password)
print("You have successfully registered! Welcome to the Freshco Family!")
grant()
break
def newuser():
print("Before you start using the app, please fill in the details below.")
alldata = []
while True:
newdata = []
nname = input("Please enter your full name:\n")
newdata.append(nname)
while True:
ngender = input("Are you female or male?\n"
"1: female\n"
"2: male\n")
if ngender=="1":
fingender="female"
newdata.append(fingender)
break
elif ngender=="2":
fingender="male"
newdata.append(fingender)
break
else:
print("INVALID INPUT")
continue
naddress = input("Please enter your address:\n")
newdata.append(naddress)
nemail = input("Please enter your email address:\n")
newdata.append(nemail)
ncontact = input("Please enter your contact number:\n")
newdata.append(ncontact)
ndob = input("Please enter your dob in this format: <DD.MM.YY>\n")
newdata.append(ndob)
alldata.append(newdata)
print(newdata)
break
print("Thank you for entering your information, you will be redirected now!")
grant()
begin()
thank you so much! T-T
I'm trying to figure out how to clear an "if" condition and how to fix the result = print(x) part of my code. I'm trying to create a little search code based on the variable data, but I can't figure a few things out:
import time
def start():
data = ["Lucas_Miguel", "João_Batista", "Rafael_Gomes", "Bruna_Santos", "Lucas_Denilson"]
print("1" + " - Check Name")
print("2" + " - Register a New Name")
option = input("Choose an option: ")
if option == "1":
def other():
name = input("Type the first name: ")
for x in data:
if name in x:
result = print(x)
while True:
print("Yes " "or " "No")
confirm = input("Is the name you want in the options?: ")
if confirm == "Yes":
break
if confirm == "No":
print("Yes", " or", " No")
try_again = input("Do you want to write again?: ")
if try_again == "Yes":
return other()
other()
else:
print("Option not available")
time.sleep(1)
return start()
start()
The first problem is in the result = print(x) part. It works, but when the answer is more than one name, only the first one appear and I don't know how to fix it.
The second problem is in the "confirm = input" part. Basically, if the person answered with "No", when they go back, the answer will still be saved and the input will run twice, the first time with the saved answer and the second with the new answer. So I want to be able to clear that before the person answer it again.
I want to apologize already if the code is ugly or weird, but I started a few days ago, so I'm still learning the basics. Also thanks in advance for the help.
There is quite a bit here to unpack and like the comment on the question suggests you should aim to look at how to ask a more concise question.
I have some suggestions to improve your code:
Split the other into its own function
Try to use more accurate variable names
As much as you can - avoid having multiple for loops happening at the same time
Have a look at list comprehension it would help a lot in this case
Think about whether a variable really belongs in a function or not like data
What you're asking for is not immediately clear but this code should do what you want - and implements the improvements as suggested above
import time
data = ["Lucas_Miguel", "João_Batista", "Rafael_Gomes", "Bruna_Santos", "Lucas_Denilson"]
def other():
name_input = input("Type the first name: ")
matches = [name for name in data if name_input in name]
if len(matches) == 0:
print ("No matches")
for name in matches:
print(name)
while True:
print("Yes " "or " "No")
confirm = input("Is the name you want in the options?: ")
if confirm == "Yes":
break
if confirm == "No":
print("Yes", " or", " No")
try_again = input("Do you want to write again?: ")
if try_again == "Yes":
return other()
else:
return
def start():
print("1" + " - Check Name")
print("2" + " - Register a New Name")
option = input("Choose an option: ")
if option == "1":
other()
else:
print("Option not available")
time.sleep(1)
return start()
start()
The first problem will be solved when you remove 8 spaces before while True:.
The second problem will be solved when you add return (without arguments) one line below return other() at the indentation level of if try_again == "Yes":
Everybody can see that you are just learning Python. You don't have to apologize if you think, your code is "ugly or weird". We all started with such small exercises.
This question already has answers here:
Asking the user for input until they give a valid response
(22 answers)
Closed 3 years ago.
After I type in any username and password (doesn't matter whether it's correct or not), it keeps printing another part of the code.
The login part works fine but it doesn't show the correct output afterwards. It continuously shows:
"Incorrect login details entered
Have you made an account?
Yes or No"
This has stumped both my teacher and I. I have looked at different websites with examples of login/registration systems. I have also tried re-arranging the code differently.
This is the code:
username = input("Please enter your username: ")
password = input("Please enter your password: ")
file = open("Usernames.txt","r")
found = False
for line in file:
user = line.split(",")
if user[0] == username and user[1] == password:
found = True
print("Username: " + user[0])
print("~~~~~")
print("Welcome to the game, " + user[0])
else:
found == False
print("Incorrect login details entered")
print("Have you made an account?")
ans = input("Yes or No ")
while ans not in ("Yes", "No"):
if ans == "Yes":
print ("Please sign in again")
username = input("Please enter your correct username: ")
password = input("Please enter your correct password: ")
elif ans == "No":
print("Would you like to make an account? ")
else:
ans = input("Please enter Yes or No ")
The expected result when the username and password is correct:
Username: Smartic
~~~~~
Welcome to the game, Smartic
The expected result when the username and password is incorrect:
Incorrect login details entered
Have you made an account?
Yes or No
The expected result when the user enters Yes:
Please sign in again
Please enter your correct username:
Please enter your correct password:
The expected result when the user enters No:
Would you like to make an account?
The expected result when the user enters something other than Yes or No:
Please enter Yes or No
No matter what username you enter, it won't satisfy every username in the file. Every time it doesn't, your error text will be printed. Reformat your code as is described in this question.
There is a new line at the end of each line in the file. You can remove newline by using strip() function.
if user[0] == username and user[1].strip() == password:
found = True
print("Username: " + user[0])
print("~~~~~")
print("Welcome to the game, " + user[0])
Change your:
while ans not in ("Yes", "No"):
In:
while True:
Besides I can recommend to make a function.
Also as John Gordon mentioned use breaks, so your script will look like:
username = input("Please enter your username: ")
password = input("Please enter your password: ")
user = {0:'e',1:'w'}
found = False
if user[0] == username and user[1] == password:
found = True
print("Username: " + user[0])
print("~~~~~")
print("Welcome to the game, " + user[0])
else:
found == False
print("Incorrect login details entered")
print("Have you made an account?")
ans = input("Yes or No ")
while True:
if ans == "Yes":
print ("Please sign in again")
username = input("Please enter your correct username: ")
password = input("Please enter your correct password: ")
break
elif ans == "No":
print("Would you like to make an account? ")
break
else:
ans = input("Please enter Yes or No ")
break
A function in my code repeats twice. In the chooseName() function, it asks the question, and once you answer, it repeats the question and then moves on with the rest of the code. Why does it do this?
# -*- coding: utf-8 -*-
from __future__ import print_function
import random
import time
def displayIntro():
print("Hello, there! Glad to meet you!")
print("Welcome to the world of Pokémon!")
print("My name is Maple.")
print("People affectionately refer to me as the Pokémon Professor.")
print("This world is inhabited far and wide by creatures called Pokémon.")
print("For some people, Pokémon are pets.")
print("Others use them for battling.")
print("As for myself, I study Pokémon as a profession.")
print("But first, tell me a little about yourself.")
def chooseGender():
gender = ""
while gender != "boy" and gender != "girl":
gender = raw_input("Now tell me. Are you a boy? Or are you a girl? ")
return gender
def chooseName():
name = ""
name = raw_input("Let's begin with your name. What is it? ")
return name
def nameConfirmation():
name = chooseName()
answer = ""
while answer != "yes" and answer != "no":
answer = raw_input("Right... So your name is " + str(name) + "? (yes or no) ")
return answer
if answer == "yes":
print("I have a grandson.")
print("He's been your rival since you both were babies.")
print("...Erm, what was his name now?")
# raw_input for their name
print("...Er, was it") #raw_input for name
# Let user pick yes or no
# If yes, move on
# If no, ask name again
print("That's right! I remember now! His name is") #raw_input for name
print("your name!") # raw_input for name
print("Your very own Pokémon legend is about to unfold!")
print("A world of dreams and adventures with Pokémon awaits! Let's go!")
if answer == "no":
chooseName()
displayIntro()
chooseGender()
chooseName()
nameConfirmation()
I apologize for not posting the rest of the code sooner.
This is the output.
Let's begin with your name. What is it? Raven
Let's begin with your name. What is it? Raven
Remove the chooseName( ) call below chooseGender( ) as it has already been called in nameConfirmation( ) definition. It worked for me.
Some modification in your code , Here is updated code:
First edit :
You are calling chooseName() two times ,
Second edit :
You are returning before main logic of your program.
Here
def nameConfirmation():
name = chooseName()
answer = ""
while answer != "yes" and answer != "no":
answer = raw_input("Right... So your name is " + str(name) + "? (yes or no) ")
return answer
You should keep in mind that function is not going to execute anything after you return from it so your code from if answer == "yes": is not going to execute even if user type yes or no
So return it at the last of the program or if you want to return at the same place then use print there instead of 'return'.
# -*- coding: utf-8 -*-
from __future__ import print_function
import random
import time
def displayIntro():
print("Hello, there! Glad to meet you!")
print("Welcome to the world of Pokémon!")
print("My name is Maple.")
print("People affectionately refer to me as the Pokémon Professor.")
print("This world is inhabited far and wide by creatures called Pokémon.")
print("For some people, Pokémon are pets.")
print("Others use them for battling.")
print("As for myself, I study Pokémon as a profession.")
print("But first, tell me a little about yourself.")
def chooseGender():
gender = ""
while gender != "boy" and gender != "girl":
gender = input("Now tell me. Are you a boy? Or are you a girl? ")
return gender
def chooseName():
name = ""
name = input("Let's begin with your name. What is it? ")
return name
def nameConfirmation():
name = chooseName()
answer = ""
while answer != "yes" and answer != "no":
answer = input("Right... So your name is " + str(name) + "? (yes or no) ")
if answer == "yes":
print("I have a grandson.")
print("He's been your rival since you both were babies.")
print("...Erm, what was his name now?")
# raw_input for their name
print("...Er, was it") #raw_input for name
# Let user pick yes or no
# If yes, move on
# If no, ask name again
print("That's right! I remember now! His name is") #raw_input for name
print("your name!") # raw_input for name
print("Your very own Pokémon legend is about to unfold!")
print("A world of dreams and adventures with Pokémon awaits! Let's go!")
if answer == "no":
chooseName()
return answer
displayIntro()
chooseGender()
nameConfirmation()
As chooseName() is getting called twice first below call of chooseGender() and second inside nameConfirmation() so that's the reason it is getting executed twice. As a fixed you can comment or remove chooseName() which is below chooseGender() as shown.
displayIntro()
chooseGender()
# chooseName()
nameConfirmation()
So updated code will be as follows:
# -*- coding: utf-8 -*-
from __future__ import print_function
import random
import time
def displayIntro():
print("Hello, there! Glad to meet you!")
print("Welcome to the world of Pokémon!")
print("My name is Maple.")
print("People affectionately refer to me as the Pokémon Professor.")
print("This world is inhabited far and wide by creatures called Pokémon.")
print("For some people, Pokémon are pets.")
print("Others use them for battling.")
print("As for myself, I study Pokémon as a profession.")
print("But first, tell me a little about yourself.")
def chooseGender():
gender = ""
while gender != "boy" and gender != "girl":
gender = raw_input("Now tell me. Are you a boy? Or are you a girl? ")
return gender
def chooseName():
name = ""
name = raw_input("Let's begin with your name. What is it? ")
return name
def nameConfirmation():
name = chooseName()
answer = ""
while answer != "yes" and answer != "no":
answer = raw_input("Right... So your name is " + str(name) + "? (yes or no) ")
return answer
if answer == "yes":
print("I have a grandson.")
print("He's been your rival since you both were babies.")
print("...Erm, what was his name now?")
# raw_input for their name
print("...Er, was it") #raw_input for name
# Let user pick yes or no
# If yes, move on
# If no, ask name again
print("That's right! I remember now! His name is") #raw_input for name
print("your name!") # raw_input for name
print("Your very own Pokémon legend is about to unfold!")
print("A world of dreams and adventures with Pokémon awaits! Let's go!")
if answer == "no":
chooseName()
displayIntro()
chooseGender()
# chooseName()
nameConfirmation()
You call the function choseName() and then right after you call nameConfiguration() wich starts by calling choseName(), that's why it is called twice. You can simply remove the choseName() before nameConfiguration().
I am trying to ask the user to pick a quiz, read the relevant questions from a txt file, ask for user answers, validate and check they are correct then add up to scores. I am completely self taught so have picked this code up from various sites but as I have adapted it it no longer works - what have I done wrong? I know its probably something really obvious so please be gentle with me!
getting the message global name the_file not defined
import time
def welcome():
print ("Welcome to Mrs Askew's GCSE ICT Quiz")
print()
def get_name():
firstname = input("What is your first name?:")
secondname = input("What is your second name?:")
print ("Good luck", firstname,", lets begin")
return firstname
return secondname
def displaymenu():
print("-------------------------------------------------------")
print("Menu")
print()
print("1. Input and Output Devices")
print("2. Collaborative working")
print("3. quiz3")
print("4. quiz4")
print("5. view scores")
print("6. Exit")
print()
print("-------------------------------------------------------")
def getchoice():
while True:
print("enter number 1 to 6")
quizchoice = input()
print("You have chosen number "+quizchoice)
print()
if quizchoice >='1' and quizchoice <='6':
print("that is a valid entry")
break
else:
print("invalid entry")
return quizchoice
def main():
welcome()
get_name()
while True:
displaymenu()
quizchoice = getchoice()
print ("please chooses from the options above: ")
if quizchoice == ("1"):
the_file = open("questions.txt", "r")
startquiz()
elif quizchoice == ("2"):
collaborativeworking()
startquiz()
else:
break
def collborativeworking():
the_file = open("Collaborative working.txt", "r")
return the_file
def next_line(the_file):
line = the_file.readline()
line = line.replace("/", "\n")
return line
def next_block(the_file):
category = next_line(the_file)
question = next_line(the_file)
answers = []
for i in range(4):
answers.append(next_line(the_file))
correct = next_line(the_file)
if correct:
correct=correct[0]
explanation = next_line(the_file)
time.sleep(2)
return category, question, answers, correct, explanation
def startquiz():
title = next_line(the_file)
score = 0
category, question, answers, correct, explanation = next_block(the_file)
while category:
# ask a question
print(category)
print(question)
for i in range(4):
print("\t", i + 1, "-", answers[i])
# get answer and validate
while True:
answer =(input("What's your answer?: "))
if answer >= '1' and answer <='4':
break
else:
print ("the number needs to be between 1 and 4, try again ")
# check answer
answer=str(answer)
if answer == correct:
print("\nRight!", end=" ")
return score
main()
Couple of things I noticed. You haven't provided the error you are getting (/ problems you are having) so these are the things I noticed in my quick look:
First: enter code hereimport time should be import time
Second: All function definitions (def func():) should have the code in them indented e.g.
def get_name():
firstname = input("What is your first name: ")
Third: print () should be print()
Fourth: Multiline strings do exist
"""
Look at me mum!
WOWWWW!
"""
Fifth: It looks like a lot of this has been copied from elsewhere, if you are learning, I suggest you don't copy, but try to understand what things are doing and then hand write it
Sixth: There are a lot of bugs. I think I got most of them, but you should really change something in the way you're working. It really does fail in so many places
Seventh: Here is your code with some improvements:
import time
def welcome():
print("Welcome to Mrs Askew's GCSE ICT Quiz\n")
def get_name():
firstname = input("What is your first name: ")
secondname = input("What is your second name: ")
print("Good luck" + firstname + ", lets begin") # or print("Good luck {}, lets begin".format(firstname))
return firstname, secondname
def displaymenu():
print("""-------------------------------------------------------
Menu
1. Input and Output Devices
2. Collaborative working
3. quiz3
4. quiz4
5. view scores
6. Exit
-------------------------------------------------------""")
def getchoice():
while True:
quizchoice = input("Enter number 1 to 6: ")
print("You have chosen number " + quizchoice "\n")
if quizchoice >= "1" and quizchoice <= "6":
print("That is a valid entry")
break
else:
print("invalid entry")
return quizchoice
def main():
welcome()
get_name()
while True:
displaymenu()
quizchoice = getchoice()
print("Please chooses from the options above: ")
if quizchoice == ("1"):
the_file = open("questions.txt", "r")
startquiz()
elif quizchoice == ("2"):
collaborativeworking()
startquiz()
else:
break
def collborativeworking():
the_file = open("Collaborative working.txt", "r")
return the_file
def next_line(the_file):
line = the_file.readline()
line = line.replace("/", "\n")
return line
def next_block(the_file):
category = next_line(the_file)
question = next_line(the_file)
answers = []
for i in range(4):
answers.append(next_line(the_file))
correct = next_line(the_file)
if correct:
correct = correct[0]
explanation = next_line(the_file)
time.sleep(2)
return category, question, answers, correct, explanation
def startquiz():
title = next_line(the_file)
score = 0
category, question, answers, correct, explanation = next_block(the_file)
while category:
# ask a question
print(category)
print(question)
for i in range(4):
print("\t", i + 1, "-", answers[i])
# get answer and validate
while True:
answer =(input("What's your answer?: "))
if answer >= '1' and answer <='4':
break
else:
print ("the number needs to be between 1 and 4, try again ")
# check answer
answer=str(answer)
if answer == correct:
print("\nRight!", end=" ")
return score
main()
Eighth: Please take time to make an answer before you post. People here want to answer questions, and try to answer them with the most effort they can put in, so we expect questioners to put in the same effort, to spend time on their questions (basically pretend you are asking the person you respect most in your life this question, then behave appropriately e.g. Dear your royal highness, beloved master and benefactor, who I so dearly love, please, oh please, do me the great kindness to answer my humble question that I have taken 2 days to write properly so you wouldn't be offended and have to waste as little time as possible with such a small thing as me...)
Ninth: There are much better ways to do what you want.
I suggest you:
Try perfecting parts of your program, before writing 108 lines
Try not having so many functions
Try to decrease the length of your code, make it not so verbose, but succinct
Use consistent formatting (e.g. only one type of quotes; only, spaces or tabs)
Also read up on some basic python (learn python the hard way is good)
I also highly recommend PEP (Python Enhancement Proposals) 8 and the other PEP's
Look at test-driven development in python