search
HomeBackend DevelopmentPython TutorialA brief introduction to the If statement and While statement in Python (with examples)

This article brings you a brief introduction to the If statement and While statement in Python (with examples). It has certain reference value. Friends in need can refer to it. I hope it will be helpful to you.

If statement

is used to check the condition: If the condition is true (True), it will run This block of statements (called if-block or if block)

    will run another block of statements (called else-block or else block), in which the else clause is optional

Multi-branch if statements: 1, elif and else also need to have a colon at the end of their logical lines, followed by their corresponding statements Block

##       2. You can set another if statement (nested if statement) within an if statement of the if block

数字猜测:
       
number = 50
guess_number = input("请输入猜测的数字:")
# input() 函数将以字符串的形式返回我们所输入的内容

if int(guess_number) == number :
         #if块从此开始
         print("恭喜你!猜对了!")
elif int(guess_number) < number :
         # 另一代码块开始
         print("很抱歉,你猜的小了!")
else :
         print("很抱歉,你猜的大了!")

While Statement

The While statement allows you to repeatedly execute a block of statements while a condition is true. The while statement is a type of looping statement. The while statement can also have an else clause as an optional option.

Set the variable running to True before the while loop begins. When the program starts, it first checks whether the variable running is True, and then executes the corresponding while block. After this code block is executed, the condition will be rechecked. If the variable is still True , the program will execute the while block again, otherwise it will continue executing the optional else block and move to the next statement.

The Else code block begins executing when the while loop's condition becomes False, possibly even when the condition is checked for the first time. If there is an else block within a while loop, it will always be tried unless the loop is interrupted by a break statement.

number = 50
max = 100
# input( ) 函数将以字符串的形式返回我们所输入的内容
running = True
while running :
        guess_number = input("请输入猜测的数字:")
        if int(guess_number) == number :
        # if 块从此开始
                print("恭喜你!猜对了!")
                #这将导致 while 循环终止
                running = False
        elif int(guess_number) < number :
        # 另一代码块
                print("很抱歉,你猜小了!")
                print("这个数字是在" + str(guess_number) + "和" + str(max) + "之间")
                min = guess_number
                
        else :
                print("很抱歉,你猜大了!")
                print("这个数字是在" + str(min) + "和" + str(guess_number) + "之间")
                max = guess_number
                
print(&#39;游戏结束!&#39;)

The above is the detailed content of A brief introduction to the If statement and While statement in Python (with examples). For more information, please follow other related articles on the PHP Chinese website!

Statement
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Python: compiler or Interpreter?Python: compiler or Interpreter?May 13, 2025 am 12:10 AM

Python is an interpreted language, but it also includes the compilation process. 1) Python code is first compiled into bytecode. 2) Bytecode is interpreted and executed by Python virtual machine. 3) This hybrid mechanism makes Python both flexible and efficient, but not as fast as a fully compiled language.

Python For Loop vs While Loop: When to Use Which?Python For Loop vs While Loop: When to Use Which?May 13, 2025 am 12:07 AM

Useaforloopwheniteratingoverasequenceorforaspecificnumberoftimes;useawhileloopwhencontinuinguntilaconditionismet.Forloopsareidealforknownsequences,whilewhileloopssuitsituationswithundeterminediterations.

Python loops: The most common errorsPython loops: The most common errorsMay 13, 2025 am 12:07 AM

Pythonloopscanleadtoerrorslikeinfiniteloops,modifyinglistsduringiteration,off-by-oneerrors,zero-indexingissues,andnestedloopinefficiencies.Toavoidthese:1)Use'i

For loop and while loop in Python: What are the advantages of each?For loop and while loop in Python: What are the advantages of each?May 13, 2025 am 12:01 AM

Forloopsareadvantageousforknowniterationsandsequences,offeringsimplicityandreadability;whileloopsareidealfordynamicconditionsandunknowniterations,providingcontrolovertermination.1)Forloopsareperfectforiteratingoverlists,tuples,orstrings,directlyacces

Python: A Deep Dive into Compilation and InterpretationPython: A Deep Dive into Compilation and InterpretationMay 12, 2025 am 12:14 AM

Pythonusesahybridmodelofcompilationandinterpretation:1)ThePythoninterpretercompilessourcecodeintoplatform-independentbytecode.2)ThePythonVirtualMachine(PVM)thenexecutesthisbytecode,balancingeaseofusewithperformance.

Is Python an interpreted or a compiled language, and why does it matter?Is Python an interpreted or a compiled language, and why does it matter?May 12, 2025 am 12:09 AM

Pythonisbothinterpretedandcompiled.1)It'scompiledtobytecodeforportabilityacrossplatforms.2)Thebytecodeistheninterpreted,allowingfordynamictypingandrapiddevelopment,thoughitmaybeslowerthanfullycompiledlanguages.

For Loop vs While Loop in Python: Key Differences ExplainedFor Loop vs While Loop in Python: Key Differences ExplainedMay 12, 2025 am 12:08 AM

Forloopsareidealwhenyouknowthenumberofiterationsinadvance,whilewhileloopsarebetterforsituationswhereyouneedtoloopuntilaconditionismet.Forloopsaremoreefficientandreadable,suitableforiteratingoversequences,whereaswhileloopsoffermorecontrolandareusefulf

For and While loops: a practical guideFor and While loops: a practical guideMay 12, 2025 am 12:07 AM

Forloopsareusedwhenthenumberofiterationsisknowninadvance,whilewhileloopsareusedwhentheiterationsdependonacondition.1)Forloopsareidealforiteratingoversequenceslikelistsorarrays.2)Whileloopsaresuitableforscenarioswheretheloopcontinuesuntilaspecificcond

See all articles

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Article

Hot Tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

VSCode Windows 64-bit Download

VSCode Windows 64-bit Download

A free and powerful IDE editor launched by Microsoft

WebStorm Mac version

WebStorm Mac version

Useful JavaScript development tools

PhpStorm Mac version

PhpStorm Mac version

The latest (2018.2.1) professional PHP integrated development tool

EditPlus Chinese cracked version

EditPlus Chinese cracked version

Small size, syntax highlighting, does not support code prompt function