What condition is this code testing for (Python 3.7)

In summary: Functions may block the calling thread or process, causing the entire loop to fail if the function takes a long time or if there is contention for resources. Functions and sequences of functions can be called from within a while loop using the with keyword.In summary, the author is providing a tutorial on how to use the Python language to automate common tasks. They are discussing how while loops work and how to use break statements to control the execution of the loop. They are also providing an example of how to use functions to pause the execution of the loop.
  • #1
WWGD
Science Advisor
Gold Member
6,934
10,341
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.
 
Technology news on Phys.org
  • #2
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:
  • Like
Likes Klystron and WWGD
  • #3
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
 
  • Like
Likes WWGD
  • #4
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)
 
  • Like
Likes WWGD
  • #5
@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.
 
  • Like
Likes WWGD, Klystron and scottdave
  • #6
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.
 
  • Like
Likes WWGD
  • #7
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:
  • Like
Likes WWGD
  • #8
PeterDonis said:
@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.

FactChecker said:
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.
 
  • Like
Likes scottdave and WWGD
  • #9
FactChecker said:
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.
 
  • #10
PeterDonis said:
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.
 
  • #11
WWGD said:
Here is the original

I've edited the OP of this thread to reflect the proper indentation, per this reference.
 
  • #12
WWGD said:
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:
  • #13
WWGD said:
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
 
  • Like
Likes WWGD
  • #14
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.
 
  • Like
Likes WWGD
  • #16
May I ask in this th
Ibix said:
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?
 
  • #17
WWGD said:
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.
 
  • Like
Likes WWGD
  • #18
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.
 
  • Like
Likes twild19
  • #19
Ibix said:
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.
 

1. What is the purpose of testing code in Python 3.7?

The purpose of testing code in Python 3.7 is to ensure that the code is functioning correctly and producing the desired results. This helps to catch any errors or bugs early on in the development process, making it easier to fix them before the code is deployed.

2. How do I know which condition the code is testing for in Python 3.7?

To determine the condition being tested for in Python 3.7, you can read the code or comments carefully to understand the purpose of each line. Additionally, you can use debugging tools or print statements to track the flow of the code and see which condition is being evaluated at each step.

3. What types of conditions can be tested for in Python 3.7?

Python 3.7 allows for testing a wide range of conditions, including logical expressions, comparison operations, and membership tests. It also supports testing for exceptions and errors, as well as testing the behavior of functions and objects.

4. Can I write my own custom conditions to test in Python 3.7?

Yes, you can write your own custom conditions to test in Python 3.7. This can be done by using conditional statements, such as if/else statements, or by creating custom functions that check for specific conditions. You can also use external libraries or frameworks to define and test custom conditions.

5. What are the benefits of testing for conditions in Python 3.7?

Testing for conditions in Python 3.7 has several benefits, including catching errors and bugs early on, improving code quality and reliability, and reducing the time and effort required for debugging. It also helps to ensure that the code meets the desired specifications and produces the expected results.

Similar threads

  • Programming and Computer Science
Replies
10
Views
997
  • Programming and Computer Science
Replies
4
Views
951
Replies
5
Views
829
  • Programming and Computer Science
Replies
22
Views
631
  • Programming and Computer Science
Replies
4
Views
3K
Replies
3
Views
718
  • Programming and Computer Science
Replies
2
Views
741
  • Programming and Computer Science
Replies
3
Views
677
  • Programming and Computer Science
Replies
4
Views
826
  • Programming and Computer Science
Replies
34
Views
2K
Back
Top