Python Forum
don't understand format of if/else statements
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
don't understand format of if/else statements
#1
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
Reply
#2
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.
Reply
#3
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?
Reply
#4
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...
Reply


Possibly Related Threads…
Thread Author Replies Views Last Post
  Need help implmenting if/else or case statements for option to choose file format. samlee916 1 2,021 Jul-22-2020, 06:06 PM
Last Post: Larz60+

Forum Jump:

User Panel Messages

Announcements
Announcement #1 8/1/2020
Announcement #2 8/2/2020
Announcement #3 8/6/2020