Get the App
SLTechnology News&Howtos  ›  Internet Technology  › 

How to analyze while statements in python

Shulou Source: shulou.com Published: 2022-06-01 18:37:15 09月10日 Update

This article shows you how to analyze python while statements, concise and easy to understand, absolutely can make your eyes shine, through the detailed introduction of this article I hope you can gain something.

Zero-base Python Starter-06 while statement

while statement example

Input:

#!/ usr/bin/python

# Filename: while.py

number = 23

running = True

while running:

guess = int(input('Enter an integer : '))

if guess == number:

print('Congratulations, you guessed it. ') running = False

# this causes the while loop to stop

elif guess < number:

print('No, it is a little higher than that. ')

else:

print('No, it is a little lower than that. ')

else:

print('The while loop is over. ')

# Do anything else you want to do here

print('Done')

Output:

Enter an integer : 50

No, it is a little lower than that.

Enter an integer : 22

No, it is a little higher than that.

Enter an integer : 23

Congratulations, you guessed it.

The while loop is over.

Done

Explanation:

Compared to if statements, all code is judged once and executed. While is the state condition. If the state condition is always satisfied, then the statement after while will be executed cyclically.

Until the state condition is not satisfied, jump out of the loop.

In this example, when the first two guesses entered do not match the actual number, running is always changed as a state condition, so the loop execution does not jump out. The third guess, running status changes running=False, while the loop ends and jumps out, continue to execute, output Done

The above is how to analyze the while statement in python. Have you learned any knowledge or skills? If you want to learn more skills or enrich your knowledge reserves, please pay attention to the industry information channel.

Tags: Statements states conditions loops analysis content skills numbers knowledge input output conciseness brevity code basics reality that is articles more examples Apple Docker Huawei Linux macOS MariaDB Microsoft MySQL NVidia OPPO Reno Shulou Technology Microsoft NVidia Huawei MariaDB