I would like a little bit of help because Im confused and also really stuck on this. I would like to point out that I am a bigger on python so please take it easy.
I am trying to create a simple quiz with a login/register dictionary system. I am also trying to keep all my "Registered Users" in a .txt file but i can't do that unfortunately so if anyone can help I would be delighted!
The problem is, when a users logs in or -registers i would like the quiz bit to run, but instead the login/register runs in a loop unless i take away the while statement, but if I do take it away the login/register script does not run at all. So what i need is.....
When my program runs, I want it to run the login/register script but
then when the user has registered or logged on I want it to start the
quiz.
Here is my code,
#Login & Register
users = {}
status = ""
def displayMenu():
status = input("Are you a registered user? y/n? Say quit to exit: ")
if status == "y":
oldUser()
elif status == "n":
newUser()
def newUser():
createLogin = input("Create login name: ")
if createLogin in users: # check if login name exists
print ("\nLogin name already exist!\n")
else:
createPassw = input("Create password: ")
users[createLogin] = createPassw # add login and password
print("\nUser created!\n")
def oldUser():
login = input("Enter login name: ")
passw = input("Enter password: ")
# check if user exists and login matches password
if login in users and users[login] == passw:
print ("\nLogin successful!\n")
else:
print ("\nUser doesn't exist or wrong password!\n")
while status != "q":
displayMenu()
# Defining Score variables
x = 0
score = x
# Question One
print("When did WW2 finish?")
answer1 = input("a)2001\nb)1945\nc)1877\nd)1940\n:")
if answer1.lower() == "b" or answer1.lower() == "2":
print("Correct")
x = x + 1
else:
print("Incorrect, the second Worl War ended in 1945")
# Question Two
print("Who was responsilbe of most deaths in World War 1 & 2 ")
answer2 = input("a)Donald Trump\nb)Adolf Hitler\nc)Tom Cruisend\nd)There were no WAR\n:")
if answer2.lower() == "b" or answer1.lower() == "Adolf Hitler":
print("Correct")
x = x + 1
else:
print("Incorrect, It was Adolf Hitler who took around 12 to 14 million lives")
# Question Three
print("True or False... Hitler was a painter")
answer3 = input(":")
if answer3.lower() == "true" or answer3.lower() == "t":
print("Correct")
x = x + 1
else:
print("Incorrect")
# Question Four
print("What happened in Chernobyl")
answer4 = input("a)Nuclear Plant exploaded\nb)Water Flood\nc)Alien Envasion\nd)War\n:")
if answer4.lower() == "a" or answer4 == "1967":
print("Correct")
x = x + 1
else:
print("Incorrect, the nuclear plant exploaded")
# Question Five
print("True or False... Everybody knew the reactor will explode")
answer5 = input(":")
if answer5.lower() == "false" or answer5.lower() == "f":
print("Correct")
x = x + 1
else:
print("Incorrect, no one knew it will explode")
#Total Score
score = float(x / 5) * 100
print(x,"out of 5, that is",score, "%")
At the end of the while loop add a break statement:
while status != "q":
displayMenu()
break
your status does not exist beyond the scope of the function DisplayMenu()
What you can do is use status as a return value for this function, adding
return status
in the end, and then using a condition on this :
dm=""
while dm != "q":
dm=displayMenu()
Related
I am trying to make a shopping list, however every time I delete an item it leaves a big gap and looks very awkward, please can someone help, I am still very new to it all and I have only been learning a month or two so a simple answer would be very much appreciated:
def subtract(user):
x = 0
while x == False:
answer = input("What would you like to subtract?")
if answer in user:
user = user.replace(answer,"")
y = 0
print("your list is:" + user)
add_or_subtract(user)
x == True
break
else:
print ("sorry, I do not recognise this, please try again.")
def add(user):
x = 0
while x == False:
answer = input(str("what would you like to add?".lower()))
if answer in user:
print ("sorry, this is already in the list")
else:
user = user + "\n" + answer
print ("Your list is: " + user)
answer = input("are you finished adding?".lower())
if answer in ("yes", "yea", "ye"):
answer1 = input("do you want to subtract or finish?")
if answer1 in ("subtract"):
subtract(user)
x == True
break
elif answer1 in ("finish"):
print (user)
x == True
break
else:
print("Sorry I do not recognise this")
def add_or_subtract(user):
x = 0
while x == False:
answer = input ("do you want to add or subtract or finish?".lower())
if answer in ("add","addition"):
add(user)
x == True
break
elif answer in ("subtract","takeaway"):
subtract (user)
x == True
break
elif answer in ("complete", "finish"):
print ("your final list is: " + user)
x == True
break
else:
print ("sorry i do not recognise this")
def initial(user):
x = 0
while x == False:
user = input("please type out your first item:".lower())
content = input(str("your first item is "+ user + " are you content with that?".lower()))
if content in "no":
user = ""
continue
elif content in "yes":
add_or_subtract(user)
x == True
break
shopping = ""
initial(shopping)
Also is there a better way of doing this, I feel like there is, could I use a list to record all the items and is there a way I can store the existing list into a database and then re-use that when updating?
The reason why you have a gap is because you are forgetting the \n character (newline character), so when replacing put '\n' before answer:
def subtract(user):
x = 0
while x == False:
answer = input("What would you like to subtract?")
if answer in user:
user = user.replace('\n'+answer,"") # where it is edited
y = 0
print("your list is:" + user)
add_or_subtract(user)
x == True
break
else:
print ("sorry, I do not recognise this, please try again.")
to learn Python I'm working on a small terminal upgrade game. The user enters a number that is added to a random integer to get a score (called "Films Produced" in game). The problem I can't seem to fix is every time the player goes to the menu and back then back to entering more numbers the previous number is deleted instead of added on to the new one.
Here is the code:
print("TERMINAL FILM by Dominick")
print("---------------------")
# SCORE
def filmClicker():
global score
user_input = int(input(">> Enter a number: "))
score = user_input
if user_input > 5 or user_input < 0 or user_input == 0:
print(">> Not a valid number.")
filmClicker()
elif score > 0:
score = score + random.randint(1, 50)
print("")
print(">> You produced:", score, "films", "<<")
go_back_or_menu = input(">> Press ENTER to go again. Or type TAB to go back to the menu. ")
if go_back_or_menu == "":
filmClicker()
elif go_back_or_menu == "TAB" or "Tab" or "tab":
game()
def game():
print(">>>>>>>>>>>>> Menu >>>>>>>>>>>>>")
print(">> Type A to go make films. ")
print(">> Type B to see your current balance. ")
print(">> Type C to see the current box office. ")
print(">> Type D for your stats. ")
press_button_menu = input("")
if press_button_menu == "A":
filmClicker()
elif press_button_menu == "B":
print("Current Balance =", score)
press_enter()
game()
else:
filmClicker()
game()
So I want the player to be able to insert a number, the number gets added to another number by the computer, and then a final number is spit out. I got all that working. But it doesn't save when you do that multiple times. Which I don't want, I want it to stack each time you do it.
Sorry if I poorly explained it, I can answer more about it if needed. Any help is appreciated.
UPDATE:
I removed the score = "input" variable and declared it out of any function. But it's still not saving. Here is a better answer as to what I want it to do:
In the picture below I start at the game menu. I then decide to make films, I do it 5 times. But then when I go back to the menu and check my balance, the balance equals the last time I made films and not the TOTAL films. What I want it to do is add up all of the films. So in this case 48 + 49 + 9 + 38 + 25 instead of having just the last set (which is 25 in this case), to get a total balance which can be displayed by going to the menu and typing "B."
Here is the current code:
import random
score = 0
# SCORE
def filmClicker():
global score
user_input = int(input(">> Enter a number: "))
if user_input > 5 or user_input < 0 or user_input == 0:
print(">> Not a valid number.")
filmClicker()
elif score > 0:
score = score + random.randint(1, 50)
print("")
print(">> You produced:", score, "films", "<<")
go_back_or_menu = input(">> Press ENTER to go again. Or type TAB to go back to the menu. ")
print(go_back_or_menu)
if go_back_or_menu == "":
filmClicker()
elif go_back_or_menu == "TAB" or "Tab" or "tab":
game_menu()
# GAME MENU
def game_menu():
print(">>>>>>>>>>>>> Menu >>>>>>>>>>>>>")
print(">> Type A to go make films. ")
print(">> Type B to see your current balance. ")
print(">> Type C to see the current box office. ")
print(">> Type D for your stats. ")
press_button_menu = input("")
if press_button_menu == "A":
filmClicker()
elif press_button_menu == "B":
print("Current Balance =", score)
press_enter()
game_menu()
else:
filmClicker()
game_menu()
SECOND UPDATE:
Updated Code:
import random
score = 0
# PRINT BLANK LINE
def press_enter():
press_enter = print(input(""))
# SCORE
def filmClicker():
global score
user_input = int(input(">> Enter a number: "))
score += user_input
produced = random.randint(1, 50)
if user_input > 5 or user_input < 0 or user_input == 0:
print(">> Not a valid number.")
filmClicker()
elif score > 0:
score += produced
print("")
print(">> You produced:", produced, "films", "<<")
go_back_or_menu = input(">> Press ENTER to go again. Or type TAB to go back to the menu. ")
print(go_back_or_menu)
if go_back_or_menu == "":
filmClicker()
elif go_back_or_menu == "TAB" or "Tab" or "tab":
game_menu()
# GAME MENU
def game_menu():
print(">>>>>>>>>>>>> Menu >>>>>>>>>>>>>")
print(">> Type A to go make films. ")
print(">> Type B to see your current balance. ")
print(">> Type C to see the current box office. ")
print(">> Type D for your stats. ")
press_button_menu = input("")
if press_button_menu == "A":
filmClicker()
elif press_button_menu == "B":
print("Current Balance =", score)
press_enter()
game_menu()
else:
filmClicker()
game_menu()
In the picture below it's printing how much the player is producing from that turn but I also am testing the score (which is what the 6 and 49 stand for). It's scaling weird like that, where it adds a certain amount after every turn. Any way to fix this?
I think you are looking for the += operator.
Keep the score = 0 at the top of the file to initialize the variable, then use score += user_input to keep a running tally. This is the same as writing score = score + user_input.
In your filmClicker function, you should remove the following line:
score = user_input
By assigning to it, you've essentially erased its previous value which is why it doesn't accumulate between rounds.
For saving data, You can Use Files in python
For Saving:
f=open("data_game.txt","w")
f.write(<your score>)
f.close()
For Reading:
f=open("data_game.txt","r")
score=f.read()
print(score)
f.close()
my program is for an assignment to make a password vault, so the user makes an account and enter the password vault, he then adds apps and passwords and views it, The problem is that it also has to print summaries but when the user has no entered app and passwords it dosnt tell them they dont have any.
code for the summary>>
def app_summary():
while True:
if len(vault_apps) < 1:
print('''there is no summary of your acount as,
you currently have 0 apps and passwords stored on your account''')
else: print('''You have {} app and its information stored'''.format(len(vault_apps)))
print('''Your longest password is charecters''', max(len(a) for a in vault_apps))
print('''Your shortest password is charecters''', min(len(a) for a in vault_apps))
goback_menu()
break
as you can see if there is < than one app stored it should print out ('''there is no summary of your acount as,
you currently have 0 apps and passwords stored on your account''') but instead i get this error: max(len(a) for a in vault_apps))
builtins.ValueError: max() arg is an empty sequence
Full code--->
vault_apps = []
users_passwords = ""
username = ""
vault_password = ""
def exit_code(): #This funnction exits the code, and is made into a function as many times through the program I need to exit the code, and now I can just call multiple times through this unction
while True:
print('''\n\n\n\nYou have succesesfuly and safely logged out of password locker
Goodbye!''')
exit() #this is a function for exit it exits the code, but on wing101 it takes you to an exit page which is made by the program called 'sitebulletins'
def goback_menu(): # this code allows the user to go to the main menue of the vault, and also exit at the same time, it was made so instead of always typing the main menue i can call it
goback = input('''Would you like to go back to the main menu or exit the code?, answer with
yes, or exit
''')
if goback == "yes":
locker_menu_func()
elif goback == "exit":
print("okay")
exit_code()
else: print('''please enter yes, or no''')
def existing_apps(): #this function correspons, to the main menu when the user wants to viw their stored apps and passwords, and if the user has none it asks them if they would like to go back to the menu to add some
if len(vault_apps) < 1:
print('''you have currently 0 app and passwords stored on your account''')
goback_menu()
else:
app_names = [x[0] for x in vault_apps] #this displays the stored apps, that the user has entered, if he has any
app_names_pretty = ''' this is for the join attribute which joins the strings within the variables, making them easier to format
'''.join(app_names)
print(f'''Here are the apps which you have stored information on,
------------------
{app_names_pretty}
------------------
which apps information do you want to view''') #I have used f-string as it is better than a format statment, as we are printing a list, i can print with no additional brackets and can be manipulated easier to look nuice
while True:
users_passwords = input()
if users_passwords == "":
print('''Please enter a valid answer''')
else:
for a in vault_apps: #if a (the app information the user is looking for is in thevault_apps list, print it out with the rest of its information like password
if users_passwords in a:
print('''{}password: {}'''.format(users_passwords, a[1]))
while True:
more_apps = input('''press,
1) to see the information of your other apps
2) to return to the main menu
3) to exit the code
''')
if more_apps == "1": existing_apps
if more_apps == "2": locker_menu_func()
if more_apps == "3": exit_code()
else:
print('''please input a valid answer''')
break
def store_apps():
while True:
app_name = input('''What is the name of the website/app you are adding?
''')
if 0 < len(app_name) < 16:
break
elif app_name == "":
print("Please enter an answer")
while True:
app_password = input('''What is the password of your {} account?
'''.format(app_name))
if app_password == "":
print("Please enter an answer")
else: vault_apps.append([app_name, app_password])
addapp()
break
def addapp():
add_app = input('''would you like to add another app and password, yes or no
''')
if add_app.lower() == "no":
locker_menu_func()
elif add_app.lower() == "yes":
store_apps()
else:
print("please enter a proper answer")
def app_summary():
while True:
if len(vault_apps) < 1:
print('''there is no summary of your acount as,
you currently have 0 apps and passwords stored on your account''')
else: print('''You have {} app and its information stored'''.format(len(vault_apps)))
print('''Your longest password is charecters''', max(len(a) for a in vault_apps))
print('''Your shortest password is charecters''', min(len(a) for a in vault_apps))
goback_menu()
break
def locker_menu_func():
print('''
You have opened the locker,
Please select what you would like to do,''')
locker_menu_var = input('''Press: \n1) find your existing passwords \n2) save a new password for your apps
3) see a summary of your password locker \n4) exit password locker
---------------------------------------------------------------------------------
''')
print('''----------------------------------------------------------------''')
while True:
if locker_menu_var == "1": existing_apps()
if locker_menu_var == "2": store_apps()
if locker_menu_var == "3": app_summary()
if locker_menu_var =="4": exit_code()
break
print("------------------------------------------------------------------------")
print('''Welcome to password Locker, a place where you can
store all your passwords to easily enter your precious accounts without
hassle.''')
print("------------------------------------------------------------------------")
print('''First lets make an account,''')
while True:
first_name = input('''What is your first name?
''')
if first_name.isdigit(): #isdigit, detects if there
print("Please enter a valid answer, No nubers shoud be present")
elif first_name == "":
print("Please enter an answer")
else:
break
while True:
sur_name = input('''What is your surname?
''')
if sur_name.isdigit(): #isdigit detects if the
print("No numbers")
elif sur_name == "":
print("Please enter an answer")
else:
break
def login_originup1(username, vault_password):
print(''' Welcome to password vault,
You can either login or create a New account''')
while True:
login_orsignup1 = input(''' Press \n1) to Log in
:''')
if login_orsignup1 == "1":
while input('''--------------------------------------------------------
What is your username: ''') != username:
print("Incorrect username")
while input("What is your password: ") == vault_password:
print('''-----------------------------------------------------------
''')
locker_menu_func()
break
else:
print("Incorrect password")
#Main Routine
print('''------------------------------------------------------------------------''')
print('''Welcome, {} {}
what would you like your username to be, it should be something
memorable and no longer than fifteen characters long, '''.format(first_name, sur_name))
while True:
username = input("")
if 0 < len(username) < 16:
print('''Nice, username''')
break
elif username == "":
print("Please enter an answer")
else:
print('''Your username should be a maximum of 15 charecters, ''')
print('''-------------------------------------------------------------------------''')
while True:
vault_password = input('''Now it's time to setup a password for your locker, It should be between 4
and 10 charecters long,
''')
if len(vault_password) > 4 and len(vault_password) < 11:
print('''{}, is locked in thanks for joining Password Locker'''.format(vault_password))
break
else:
print("It should be between 4 and 10 charecters long!")
print('''
-------------------------------------------------------------------------------------------''')
login_originup1(username, vault_password)
The indentation of the else: block is wrong, it should be:
else:
print('''You have {} app and its information stored'''.format(len(vault_apps)))
print('''Your longest password is charecters''', max(len(a) for a in vault_apps))
print('''Your shortest password is charecters''', min(len(a) for a in vault_apps))
As a general rule, you could avoid putting else: blocks on the same line, this would avoid such problems when you add lines to them afterwards.
Your indentation is wrong. All your print calls should be in the else block. Also, consider using f-strings and factoring out your generator expressions for the lengths into a separate list:
if not vault_apps:
print('There is no summary of your account as you have no apps and passwords stored.')
else:
lengths = [len(a) for a in vault_apps]
print(f'You have {n_apps} apps and their information stored.')
print(f'Your longest password is {max(lengths)} characters.')
print(f'Your shortest password is {min(lengths)} characters.')
Is there a way to set a 30 second timer to verify a username for a program before it returns back to the start line, and requests for the user to input the name again? This is what I have so far:
print("")
verifyp1loop = True
while verifyp1loop==True:
verifyp1 = input("Please input Player 1's username. ")
verifyp1confirm = input("Are you sure you want this to be your username? y/n ")
if verifyp1confirm == "y":
print("Username confirmed.")
verifyp1loop=False
else:
print("Username denied.")
verifyp2loop = True
while verifyp2loop==True:
verifyp2=input("Please input Player 2's username. ")
verifyp2confirm=input("Are you sure you want this to be your username? y/n ")
if verifyp2confirm == "y":
print("Username confirmed.")
verifyp2loop=False
else:
print("Username denied.")
I'm very new to this and any help would be appreciated :)
Lightweight solution:
no loops
no threads
just example how to implement timeout
import time
class Verify(object):
def __init__(self,timeout):
self.timeout = timeout
self.verification = None
def verify(self):
self.verification = None
start_verification = time.time()
verifyp1confirm = input("Are you sure you want this to be your username? y/n ")
end_verification = time.time()
if (end_verification-start_verification)>self.timeout:
print('Denied')
self.verification = 0
else:
print('OK')
self.verification = 1
>>> ver=Verify(3)
>>> ver.verify()
Are you sure you want this to be your username? y/n y
OK
>>> print(ver.verification)
1
>>> ver.verify()
Are you sure you want this to be your username? y/n y
Denied
>>> print(ver.verification)
0
Note same answer, different output
Implementation:
ver=Verify(3)
while ver.verification == None or ver.verification ==0:
ver.verify()
I am writing a program that asks the user to enter a password. If the password matches the constant I've set it prints out a "successfully logged in message". However if the password is incorrect, it gives the number of guesses left and asks the user to try again. The program should end after 3 incorrect guesses but it keeps on asking even after 3 attempts have been used. I think the problem is in my while loop but I am unsure.
Code:
def main():
PASSWORD = "apple"
ALLOWED = 3
password = input("Enter the password: ")
while password != PASSWORD :
ALLOWED = ALLOWED - 1
print("Wrong. You have", ALLOWED, "guesses left")
if ALLOWED == 0:
print("You have been locked out")
password = input("Enter again ")
print("You have successfully logged into the system")
main()
Right now you never exit your while loop. To break out of it, use the break keyword.
To exit your program completely, you will need to import sys and sys.exit()
I suggest adding these to your if ALLOWED == 0 statement.
You need to use break to exit the loop, or add a secondary condition, otherwise it will keep going anyway until the password is correct.
So, either:
while (password != PASSWORD) and (ALLOWED > 0):
Or:
if ALLOWED == 0:
print("You have been locked out")
break
The condition password != PASSWORD is not enough to exit the loop (It will exit the loop only if you give the right password). Add the condition also in while (password != PASSWORD and ALLOWED > 0)
Change print("You have been locked out") to sys.exit("You have been locked out") (or otherwise exit the main). Remember to import sys to use sys.exit.
Your while loop requires a correct password to finish, and there is no other way to exit the loop. I suggest a break statement:
def main():
PASSWORD = "apple"
ALLOWED = 3
password = input("Enter the password: ")
while password != PASSWORD :
ALLOWED = ALLOWED - 1
print("Wrong. You have", ALLOWED, "guesses left")
if ALLOWED == 0:
print("You have been locked out")
break
password = input("Enter again ")
print("You have successfully logged into the system")
You may want to do more research if your program needs to be secure.
Managed to make it work but just making it check if ALLOWED == 0 and if it does print "you are locked out", and if ALLOWED <= 0 then it will not let you go any further.
def main():
PASSWORD = "apple"
ALLOWED = 3
password = input("Enter the password: ")
while password != PASSWORD or ALLOWED <= 0:
ALLOWED = ALLOWED - 1
if ALLOWED > 0: print("Wrong. You have", ALLOWED, "guesses left")
if ALLOWED == 0: print("You have been locked out")
if ALLOWED < 0:
print("You have been locked out")
password = input("Enter again ")
print("You have successfully logged into the system")
main()
also wrote a different version which seemed easier in my opinion
def main():
USERNAME = "admin"
PASSWORD = "root"
ATTEMPTS = 3
while ATTEMPTS >= 1:
print("You have",ATTEMPTS,"attempts left")
if ATTEMPTS == 0:
break
user = input("Please enter your username:")
password = input("Now enter your password:")
if user == USERNAME and password == PASSWORD:
print("\nYou have successfully logged into the system")
return
else:
print("\nThis user name or password does not exist\n")
ATTEMPTS -= 1
print("you have been locked out.")
main()