python if + else if statement - python

I'm new to python so please kindly help, I don't know much.
I'm working on a project which asks for a command, if the command is = to "help" then it will say how to use the program. I can't seem to do this, every time I try to use the if statement, it still prints the help section wether the command exists or not.
example: someone enters a command that doesn't exist on the script, it still prints the help section.
print("welcome, to use this, please input the options below")
print ("help | exit")
option = input("what option would you like to use? ")
if help:
print("this is a test, there will be an actual help section soon.")
else:
print("no such command")

Check using == equality operator
print("welcome, to use this, please input the options below")
print("help | exit")
option = input("what option would you like to use? ")
if option == "help":
print("this is a test, there will be an actual help section soon.")
else:
print("no such command")

You need to reference your variable option in the if statement for it to work.
print("welcome, to use this, please input the options below")
print ("help | exit")
option = input("what option would you like to use? ")
if option == "help":
print("this is a test, there will be an actual help section soon.")
else:
print("no such command")
I'm also just starting with Python and I hope we both can learn a lot from here.

Try this.
`print("welcome, to use this, please input the options below")
print ("help | exit")
option = input("what option would you like to use? ")
if option == "help":
print("this is a test, there will be an actual help section soon.")
else:
print("no such command")`

Related

How do I use an elif statement properly?

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.

Building a basic program that has user input a number to indicate instructions for a menu of options. Stuck on verifying it's an acceptable answer?

##Creation of a menu for user to choose from
print ("Please choose an activity from the list: ")
print ("1: Instruction List 1")
print "" ##Formatting line
userInput = input("Please enter your choice: ")
"""Create the desired instructions based on the user input by
integrating a function"""
def instructions_List(userInput):
if isinstance(userInput, int) == True and userInput == 1:
print "User instructions here"
return
elif userInput.isalpha():
print "That was not an option on the menu!"
return
else:
print "That was not an option on the menu!"
return
##Run the function to do what is intended for the program
instructions_List(userInput)
So the idea is a user will be shown a menu of options to choose from. Once they select an option the screen will display instructions to follow for the menu options. I'm practicing my skills by first making sure the user can't input something beyond what the menu has displayed. I understand I will need to eventually integrate loops to make it restart from the beginning. But for now I'm trying to make sure it only accepts integers or floats, just anything that is not a string or not an option on the menu. When I run the code and input a string such as abc, it's kicking out errors trying to claim the string a variable in the code. What am I doing wrong here?
Tested your code and it works just fine.

Python input only accept one argument

I am writing a text game in python 3.3.4, at one point I ask for a name. Is there a a way to only accept one name, (one argument to the input) and if the user inputs more than one arg.
Here is what I currently have.
name =input('Piggy: What is your name?\n').title()
time.sleep(1)
print('Hello, {}. Piggy is what they call me.'.format(name))
time.sleep(1)
print('{}: Nice to meet you'.format(name))
time.sleep(1)
print('** Objective Two Completed **')
I am guessing I will need to use something like while, and then if and elif.
Help is greatly appreciated
while True:
name = input("What is your name? ").strip()
if len(name.split()) == 1:
name = name.title()
break
else:
print("Too long! Make it shorter!")

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'.

Exit while loop by user hitting ENTER key

I am a python newbie and have been asked to carry out some exercises using while and for loops. I have been asked to make a program loop until exit is requested by the user hitting <Return> only. So far I have:
User = raw_input('Enter <Carriage return> only to exit: ')
running = 1
while running == 1:
Run my program
if User == # Not sure what to put here
Break
else
running == 1
I have tried: (as instructed in the exercise)
if User == <Carriage return>
and also
if User == <Return>
but this only results in invalid syntax.
Please could you advise me on how to do this in the simplest way possible.
Thanks
I ran into this page while (no pun) looking for something else. Here is what I use:
while True:
i = input("Enter text (or Enter to quit): ")
if not i:
break
print("Your input:", i)
print("While loop has exited")
The exact thing you want ;)
https://stackoverflow.com/a/22391379/3394391
import sys, select, os
i = 0
while True:
os.system('cls' if os.name == 'nt' else 'clear')
print "I'm doing stuff. Press Enter to stop me!"
print i
if sys.stdin in select.select([sys.stdin], [], [], 0)[0]:
line = raw_input()
break
i += 1
Actually, I suppose you are looking for a code that runs a loop until a key is pressed from the keyboard. Of course, the program shouldn't wait for the user all the time to enter it.
If you use raw_input() in python 2.7 or input() in python 3.0, The program waits for the user to press a key.
If you don't want the program to wait for the user to press a key but still want to run the code, then you got to do a little more complex thing where you need to use kbhit() function in msvcrt module.
Actually, there is a recipe in ActiveState where they addressed this issue. Please follow this link
I think the following links would also help you to understand in much better way.
python cross platform listening for keypresses
How do I get a single keypress at a time
Useful routines from the MS VC++ runtime
I hope this helps you to get your job done.
Use a print statement to see what raw_input returns when you hit enter. Then change your test to compare to that.
This works for python 3.5 using parallel threading. You could easily adapt this to be sensitive to only a specific keystroke.
import time
import threading
# set global variable flag
flag = 1
def normal():
global flag
while flag==1:
print('normal stuff')
time.sleep(2)
if flag==False:
print('The while loop is now closing')
def get_input():
global flag
keystrk=input('Press a key \n')
# thread doesn't continue until key is pressed
print('You pressed: ', keystrk)
flag=False
print('flag is now:', flag)
n=threading.Thread(target=normal)
i=threading.Thread(target=get_input)
n.start()
i.start()
You need to find out what the variable User would look like when you just press Enter. I won't give you the full answer, but a tip: Fire an interpreter and try it out. It's not that hard ;) Notice that print's sep is '\n' by default (was that too much :o)
if repr(User) == repr(''):
break
a very simple solution would be, and I see you have said that you
would like to see the simplest solution possible.
A prompt for the user to continue after halting a loop Etc.
raw_input("Press<enter> to continue")
user_input=input("ENTER SOME POSITIVE INTEGER : ")
if((not user_input) or (int(user_input)<=0)):
print("ENTER SOME POSITIVE INTEGER GREATER THAN ZERO") #print some info
import sys #import
sys.exit(0) #exit program
'''
#(not user_input) checks if user has pressed enter key without entering
# number.
#(int(user_input)<=0) checks if user has entered any number less than or
#equal to zero.
'''
Here is the best and simplest answer. Use try and except calls.
x = randint(1,9)
guess = -1
print "Guess the number below 10:"
while guess != x:
try:
guess = int(raw_input("Guess: "))
if guess < x:
print "Guess higher."
elif guess > x:
print "Guess lower."
else:
print "Correct."
except:
print "You did not put any number."
You are nearly there. the easiest way to get this done would be to search for an empty variable, which is what you get when pressing enter at an input request. My code below is 3.5
running = 1
while running == 1:
user = input(str('Enter <Carriage return> only to exit: '))
if user == '':
running = 0
else:
print('You had one job...')
I recommend to use u\000D. It is the CR in unicode.
Here's a solution (resembling the original) that works:
User = raw_input('Enter <Carriage return> only to exit: ')
while True:
#Run my program
print 'In the loop, User=%r' % (User, )
# Check if the user asked to terminate the loop.
if User == '':
break
# Give the user another chance to exit.
User = raw_input('Enter <Carriage return> only to exit: ')
Note that the code in the original question has several issues:
The if/else is outside the while loop, so the loop will run forever.
The else is missing a colon.
In the else clause, there's a double-equal instead of equal. This doesn't perform an assignment, it is a useless comparison expression.
It doesn't need the running variable, since the if clause performs a break.
If you want your user to press enter, then the raw_input() will return "", so compare the User with "":
User = raw_input('Press enter to exit...')
running = 1
while running == 1:
Run your program
if User == "":
break
else
running == 1
The following works from me:
i = '0'
while len(i) != 0:
i = list(map(int, input(),split()))

Categories

Resources