Python Forum
don't understand format of if/else statements - Printable Version

+- Python Forum (https://python-forum.io)
+-- Forum: Python Coding (https://python-forum.io/forum-7.html)
+--- Forum: General Coding Help (https://python-forum.io/forum-8.html)
+--- Thread: don't understand format of if/else statements (/thread-29630.html)



don't understand format of if/else statements - Colin999 - Sep-14-2020

Hello, I'm using PythonAnywhere.com. I don't understand how to format these if/else statements so when the user doesn't enter their name, the result will ONLY be "Please enter your name." Instead it adds "Hi You are a student".

first_name = input("What is your name? ")

if first_name == "":
    print("Please enter your name: ")

if first_name.lower() == "steve":
    print("You are the instructor")

else:
    print("Hi " + first_name + "you are a student")
Output:
What is your name? Please enter your name: Hi You are a student



RE: don't understand format of if/else statements - bowlofred - Sep-14-2020

Looks like you want them to be an if/elif/else group.

The second if resets the conditionals and is examined whether the first one was checked or not. If the second if is instead an elif, then only one of the three paths can be taken.


RE: don't understand format of if/else statements - Colin999 - Sep-14-2020

Oh excellent, ok. Can you give me a very brief example of how an elif would work?

Ok, I think I got it, but I don't know why it adds the next user input line of code when I don't want it to yet?

first_name = input("What is your name? ")

if first_name == "":
    print("Please enter your name: ")

elif first_name.lower() == "steve":
    print("You are the instructor")

else:
    print("Hi " + first_name + " You are a student")

print()

birth_year = input("What year were you born? ")
Output:
What is your name? Please enter your name: What year were you born?



RE: don't understand format of if/else statements - bowlofred - Sep-14-2020

If there's no name, you enter the if block. The only thing in that block is a print. You then continue past the end of the else block.

You'd probably want a loop of some sort so that if there's no name, you go back and ask for the name again.

first_name = ""
while first_name == "":
    first_name = input("What is your name? ")

# can't get here until something is entered for the name.
# do further tests for the person...