While Loops w/ Previously Undefined Variable

Hey everyone. Trying to figure out how to initialize a While Loop if the variable hasn’t been defined before. See below:

age = 1 

while age != 0 :
   age = float(input("Enter your age"))
   if age == 0.0 :
        sys.exit("Process finished with exit code 0")
    dreamJob =input("What is your dream job?: ")
    dreamCar =input("What is your dream car? ")
    jobStatus =input("Are you employed?")
    print("You are", age, "years old, want to be a", dreamJob, "and own a", dreamCar) 

The goal is to have this code run over and over again, repeatedly until the user inputs 0 as the age. I feel like the predefinition of age (age = 1) is an unnecessary line of coding, but not sure how to write it differently. Suggestions?

One decent option is precisely what you have done. If you want to get rid of the arbitrary value 1 you could use age = None instead.

In this case it may be better to call input before the loop and at the end of the loop:

age = float(input("Enter you age "))
while age != 0:
   # do stuff
   age = float(input("Enter you age "))

This has the benefit of getting rid of the superfluous if age == 0 statement.

Since Python 3.8, there’s an additional possibility: an assignment expression using the “walrus operator”:

while (age := float(input("Enter you age "))) != 0:
    # do stuff

I have one additional note about your code:
you wrote

sys.exit("Process finished with exit code 0")

As stated in the documentation for sys.exit, this has the result of printing Process finished with exit code 0 to stderr and exiting with code 1, not 0. To exit with code zero, call sys.exit(0) — or, in this case, just use break to break out of the while loop.

Thanks @tjol. Regarding your first suggestion, won’t that prompt the user for their age twice?

Thanks again,
Ryan

Sorry, I wasn’t very clear. The idea is to replace "# do stuff " with all the other code you want to run in the loop.

But yes, it will prompt the user for their age twice. Or thrice. Or however many times. But the original does this as well :slight_smile:

Apologies. I didn’t realize the second call was at the end of the loop. This makes sense. I’ll try applying some of this tonight and see what I like best!

Ryan

Hi Ryan,

Your markup is broken: you used two backticks to start the code block,
but you need to use three, and they should be on their own line.

Did you make this post on the website? I’m surprised that you didn’t
notice that the formatting was lost.

You suggested that the line age = 1 was an unnecessary line of code.
It is not unnecessary. If you take it out, the while loop cannot test
whether or not age equals zero because age doesn’t exist. So the
simplest solution that works is to do what you already did: initialise
the age variable before the loop.

This works, is efficient, simple and understandable. Any other solution
will just be harder to read and write.

One alternative would be to change the loop to an infinite loop and
forget about testing the age in the while condition. You already have an
exit in the middle of your loop, so that’s not too bad*.

while True:
    age = float(input("Enter your age"))
    if age == 0.0:
        sys.exit("Process finished with exit code 0")
    ...

although I’ll be honest, looking at that sys.exit in the middle of your
while loop makes me come out in hives wink but since I can’t see the
rest of your code I don’t know if that’s justified or not.

I can tell you though that your exit command is severely broken. Your
exit command:

  • prints the message “Process finished with exit code 0”
  • and then exits with exit code 1 (failure)

which makes the message a lie. You can check this for yourself by
running your script and then checking the exit code.

In bash (under Linux), you can check the exit code with:

echo $?

In Windows cmd.exe, I think you can use:

echo %errorlevel%

and in Powershell I think that you can use

$lastExitCode

If you have no code after your while loop, then I recommend that you
replace the sys.exit(...) line with a simple break.

So I’m taking a uni class as intro to python. The current work I’m doing uses a similar bit of code to this (but as I didn’t want to unintentionally cheat, I changed some of it here).

The point of the sys.exit command is to cause the program to abort once “0” is entered as the age. The instructions noted that the program should show “Process finished with exit code 0”.

I’m now realizing that that shouldn’t have been an output process and I misunderstood. Can you help with how I’d get an exit code of 0?

Thanks for your info about the hash marks. I typed this out on my phone and didn’t notice the formatting. It’s been fixed.

Sincere thanks to everyone for their input. I think I’ve got it:


age = 1 

while age != 0 :
   age = float(input("Enter your age"))
   if age == 0 :
     break
   dreamJob =input("What is your dream job?: ")
   dreamCar =input("What is your dream car? ")
   jobStatus =input("Are you employed?")
   print("You are", age, "years old, want to be a", dreamJob, "and own a", dreamCar) 

I don’t have pycharm on my phone but I’m assuming this code now exits with exit code 0 if 0 is entered as age?

Unfortunately, teachers and instructors are not always as clear as they

should be. I cannot tell what the instructor intends about the exit

code, especially since the information is being passed on second hand.

You said:

Which we can interpret at least two ways:

(1) Your program should print the message "Process finished with exit

code 0" and then actually exit with exit code 0.

Or (2) your program should exit with exit code 0 and some other

program will advise the instructor that the process (your program)

exited with code 0.

To exit with code 0, all you need to do is have your program reach the

bottom of the file with no errors. When the interpreter has finished

running your code, and no error has occurred, it will exit with code 0.

You don’t need to do anything.

Another way is for you to explicitly call:

sys.exit(0)

or you can use sys.exit(None) or just call sys.exit with no arguments

at all: sys.exit().

But if you pass a string to sys.exit, it will print the string and

then exit with code 1 which means an error occurred.

Your instinct that the initial age = 1 is less elegant than it might be is good. Also, that the alternative of asking the age in two places is ugly. I might have written:

while (age := float(input("Enter your age: "))) != 0.0:
    dreamJob = ... # i.e. the rest of your loop

# sys.exit() here if you want it

The walrus operator := assigns a value to age but is also an expression that returns the same value (which != 0.0 will test). It is available from Python 3.8 on.

Where a Boolean (True or False) value is expected, zero will be treated as False, and non-zero as True, so you don’t really need != 0.0 except it may be clearer to a human reader.

Bit of a delayed reply here Jeff, but thanks so much! I haven’t learned much about the walrus operator yet, so I’ll have to look into it!

Hi Ryan,

I recommend you skip the walrus operator until you have a better
understanding of the basics.

Have you worked through any Python tutorials or books? I can
strongly recommend the book “Learning Python” by Mark Lutz

https://www.booktopia.com.au/learning-python-mark-lutz/book/9781449355739.html

(P.S. please don’t buy from Amazon.)

Oh, sorry, I forgot to also link to the Python tutorial:

https://docs.python.org/3/tutorial/index.html