Python What condition is this code testing for (Python 3.7)

  • Thread starter WWGD
  • Start date

WWGD

Science Advisor
Gold Member
4,138
1,726
Hi, I am taching myself Python 3.7.2.
I think I get how 'While True' statements work,
but I am having trouble making sense of this. The program runs, but I would like to understand well what
is the condition being tested. (From 'Automate the Boring Stuff with Python)
We have a dictionary of people and their birthdates. We want to see if someone's is in a key, i.e., is in the
dictionary. If they are in the dictionary, we acknowledge them. If they are not, we ask for their birthday and then add them into the dictionary. I get that 'While True' statements loop until the condition described in it is not realized/met. *.

*Assume program is well-written, will not loop infinitely.

Python:
BirthdayDictionary = { 'Name1': 'Date 1',....., 'Namen' :'Daten '    }
while True:
    print('Enter a name: (blank to quit)')
    name = input()
    if name == '':
        break
    if name in dictionary:
        print( BirthdayDictionary[name]  + 'Is the Birthday Of ' name  )
    else:
       print('I have no info on' + name)
       print(' What is the birthday of ' + name? )
       bday =input()
       BirthdayDictionary[name]=bday
       print('Database has been updated')
)))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))
Thanks.
 

scottdave

Science Advisor
Homework Helper
Insights Author
Gold Member
1,551
571
In any programming language which has a while loop, the condition is evaluated. If the condition is True, then the rest of the statements within the While loop are executed.
In your example, the condition is always true. This would seem to run forever, except for the break statement.
In Python, a break statement stops the loop execution and continues with the rest of the program.
See examples here - http://www.tutorialspoint.com/python/python_loop_control.htm

What it seems the author of Automate The Boring Stuff is doing, is to check if nothing was entered in the middle, then break the loop. If some value was entered, then continue with the loop. There are some other ways that the loop could be ended, without using break.

One way I've used is something like this:
Python:
testval = 1
while testval > 0:
     #
     # some various code here
     #
     if break_condition:  # break_condition is some boolean variable which is set by the code
          testval = -1
That will keep running the loop, and in my "various code" some calculations will eventually occur which trigger the break condition. Then my testval variable is set to -1. Now when the while tests the condition, the variable is no longer greater than zero, so the condition is False, and the while loop ends.
One that I did was running some iterations, trying to find the root to an equation.
When the value was close enough to zero (less than some small number), then I decided to stop iterating, and break out. I also would have a counter which would break out after a say it had run a thousand iterations (or whatever seemed reasonable).
 
Last edited:

scottdave

Science Advisor
Homework Helper
Insights Author
Gold Member
1,551
571
Note, use the [ CODE = Python ] and the [ / Code ] {but without spaces} to make nice code blocks.

Here is some help for other formatting tags. https://www.physicsforums.com/help/bb-codes
 

scottdave

Science Advisor
Homework Helper
Insights Author
Gold Member
1,551
571
In an online Python course that I recently took, I also saw some while False and if False statements in the instructor's sample solutions.

It appears that they created these to be able to "turn off" code after they were done with the troubleshooting process)
 
24,381
6,023
@WWGD, it really helps to use a code block for code, particularly with Python where indentation is significant. See the "CODE" bb codes here:

https://www.physicsforums.com/help/bb-codes

I have used magic moderator powers to edit your OP to wrap the Python code in a code block.
 

Klystron

Gold Member
292
305
Certainly agree with @scottdave on constructing while loops. A 'while (true)' closed loop may be useful for teaching basic iterative structure but take control of the decision process in actual code. While closed loops may appear benign, they often lead to difficult to trace failure conditions after unexpected errors. Program control is even more important for multi-threaded code and parallel processing. Declare and "own" your control variables. Use break statements as needed but still carefully monitor your conditional control variables.

Notice that the code example in #2 gives you multiple conditional variables for finer iterative control with 'testval' able to hold different values depending on conditions. Say we reserve zero as NULL. We can assign negative values as descriptors while value greater than zero continues iteration.

Consider what happens when calling a function or sequence of functions from within an iterative construction, essentially pausing iteration while the function performs its task. Proper control structure allows monitoring subroutines (functions) and alter or continue iteration upon return. Controlled iteration also allows timing and synchronization in more advanced applications. Reliability need not be sacrificed to simplicity.
 

FactChecker

Science Advisor
Gold Member
2018 Award
4,730
1,614
I have to think that the indentation of the code has been messed up. The execution will only leave the upper 'while loop' when name=''. That leaves the remainder of the code with no name to work with. For a useful program, everything after the 'break' statement should have one more indentation.
EDIT: The code in the OP is not indented correctly.
 
Last edited:
32,373
4,147
@WWGD, it really helps to use a code block for code, particularly with Python where indentation is significant.
This can't be emphasized enough! Python, unlike other languages derived from C, doesn't use braces to enclose blocks; it uses indentation only.

I have to think that the indentation of the code has been messed up.
That's very likely. The original post had no indentation, and @PeterDonis attempted to make sense of the posted code by incorporating what he believed to be the correct indentation.
 
24,381
6,023
I have to think that the indentation of the code has been messed up.
Possibly. The raw text that was entered had indentation in it (which was obscured by the text originally not being inside a code block, so the formatting just removed all of the whitespace); that's the indentation I preserved when I put the code inside a code block. If @WWGD can take a look and let me know if it's messed up, I can edit the post again to fix it.
 

WWGD

Science Advisor
Gold Member
4,138
1,726
Possibly. The raw text that was entered had indentation in it (which was obscured by the text originally not being inside a code block, so the formatting just removed all of the whitespace); that's the indentation I preserved when I put the code inside a code block. If @WWGD can take a look and let me know if it's messed up, I can edit the post again to fix it.
Sure, sorry. Here is the original:

Ok, this comes from :
https://automatetheboringstuff.com/chapter5/ , first code from the top:
)))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))

EDIT: Sorry, I paste the original with the given pasting, but when I submit, it changes the original spacing. How can I avoid that?
Second if from top :
if name in birthdays
should be aligned with first ' if name ' from top.
EDIT 2: I will copy and paste to a file and include it here as attachment.
 
24,381
6,023
I paste the original with the given pasting, but when I submit, it changes the original spacing. How can I avoid that?
I'm not sure if there is a way to guarantee preserving all of the original spacing when cutting and pasting. Some hand cleanup is probably always going to be required. [Edit] Also, you should use a code block when posting code, as otherwise it doesn't matter how the raw text you enter is indented or spaced, the formatting will ignore it.
 
Last edited:
24,381
6,023
I would like to understand well what
is the condition being tested.
The program will keep asking for a name and checking it against the dictionary (and then printing the birthday if it's already in the dictionary, or asking for the birthday to update the dictionary if it's not), until the user enters a blank name (just presses the Enter key at the prompt), at which point the while loop exits and the program ends. The check for when to exit the loop is the statement:

Python:
if name == '':
    break
 

Ibix

Science Advisor
Insights Author
4,702
3,039
The revised code repeatedly looks people up in the hash table an either prints their birthday or prompts the user for the birthday. If a blank name is submitted (an empty string), the code breaks out of the loop.

This kind of
Python:
while something:
    if something_else:
        break
is relatively common in python because the language allows an else clause with a loop. The contents of the clause only get executed if the loop exits normally rather than something breaking out of it. So, for example, a rather silly way of checking an array for a value and printing something if the value is not found is this:
Python:
def isAPlanet(name):
    for planet in ["Mercury","Venus","Earth","Mars","Jupiter","Saturn","Uranus","Neptune"]:
        if name==planet:
            print(name+" is a planet")
            break
    else:
        print(name+" is not a planet")
isAPlanet("Mars") # A planet
isAPlanet("Nibiru") # Not a planet. Or so They say!
The else here is associated with the for, and only executes if a break is not called. If you don't use it, you have to do the rather clumsier
Python:
def isAPlanet(name):
    planetFound=False
    for planet in ["Mercury","Venus","Earth","Mars","Jupiter","Saturn","Uranus","Neptune"]:
        if name==planet:
            planetFound=True
    if planetFound:
        print(name+" is a planet")
    else:
        print(name+" is not a planet")
Obviously you could replace the whole thing with a single if/else statement, so this isn't a great example.
 

Ibix

Science Advisor
Insights Author
4,702
3,039

WWGD

Science Advisor
Gold Member
4,138
1,726
May I ask in this th
The revised code repeatedly looks people up in the hash table an either prints their birthday or prompts the user for the birthday. If a blank name is submitted (an empty string), the code breaks out of the loop.

This kind of
Python:
while something:
    if something_else:
        break
is relatively common in python because the language allows an else clause with a loop. The contents of the clause only get executed if the loop exits normally rather than something breaking out of it. So, for example, a rather silly way of checking an array for a value and printing something if the value is not found is this:
Python:
def isAPlanet(name):
    for planet in ["Mercury","Venus","Earth","Mars","Jupiter","Saturn","Uranus","Neptune"]:
        if name==planet:
            print(name+" is a planet")
            break
    else:
        print(name+" is not a planet")
isAPlanet("Mars") # A planet
isAPlanet("Nibiru") # Not a planet. Or so They say!
The else here is associated with the for, and only executes if a break is not called. If you don't use it, you have to do the rather clumsier
Python:
def isAPlanet(name):
    planetFound=False
    for planet in ["Mercury","Venus","Earth","Mars","Jupiter","Saturn","Uranus","Neptune"]:
        if name==planet:
            planetFound=True
    if planetFound:
        print(name+" is a planet")
    else:
        print(name+" is not a planet")
Obviously you could replace the whole thing with a single if/else statement, so this isn't a great example.
Dont you need to have some input, say, planet = input() at some point?
 

Ibix

Science Advisor
Insights Author
4,702
3,039
Dont you need to have some input, say, planet = input() at some point?
The first code block has hard-coded checks to see if Mars and Nibiru are planets. The second is just the function definition, so wouldn't actually do anything. Typically you'd read some user input or a text file or something and feed it to the function, yes. I just couldn't be bothered typing the code for that.
 

WWGD

Science Advisor
Gold Member
4,138
1,726
Thank you all. I did not know that '' was the blank string. It seems equivalent to explaining something to an autistic person, and I may be somewhat-there myself.
 

scottdave

Science Advisor
Homework Helper
Insights Author
Gold Member
1,551
571
At least on my phone, the python code on that page is centered. It does look better with the ragged edges balancing...
I did notice the centering on my browser, as well. It would definitely cause confusion for people who are fairly new to Python.
It probably is some formatting flag, or maybe some web designer thought it would look pretty centered. ?:)
If you click on the little Try It button, it opens up a code window where you can actually see it formatted properly. You can run the code, as well as modify it, and see how your modifications alter the execution.
When I opened the PDF version of that topic, the code blocks appearance are correct. I left them feedback in their Contact Us page.
 

Want to reply to this thread?

"What condition is this code testing for (Python 3.7)" You must log in or register to reply here.

Physics Forums Values

We Value Quality
• Topics based on mainstream science
• Proper English grammar and spelling
We Value Civility
• Positive and compassionate attitudes
• Patience while debating
We Value Productivity
• Disciplined to remain on-topic
• Recognition of own weaknesses
• Solo and co-op problem solving
Top