How to create a number menu in python - python

i need a simple python code which makes a number menu, that doesn't take up many lines
print ("Pick an option")
menu =0
Menu = input("""
1. Check Password
2. Generate Password
3. Quit
""")
if (menu) == 1:
Password = input("Please enter the password you want to check")
points =0
i tried this but it did not work how i thought it would. i thought this code would work as i have tried it before and it worked but i must have made a mistake in this one.
anyone have any suggestions?
thanks
this is my full code:
print ("Pick an option")
menu =0
Menu = input("""
1. Check Password
2. Generate Password
3. Quit
""")
if (menu) == 1:
Password = input("Please enter the password you want to check")
points =0
smybols = ['!','%','^','&','*','(',')','-','_','=','+',]
querty =
["qwertyuiop","QWERTYUIOP","asdfghjl","ASDFGHJKL","zxcvbnm","ZXCVBNM"]
if len(password) >24:
print ('password is too long It must be between 8 and 24 characters')
elif len(password) <8:
print ('password is too short It must be between 8 and 24 characters')
elif len(password) >=8 and len(password) <= 24:
print ('password ok\n')

There are some fundamental flaws with your code that tells us you are not sure what the difference between types are (str vs int), or what some functions actually do (input()). These need to be corrected before you progress any further with your program.
Lets take a look at what your code currently does:
print ("Pick an option") # prints a message
menu = 0 # initializes a variable (menu) of type int to 0
Menu = input(""" # prints a message to receive input for variable (Menu) of type str
1. Check Password
2. Generate Password
3. Quit
""")
if (menu) == 1: # conditional check against (menu) to int of 1
...
Now stop here and look a little closer:
menu = 0 this sets a variable called menu equal to 0; the variable has a lowercase m and is of type int since you initialized it with an int.
Menu = input(...) this sets a variable called Menu equal to a str received from input(). So if you input 1, then what happens is a str is returned such that Menu = '1'. Notice that the variable has an uppercase M unlike menu before it; also note the ' ' around the 1. That means this is a str.
if (menu) == 1:... this checks the lower case'd menu against 1. Well you initialized menu = 0 and then you never touch the lower case'd menu again, so when you get to this it is still 0. So of course this will fail.
Given all that, here is what you can do to fix your code:
menu = 0
menu = int(input("Pick an option:\n"
"1. Check Password\n"
"2. Generate Password\n"
"3. Quit\n\n"
"Option Selected: ")
if (menu) == 1:
....

Because you are comparing a str and int. convert it into int
print ("Pick an option")
Menu = int(input("""
1. Check Password
2. Generate Password
3. Quit
"""))
if Menu == 1:
Password = input("Please enter the password you want to check")
points =0

Related

How to make my code break out of loop and actually detect a certain input

I am doing a basic Python assessment on a password vault but am getting errors that I can't seem to solve myself. and btw guys I didn't come here for a grammar and punctuation lesson, so if you are just here to edit my question and not offer any assistance please dont bother.
For example, in this part of the code I want the user to input 1 or 2, and if he selects 1 it asks him to log in, while if he selects 2 it asks him to register. But at the moment it is completely ignoring the parameters and accepting anything.
Another problem is that when the user enters the valid password, instead of just stopping at password correct, it for some reason re-asks "what is your username."
while True:
login_orsignup1 = input('''Press
1) to Log in
2) to register a new account
''')
if login_orsignup1 != 1:
while True:
username = input('''What is your,
Username: ''')
if input_username == username:
l_p = input('''What is your password ''')
while True:
if l_p == input_lockerpassword:
print("Password Correct")
break
login_originup1()
----------------------------------------------------------#Full code begins now
l_p = ""
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")
#the continue code skips the boundries within the loop and carries on with the connected program until it is succesfully met
else:
break #the break loop exits the current loop and continues with the next programes following it
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")
#the continue code skips the boundries within the loop and carries on with the connected program until it is succesfully met
else:
break
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:
input_username = input("")
if 0 < len(input_username) < 16:
print('''Nice, username''')
break
elif input_username == "":
print("Please enter an answer")
else:
print('''Your username should be a maximum of 15 charecters, ''')
print('''-------------------------------------------------------------------------''')
while True:
input_lockerpassword = input('''Now it's time to setup a password for your locker, It should be between 4
and 10 charecters long,
''')
if len(input_lockerpassword) > 4 and len(input_lockerpassword) < 11:
print('''{}, is locked in thanks for joining Password Locker'''.format(input_lockerpassword))
break
else:
print("It should be between 4 and 10 charecters long!")
print('''
-------------------------------------------------------------------------------------------''')
def login_originup1():
print(''' Welcome to password vault, You can either login or create a New account''')
while True:
login_orsignup1 = input('''Press
1) to Log in
2) to register a new account
''')
if login_orsignup1 != 1:
while True:
username = input('''What is your,
Username: ''')
if input_username == username:
l_p = input('''What is your password ''')
while True:
if l_p == input_lockerpassword:
print("Password Correct")
break
login_originup1()```
Ok, first of all, you should know that the input() function returns a string and, as such, your first condition : if login_orsignup1 != 1 will always be true, because the string object '1' isn't equal to the int object 1. As for why you get asked again for the user after having a good password, that is because the break statement only breaks from the current loop. So you only break of this loop to get back at the start of your username verification loop. I would suggest a cleaner implementation like so :
# login or sign-up loop
while True:
login_orsignup1 = input(" Press \n1) to Log in \n2) to register a new account")
# you can have the input result in a variable like so, if you want to use it later on
if login_orsignup1 == "1": # you said '1' was for login, right?
# or you can test this directly in your if statement
# if it is only needed for this condition
while input("What is your username: ") != username:
print("Incorrect username")
# same thing for password, but could be implemented another way if you
# don't want to loop until the user gets the correct password
while input("What is your password: ") != input_lockerpassword:
print("Incorrect password for this username")
# your code gets here only if the user entered the right credentials
# so you can now break of the login or sign-up loop
break
elif login_orsignup1 == "2":
# code for registration here
This could be good enough for a simple thing. I would recommend designing this console program by following concepts of a state-machine and adding more code at each step to handle cases like going back one step or back at the start.
Hope this helps
the problem is in your login_originup1 function you are making three While loops that the program can't escape from in your function you are asking if login_orsignup1 != 1
without an else statement so if the user wanted to login he would press input in "1" then the program will say that
"1" =! 1 is false
it will look for an else statement But not find one so it will go back to the start of the loop and ask the user to input again. this is it for the First Loop.
Now if the user Inputs in "2" (which means that the user wants to register) it will make him log-in because:
"2" =! 1is true
and will continue to the next while loop in here you will be asking for the username and the user will give the username. Now this is it for the Second Loop
we now go to the last loop where you ask for the Password and the User Will give the Password. The program Will either 1. say that it was false and ask for the password again or 2. it will accept the password and Break the While loop. Now this is it for the Third Loop
so why is it asking me for the Username Because the break statement breaks only the while loop it is in so that break statement broke only the third while loop and was back to the Second Loop which the Second Loop will bring us back into the Third Loop again
so how to fix this?
simple like this:
def login_originup1():
print('Welcome to password vault, You can either login or create a New account')
while True:
login_orsignu = input('Press\n1) to Log in\n2) to register a new account\n')
loopBreaker = 0
if loopBreaker:
break
if int(login_orsignu) != 1:
while True:
if loopBreaker:
break
username = input('What is your,\nUsername:')
if input_username == username:
l_p = input('What is your password ')
while True:
if loopBreaker:
break
if l_p == input_lockerpassword:
print("Password Correct")
loopBreaker = 1
break

python 3.3 Password checker

I am creating a program that checks passwords to see if they are strong enough:
they need caps,
lower case,
numbers,
symbols and
cannot contain easy passwords.
As you can see below this is only some of my code and I have a menu, and a password checker, the only problem is that the checker doesn't seem to be working as when I enter a password, its always saying its a strong password even though it does not contain any caps or numbers or symbols. Below is my code so far.
import random #importing random
import time #importing time
global Menu
def Menu():
global optionchoice #globalising variable optionchoice so that it can be used inside of another def of the code
print("Hey, Welcome to PassWordChecker.")
time.sleep(2) #delaying the next line for 2 seconds
print("Please choose one of the options below." )
time.sleep(1)
print("MENU:")
print("***")
print(" press 1 once for : password checker ")
print(" press 2 twice for : password generator")
print(" press 3 two or three times to : Quit ")
print(" ***") #creating a basic menu
optionchoice = (input("which option would you like to choose?"))
def checkpasswordandinput():
global optionchoice
optionchoice = optionchoice
if optionchoice == '1':
print(" please enter a password. ")
UserPassword = input("")
if len(UserPassword) <= 8 or len(UserPassword) >= 24 or UserPassword == UserPassword.isupper() or UserPassword == UserPassword.isdigit() or UserPassword == UserPassword.islower() or UserPassword == UserPassword.isalpha():
print("make sure your password includes numbers and upper and lower case letters ")
UserPassword = input('please enter a new password')
else:
print('your password is a very good one that is difficult to crack')
return Menu()
Notes to future readers:
Please do not write code in the form above:
Do not import modules you don't need
Do not use global variables
Do use loops: eg while True:
Do call functions from other functions
Do return values from one function back to the caller: optionchoice = menu()
The above code would have been better in this form:
import time
def menu():
print(" press 1 for password checker ")
print(" press 2 for password generator")
print(" press 3 to Quit")
return input("which option would you like to choose?")
def checkpasswordandinput():
while True:
optionchoice = menu()
if optionchoice == '1':
#Enter password and validate
pass
# detect other options
if optionchoice == '3':
break
checkpasswordandinput()
Those checks in the form UserPassword == UserPassword.isupper() will not work. Here, you are comparing a string, the password, to a boolean, the result of isX(). Hence, all those checks are False and you get to the else branch (if the length is acceptable).
In the case of upper and lowercase chars, you could use UserPassword == UserPassword.upper() instead (just upper, not isupper, and analogously with lower()), i.e. compare the password to it's upper/lowercased version, but for digits this does not work. Instead, you can use any to check if any char is a digit: any(c.isdigit() for c in UserPassword)
Edit: You can use UserPassword == UserPassword.upper() to check if the password does not contains any lowercase letters, which is kind of unintuitive. Instead, I'd suggest using any for all the checks and also inversing the condition so the "positive" case is in the ifs body and the "negative" in the else. Something like this:
up = UserPassword
if 8 <= len(up) <= 24 and any(c.isupper() for c in up) and any(c.islower() for c in up) and any(c.isdigit() for c in up) and any(c.isalpha() for c in up):
Or a bit shorter, using a list of functions:
if 8 <= len(up) <= 24 and all(any(f(c) for c in up) for f in (str.islower, str.isupper, str.isdigit, str.isalpha)):
So you need to do something like the following:
hasUpper = False
hasLower = False
hasDigit = False
etc etc
Then, go through the 'password' one character at a time:
ie. string[1], string[2], string[3]
Run your boolean result on it (isupper, islower, etc)
when true, change your hasUpper, hasLower, hasDigit to True
Then, once gone through the whole string, check your boolean results with your requirements. ie:
if requirements are upper, lower, and digit.
if hasUpper = True and hasLower = True and hasDigit = True:
then it's a good password, etc.
Make sense?

Limiting the amount of numbers in a user input

I'm making a 4 digit password guesser in python 3. I want to make sure that you can only put in 4 digit passwords and not 5 or 6 digit passwords. Here is the code I have so far.
print('your password will not be used or saved for later use you do not have to put in your real password')
real_password = int(input("please enter your four digit phone password here:"))
computer_guess = 0000
guess_counter = 0
yes = 'yes'
no = 'no'
print ("guessing your password...")
while computer_guess < real_password:
computer_guess = computer_guess + 1
guess_counter = guess_counter + 1
print("guess number", guess_counter)
print ("your password is", computer_guess)
Before you cast the input to an int, cast it to a str instead, then you can call the len() builtin method to check the length of the entered string. Check the documentation for details on this method. If it is greater than 4, then you should recall your input call. Something like the following should work:
>>> real_password = input("please enter your four digit phone password here: ")
please enter your four digit phone password here: 1234
>>> while len(str(real_password)) != 4:
... real_password = input("please enter your four digit phone password here: ")
In this condition the loop would not be ran, however if the entered string was not equal to 4, the loop would run until that condition was satisfied.
print('your password will not be used or saved for later use you do not have to put in your real password')
def get_password():
real_password = int(input("please enter your four digit phone password here:"))
if len(str(real_password)) != 4: # condition is not met if your variable
get_password() # is not 4, easily changed if you
else: # want
return real_password
#define a method and ask it to call itself until a condition is met
#
real_password = get_password() # here the method is called and the return
computer_guess = 0 # value is saved as 'real_password'
guess_counter = 0
yes = 'yes' # these are not used in your code
no = 'no' # but I'm am sure you knew that
print ("guessing your password...")
while computer_guess != real_password: # your loop should break when the
computer_guess += 1 # is found, not some other implied
guess_counter += 1 # the '+=' operator is handy
print("guess number", guess_counter)
print ("your password is", str(computer_guess)) # explicitly define the int
# as a string
I hope that helped...

Integer and string conflicts

Currently I'm working on an assignment that requires that I create a program in which the user enters a number between 0-4. The program then checks which number the user inputs and outputs a specific string. For example if the user enters 4, the program will output "80 or above: Level 4"
The problem is that the user should also be able to quit the program. I decided to create the program so if the user inputs something that is not blank (while input != "":) the program will run, but if they decide to hit enter the program will end.
This is the code I've come up with so far:
def get_level():
level = raw_input("Enter a number from 0-4 (Press <Enter> to quit): ")
return level
def check_mark(level):
if int(level) == 4:
print "80 or above: Level 4"
elif int(level) == 3:
print "70 - 79: Level 3"
elif int(level) == 2:
print "60 - 69: Level 2"
elif int(level) == 1:
print "50 - 59: Level 1"
elif int(level) == 0:
print "Below 50: Level 0"
else:
print "ERROR: out of range"
def output(level):
while level != "":
level = raw_input("Enter a number from 0-4 (Press <Enter> to quit): ")
check_mark(level)
print
def main():
user_level = get_level()
user_mark = check_mark(user_level)
print
program_output = output(user_level)
main()
I'm pretty aware that the problem has to do with the fact that raw_input only accepts strings which is what activates the "while level != "":" statement. I tried working around this by placing int() operators before each level. The problem is that it conflicts with the input if the user enters blank since it checks whether the input is an integer. Something like that anyways.
So I was hoping someone could guide me to finding a way around this. It would be much appreciated!
You probably want the next looping code:
def output(level):
level = raw_input("Enter a number from 0-4 (Press <Enter> to quit): ")
while level != "":
check_mark(level)
level = raw_input("\nEnter a number from 0-4 (Press <Enter> to quit): ")
I don't htink there is any shortcut around validating input. So the user can either type "" or an integer. What happens if the user types in letters?
I would verify all input to handle accordingly so the program doesn't break
# check for blank
if level == '':
# exit for user
# validate input if not exit
try:
level_int = int(level)
except ValueErrror:
# integer not inputed
if not (0 <= level_int <= 4):
# check that input is between 0 4
# out of range
or you could just check for expection in check_mark when you call it in main

Multiple raw_inputs

#Print out the menu
print """
###############################################
# 1 - Introduction. #
# 2 - Base. #
# 3 - Contact. #
###############################################"""
#Get the user's choice
choice = raw_input("")
#Work with choice
print choice
if choice == 1:
print "# Welcome to xbrEra's first application! #"
elif choice == 2:
print "# This application was built in Python 7.2.1. #"
elif choice == 3:
print "# Contact me at Blackriver.era#hotmail.com #"
else:
print "# Invalid choice! #"
That is my code. My problem is that after the first input has been completed, they next inputs will have ">>> " as a prefix. How do I change this, and also I keep getting "Invalid choice!" in the current code. Please help, thank you!
I keep getting "Invalid choice!" in the current code
raw_input() returns string in python 2.7, so you need to compare as
choice == "1"
or you may try with input() instead of raw_input(), which evaluate input as numbers.
or you could parse to integer with int(raw_input()) as J.F. Sebastian pointed out. non-integer input could cause errors, so wrap it with try: except: block like
try:
choice = int(raw_input(), 10)
except ValueError:
choice = None
ps: ", 10" is for base 10, input could be zero padded like 010, which could take input as octal numbers
#Print out the menu
ch = """###############################################
# 1 - Introduction. #
# 2 - Base. #
# 3 - Contact. #
###############################################
Enter your choice : """
choice = raw_input(ch)
warn = "\n You must enter 1 or 2 or 3.\n"+\
" Enter your choice : "
while choice not in ('1','2','3'):
choice = raw_input(warn)
print ("# Welcome to xbrEra's first application! #",
"# This application was built in Python 7.2.1. #",
"# Contact me at Blackriver.era#hotmail.com #")[int(choice)-1]
I think you need to code your new lines like this '\n''You must enter 1, 2, or 3.''\n'

Categories