How do I use an elif statement properly? - python

Please don't judge me.. I've only been working with Python for a month now.
While laying in my bed I thought of making this and created it in a few minutes but I made to many else and if statements and my code just looks so messy, I kept adding things that weren't needed..(For fun :D)
Anyways, here is my code.. If you could tell me how to use the "elif" statements properly that'd be awesome.(I'm still learning python)
Question: I've tried using an elif statement multiple times and I keep getting an error. How do I fix this?
key = True # Game key, if this is false the program won't work.
print("Please type a password: ") # Asking for users password
Pass = input()
print("Thank you for typing your password, please make sure it's secure by trying again..") # Ask them to confirm their password by re-typing it
Again = input()
if Pass == Again:
print("Thank you for choosing a working password, please create your character")
print("Please type your username without numbers")
else:
print("Something's wrong with your password or username!")
# Has user confirm if his information is correct
User = input()
print("checking..")
if User.isalpha() and key == True:
print("So your Username is " + User + " and your chosen password is: " + str(Pass))
else:
print("Either your key is broken or something is wrong..")
if len(User) >= 4: # Checking if the chosen username has 4 or more characters in it
print("The length of your Username is: ")
print(str(len(User)))
print("If this information is correct please type 'true' or 'false'")
else:
print("Please type a username longer than 4 characters!")
answer = input() # I kinda fucked up because my coding is dirty and unorganized lol..
if answer == str(True):
print("Thank you, we're setting up your account! :D")
else:
print("Please re-run the program and fix your information!")

We can't debug code you haven't posted, and (as is to be expected - you are on a learning exercise here, and there's a lot to think about) your program structure isn't very helpful. For example, when the user enters non-matching passwords you tell them about it, but nevertheless continue to ask them for their username. Don't worry about this, you will soon learn how to fix it.
Since you ask about the elif, it is basically a syntax abbreviation for else if that avoids going to multiple indentation levels. Suppose you wanted a value of '1' or '2' to take different actions, and to declare other values invalid. You could write
if value == '1':
#take action appropriate to 1
else:
if value == '2':
# take action appropriate to 2
else:
raise ValueError("Allowed inputs are '1' or '2'")
Note that the different actions are at different indentation levels. The more cases you have to consider, the more levels of indentation you have to introduce. So it's generally felt to be more readable to write
if value == '1':
# Take action appropriate to 1
elif value == '2':
# Take action appropriate to 2
else:
raise ValueError("Allowed inputs are '1' or '2'")
Now all the actions and decisions are at the same indentation levels. That's pretty much all there is to it. If you leave the else case off then you won't take any actions at all, so it's normally used to specify the default action, in this case raising an exception.
PS: If you want to be sure the user has entered two matching passwords before you proceed, look at the while loop, which allows you to repeat a set of actions until some condition (in this case the passwords being equal) is true.

Here is an example if if/elif/else statement in python3:
test = 'mytest'
if test == 'not_my_test':
print('nope')
elif test == 'mytest':
print('yay')
else:
print('something else')
You can find more information here : https://docs.python.org/3/tutorial/controlflow.html
EDIT:
As a general remark, you should not define variable using capital letters (PEP convention: https://www.python.org/dev/peps/pep-0008/?)

So using Elif
if Pass == Again:
print("Thank you for choosing a working password, please create your character")
print("Please type your username without numbers")
elif Pass != Again:
print("Something's wrong with your password or username!")
Though what is this error you're getting, we can't really help you without it.

Related

A Loop I can never return from

So I have been tasked with creating a Login function using an intake from a pickle file, my only issue (that I have noticed) so far is that I can never get out of the loop.
for counter in range(len(Users)):
UserN = input("Username: ")
if UserN in Users[counter]:
PassW = input("Password: ")
if PassW in Users[counter]:
print("User Authenticated")
break
else:
attempt = 1
while attempt != 4:
print("Password Incorrect | Attempt", attempt)
PassW = input("Password: ")
if PassW in Users[1]:
print("User Authenticated")
MainMenu()
else:
attempt = attempt + 1
if attempt == 4:
print("\nToo many attempts, you are locked out")
exit()
else:
print("\nUser not found!\n")
If the user is authenticated, the count of the attempt will stop increasing, but the condition for the while-loop is stop is attempt == 4, so it will be stuck until the user has typed in the wrong password 4 times.
To fix it, either add a variable authenticated before the while-loop and initialize it as False, then set it to True once the user has successfully been authenticated.
attempt = 1
authenticated = False
while attempt != 4 and !authenticated:
...
if PassW in Users[1]:
...
authenticated = True
Or if you don't want a new variable, simply break by
if PassW in Users[1]:
...
break
to break the loop
If you the password is found, you call another function but you never exit from the loop. You should add a break statement.
You can add a break statement under
MainMenu()
break;
The logic in your code seems quite wonky.
This code assumes that the username is the first appearing in Users; if the second user logs in, they need to enter their name twice, the third user 3 times, and so on. If you mistype your name on your "turn", you won't be able to log in at all.
I would suggest the following structure:
Turn your variable "Users" into a dictionary, mapping user name to password.
Ask the user name.
If the user name does not appear, either stop or loop (you might want to prompt to ask whether they want to try again or not, or just let them press ctrl-D to stop (and catch the ensuing EOFError or KeyboardInterrupt (which happens if they press ctrl-C instead).
Some other issues, that are not as crucial for this question but good guidelines:
Use proper style conventions. Variable names should not start with upper case characters. Same for goes for functions. It should be users, passw, main_menu().
You really should not store passwords in a pickle file; that is obfuscation rather than security. Have a look at https://www.geeksforgeeks.org/getpass-and-getuser-in-python-password-without-echo/ for better practices.
When you say the user is locked out, nothing actually happens. They are not really locked out; they could just try again. That means you can just create a bit that brute-forces password guesses
Let them enter the password, with a maximum number of guesses.
A good rule is to test for attempt > 3 instead of attempt == 4. This does not make a difference here, but in larger functions, it's often good practice to make the test a bit "wider".

Noob's python journey pt. 1: Functions and commands that jump everywhere [duplicate]

This question already has answers here:
Asking the user for input until they give a valid response
(22 answers)
Closed 3 years ago.
So, noob here, now that's out of the way let's get to the problem shall we?
(First post, ever)
So, my code (below) is quite inconsistent. I have just begun, about two days ago, and I'm dying to become better and love all kinds of critique, so unload all you've got.
When the user enters "login" to login he gets prompted to enter the username (a separate function creating a global variable for the password function to use as the welcoming name.) and is immediately redirected to the password check. Here there are two outcomes: 1. The user types in the correct password, the user will be "let in:" "Welcome " + username + "." 2. The user types in the wrong password/types anything that isn't the password: the user is sent back to the username check. But what happens for me is that the Python instead jumps back to the intro code and exits the program with: "Invalid input." And it seems as if the program goes to the password function, does its thing and immediately reverts to the former function.
Tl:Dr: Functions don't loop as they should, instead return to the previous function, thus ignoring the action I wrote.
Excuse me for the wall of text, and please, please please for the love of god or anything, don't hit me with a wall of code and "Fixed!" I'm very new and barely understand anything outside this patch of code which I myself wrote with my new gained experience. Otherwise it will end up with a [ctrl + c --> ctrl + v] situation and I really, really want to learn, not copy. So if you think you have what it takes, please do your best, everything is appreciated :)
Ps: Tips & Tricks are valuable for me!
PPs: If you want more code, just say it and I'll do my best.
Changes in the login screen:
choice = input
if input blah blah:
"function"
creating a whole function for it
moving the commands around
messing with other codes
# Password check.
def password_check():
print("Please enter your password")
print("")
password = input("")
if password == "1234":
return "Welcome " + username + "."
elif password != "1234":
username_check()
# Intro screen: invalid input notifier.
if choice != ["login", "exit"]:
print("Invalid input.")
input(" ")
Your if statement checking password was in the global area and not inside your function.
# Password check.
def password_check():
password = input("Please enter your password\n\n ")
if password == "1234":
return "Welcome " + username + "."
elif password != "1234":
username_check()
# Intro screen: invalid input notifier.
if choice != ["login", "exit"]:
print("Invalid input.")
input(" ")

Have the boolean value of var follow into another file

I have two files in my text-based game. The variable that is being assigned will be keep_note.
If you enter "Take" the boolean value True is assigned to the have_note-001
but in the next file when if have_note_001 == True I get an error saying
have_note-001 is undefined
If keep_note is == "Take":
have_note_001 = True
Then in the next file I want that True value to travel over to the next file.
If have_note_001 == True: print("This Value Is True")
keep_paper = input("Do you want to Leave the piece of paper or Take it? > ")
if keep_paper == "Take":
have_note_01 = True
if have_note_01 == True:
print("You have chosen to keep the piece of paper")
print("You leave the house with the note(" + note_001 + ")")
This is my next file
from intros.intro_001 import have_note_001
if have_note_01 == True:
print("True")
elif have_note_01 == False:
print("False")
In the file, the import is working.
I am importing the have_note_001. It is just not transferring the value True over. It doesnt seem to remember when you give it that value you in the first file, to the second
How can I have the value assigned to a variable carry over to another file when imported?
I'm not sure what you are asking for is in your best interest. The values stored in variables are already carried over by default when you import the file they are from. However, this type of sporadic architecture is not really considered good practice. Let me give you some feedback on your program. First lets give it some input validation:
# start off setting keep_paper to nothing
keep_paper = ''
# As long as the player does not enter 'take' or 'leave' we are going to
# keep asking them to enter a proper response.
while keep_paper not in ['take', 'leave']:
# here we are going to "try" and ask the player for his choice
try:
# here we are getting input from the user with input(...)
# then converting it into a string with str(...)
# then converting it to lowercase with .lower()
# all together str(input(...)).lower()
keep_paper = str(input("Do you want to Leave the piece of paper or Take it? > ")).lower()
# if the player entered an invalid response such as "53" we will go back
# to the beginning and ask for another response.
except ValueError:
print("Sorry, I didn't understand that.")
# ask the user to provide valid input
continue
if have_note_01 == True:
print("True")
elif have_note_01 == False:
print("False")
Now let's address the main topic of your question. Having the value assigned to a variable carry over on imports. As I've already mentioned, this is generally not something that you want, which is why most Python programs have code including:
if __name__ == "__main__":
# do xyz....
This ensures that xyz is only run if the file is being ran, and will not run if the file is imported.
For good measure, I recommend you checkout: https://github.com/phillipjohnson/text-adventure-tut/tree/master/adventuretutorial, reading over the code in this project will give you a better idea at how you might want to tackle your own project. (The basics of functions, classes and inheritance)

User inputted script

I am trying to run a script which asks users for their favorite sports teams. This is what I have so far:
print("Who is your favorite sports team: Yankees, Knicks, or Jets?")
if input is "Yankees":
print("Good choice, go Yankees")
elif input is "Knicks":
print("Why...? They are terrible")
elif input is "Jets":
print("They are terrible too...")
else:
print("I have never heard of that team, try another team.")
Whenever I run this script, the last "else" function takes over before the user can input anything.
Also, none of the teams to choose from are defined. Help?
Input is a function that asks user for an answer.
You need to call it and assign the return value to some variable.
Then check that variable, not the input itself.
Note
you probably want raw_input() instead to get the string you want.
Just remember to strip the whitespace.
Your main problem is that you are using is to compare values. As it was discussed in the question here --> String comparison in Python: is vs. ==
You use == when comparing values and is when comparing identities.
You would want to change your code to look like this:
print("Who is your favorite sports team: Yankees, Knicks, or Jets?")
if input == "Yankees":
print("Good choice, go Yankees")
elif input == "Knicks":
print("Why...? They are terrible")
elif input == "Jets":
print("They are terrible too...")
else:
print("I have never heard of that team, try another team.")
However, you may want to consider putting your code into a while loop so that the user is asked the question until thy answer with an accepted answer.
You may also want to consider adding some human error tolerance, by forcing the compared value into lowercase letters. That way as long as the team name is spelled correctly, they comparison will be made accurately.
For example, see the code below:
while True: #This means that the loop will continue until a "break"
answer = input("Who is your favorite sports team: Yankees, Knicks, or Jets? ").lower()
#the .lower() is where the input is made lowercase
if answer == "yankees":
print("Good choice, go Yankees")
break
elif answer == "knicks":
print("Why...? They are terrible")
break
elif answer == "jets":
print("They are terrible too...")
break
else:
print("I have never heard of that team, try another team.")

Managing user input's case in Python

I have set up a script to say something when the user enters something other than Yes. However it still says this when the user says Yes. What am I doing wrong?
I am using Python 2.7.2.
Here is my code:
print 'Hi! Welcome!'
begin = raw_input ('Will you answer some questions for me? ')
if begin == 'yes':
print 'Ok! Let\'s get started then!'
else:
print 'Well then why did you open a script clearly entiled\'QUIZ\'?!'
Just change the line
if begin == 'yes':
to
if begin.lower() == 'yes':
Because string compare is case sensitive, the match will only if true iff user enters the reply in lower case
The issue here is case sensitivity.
>>> "yes" == "Yes"
False
Try using str.lower() on the user input before your comparison to ignore case. E.g:
print 'Hi! Welcome!'
begin = raw_input ('Will you answer some questions for me? ')
if begin.lower() == 'yes':
print 'Ok! Let\'s get started then!'
else:
print "Well then why did you open a script clearly entiled\'QUIZ\'?!"
#If a single apostrophe is used inside the print str then it must be surrounded by double apostrophes.
Abhijit's method also works if you just want to accept more than one version of a string from a user. For example, I'm using this to confirm whether the user wants to exit:
confirm = input('Are you sure you would like to exit? N to re-run program')
if confirm.lower() in ('n','no'): #.lower just forces the users input to be changed to lower case
print("I'll take that as a no.")
return confirm #this then just goes back to main()
else:
exit()
This way either 'n' or 'N'; 'no' or 'NO' or 'nO' are all accepted cases of 'no'.

Categories

Resources