SWHJ
SWHJ

Reputation: 464

Is there a more elegant way of using a 'while loop' without having to define variables outside the 'while loop' first?

I'm very much new to Stackoverflow and Python(3) so excuse any errors I've made! This is the code I wrote so far:

print("""You will need to enter your name so we can make a reservation!
(Use Enter ↵ to confirm)""")

user_firstname = str(input("What is your first name? "))
user_lastname = str(input("What is your last name?  "))
confirm_username = str(input("Is your name " + user_firstname + " " + user_lastname + " ? (y/n) "))[0]

while not confirm_username == "y":
    user_firstname = str(input("What is your first name? "))
    user_lastname = str(input("What is your last name?  "))
    confirm_username = str(input("Is your name " + user_firstname + " " + user_lastname + " ? (y/n) "))[0]
else:
    user_name = user_firstname + " " + user_lastname
    

As you can see in my example I have to state some variables twice (user_firstname, user_lastname & confirm_username). Once before the while loop and once within the while loop. I was wondering if there is a more elegant, less bulky way of writing this code? Any other optimization suggestions are very much welcome as well!

Thank you!

Upvotes: 3

Views: 573

Answers (2)

ShadowRanger
ShadowRanger

Reputation: 155323

Use the Python equivalent of C's do/while, which is just a while True: infinite loop that ends with an if condition: break:

while True:
    user_firstname = input("What is your first name? ")
    user_lastname = input("What is your last name?  ")
    confirm_username = input("Is your name " + user_firstname + " " + user_lastname + " ? (y/n) ")[0]
    if confirm_username == "y":
        break
user_name = user_firstname + " " + user_lastname

Note: I removed the str() wrapping around your input calls; input already returns str, so the wrapping is pointless.

Upvotes: 2

wasif
wasif

Reputation: 15470

while True infinite loop, when done BREAK!!

print("""You will need to enter your name so we can make a reservation!
(Use Enter ↵ to confirm)""")

user_firstname = str(input("What is your first name? "))
user_lastname = str(input("What is your last name?  "))

while True:
  confirm_username = str(input("Is your name " + user_firstname + " " + user_lastname + " ? (y/n) "))[0]
  if confirm_username == "y":
    user_name = user_firstname + " " + user_lastname
    break

Upvotes: 1

Related Questions