Home Backend Development Python Tutorial python--conditional statements and loop statements

python--conditional statements and loop statements

Jul 17, 2017 pm 04:00 PM
python cycle statement

Today we look at conditional statements and loop statements.

Preview:

1. Use a while loop to output 1 2 3 4 5 6 8 9 10

2. Find the sum of all numbers from 1 to 100

3. Output all odd numbers from 1 to 100

4. Output all even numbers within 1-100

5, find the sum of all numbers from 1-2+3-4+5...99

6. User login (three chances to retry)


1. Conditional statement

When the program we write needs to branch, it can also be said that when an event occurs and different processing situations occur under specific circumstances, our conditional statements will be used.

if...else statement:

##Single branch:

1 '''2 if 条件 :3     满足条件后执行的代码4 '''5 6 age = 187 if age == 18 :8     print("我成年了!")
Copy after login

Double branch

 1 ''' 2 if 条件 : 3     满足条件后执行的代码 4 else 5     不满足if时执行 6 ''' 7  8 age = 19 9 if age <= 18 :10     print("我未年!")11 else :12     print("我成年了!")
Copy after login

Multiple branch:

 1 &#39;&#39;&#39; 2 if 条件 : 3     满足条件后执行的代码 4 elif 条件 : 5     不满足上面条件执行 6 elif 条件 : 7     不满足上面条件执行 8 ... 9 else10     不满足上面条件执行11 &#39;&#39;&#39;12 13 age = 1914 if age <= 18 :15     print("我还未年!")16 elif age >= 18 :17     print("我已经成年了!")18 else :19     print("我今年刚成年!")
Copy after login

Indentation:

In other languages, mostly by {} to determine the code block, but there is no {} in python. This is a major feature of python. So how does python determine the code block to be executed? This leads to the concept of forced indentation. The purpose is to let the program know which condition each piece of code depends on. If it is not distinguished by indentation, the program cannot determine the code block to be executed.

Python’s indentation principle:

Top-level code must be written on the top line, that is, if a line of code itself does not depend on Under any conditions, then it must not be indented at all

Codes at the same level must be indented the same

Official recommendations for indentation 4 spaces, of course you can also indent in the way you are used to.

2. Loop statement

while statement:

1 '''2 while 条件 :3     满足条件后执行的代码4 '''5 6 count = 0 
7 while count <= 100 :    #只要count<=100就不断执行下面的代码8     print("loop ", count )9     count +=1    #每执行一次,就把count+1,要不然就变成死循环啦,因为count一直是0
Copy after login

while...else statement:

Unlike other languages, else is generally only paired with if. In Python There is also a while...else statement in it. The function of else after while means that when the while loop is executed normally and is not interrupted by break, the statement after else will be executed.

Infinite loop:

There is a kind of loop called an infinite loop. Once it enters the infinite loop, the program will run You will never be able to quit until the end of time.

while is executed as long as the following condition is always true (that is, the condition result is always true).

For example: In the above code, if there is no code count += 1, the program will enter an infinite loop. Because count = 0, count <= 100 is always true.

Loop termination statement:

If during the loop, for some reason, you do not want to continue the loop , it is necessary to use the break or continue termination statement.

break: Break out of the loop completely and execute the code after the loop.

continue: Jump out of this loop, do not execute the code after continue, and re-enter the loop to judge the condition of the loop.

for loop:

1 for i in range (4) :    # i 为变量 (4)取值范围2     print(">>:",i)    # 0 1 2 33 4 for i in range (1,5) :    # 顾头不顾尾5     print(">>:",i)    # 1 2 3 46 7 for i in range (1,5,2) :    # 步长2 每两个取一个值8     print(">>:",i)    # 1 3
Copy after login

Multiplication table practice:

1 for i in range(1,10) :2     for j in range(1,i+1) :3         print("%s*%s=%s" %(j,i,i*j),end=" ")4     print()
Copy after login

结果:

 

预习解答:

 1 #使用while循环输出1 2 3 4 5 6     8 9 10 2 count = 1 3 while count <= 10 : 4     print(count) 5     count += 1 6     if count == 7 : 7         count += 1 8  9 #count = 010 #while count < 10 :11 #   count += 112 #   if count == 7 :13 #       continue14 #       print(count)
Copy after login
1 #求1-100的所有数的和2 count = 13 sum = 04 while count <= 100 :5     sum += count6     count += 17 print(sum)
Copy after login
1 #输出 1-100 内的所有奇数2 count = 13 while count <= 100 :4     print(count)5     count += 2
Copy after login
1 #输出 1-100 内的所有偶数2 count = 23 while count <= 100 :4     print(count)5     count += 2
Copy after login
 1 #求1-2+3-4+5 ... 99的所有数的和 2 count = 1 3 sum = 0 4 while count < 100 : 5     if count % 2 == 1 : 6         sum += count 7     else : 8         sum -= count 9     count += 110 print(sum)
Copy after login
 1 #用户登陆(三次机会重试) 2 username = "oldbody" 3 password = 10086 4 count = 1 5 print("请输入账户密码共三次尝试机会!") 6 while count <= 3 : 7     name = input("请输入账户:") 8     pswd = int(input("请输入密码:")) 9     if name == username and pswd == password :10         print("输入正确!")11         break12     else :13         print("第",count,"输入错误请重新输入!")14         count += 1
Copy after login

小知识点:

print()自带一个换行符。

如果想取消默认换行符加end(""),详情可以参考九九乘法表的代码。

 

The above is the detailed content of python--conditional statements and loop statements. For more information, please follow other related articles on the PHP Chinese website!

Statement of this Website
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

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 Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

Is the vscode extension malicious? Is the vscode extension malicious? Apr 15, 2025 pm 07:57 PM

VS Code extensions pose malicious risks, such as hiding malicious code, exploiting vulnerabilities, and masturbating as legitimate extensions. Methods to identify malicious extensions include: checking publishers, reading comments, checking code, and installing with caution. Security measures also include: security awareness, good habits, regular updates and antivirus software.

How to run programs in terminal vscode How to run programs in terminal vscode Apr 15, 2025 pm 06:42 PM

In VS Code, you can run the program in the terminal through the following steps: Prepare the code and open the integrated terminal to ensure that the code directory is consistent with the terminal working directory. Select the run command according to the programming language (such as Python's python your_file_name.py) to check whether it runs successfully and resolve errors. Use the debugger to improve debugging efficiency.

Can vs code run in Windows 8 Can vs code run in Windows 8 Apr 15, 2025 pm 07:24 PM

VS Code can run on Windows 8, but the experience may not be great. First make sure the system has been updated to the latest patch, then download the VS Code installation package that matches the system architecture and install it as prompted. After installation, be aware that some extensions may be incompatible with Windows 8 and need to look for alternative extensions or use newer Windows systems in a virtual machine. Install the necessary extensions to check whether they work properly. Although VS Code is feasible on Windows 8, it is recommended to upgrade to a newer Windows system for a better development experience and security.

Can visual studio code be used in python Can visual studio code be used in python Apr 15, 2025 pm 08:18 PM

VS Code can be used to write Python and provides many features that make it an ideal tool for developing Python applications. It allows users to: install Python extensions to get functions such as code completion, syntax highlighting, and debugging. Use the debugger to track code step by step, find and fix errors. Integrate Git for version control. Use code formatting tools to maintain code consistency. Use the Linting tool to spot potential problems ahead of time.

Choosing Between PHP and Python: A Guide Choosing Between PHP and Python: A Guide Apr 18, 2025 am 12:24 AM

PHP is suitable for web development and rapid prototyping, and Python is suitable for data science and machine learning. 1.PHP is used for dynamic web development, with simple syntax and suitable for rapid development. 2. Python has concise syntax, is suitable for multiple fields, and has a strong library ecosystem.

Can vscode be used for mac Can vscode be used for mac Apr 15, 2025 pm 07:36 PM

VS Code is available on Mac. It has powerful extensions, Git integration, terminal and debugger, and also offers a wealth of setup options. However, for particularly large projects or highly professional development, VS Code may have performance or functional limitations.

PHP and Python: Different Paradigms Explained PHP and Python: Different Paradigms Explained Apr 18, 2025 am 12:26 AM

PHP is mainly procedural programming, but also supports object-oriented programming (OOP); Python supports a variety of paradigms, including OOP, functional and procedural programming. PHP is suitable for web development, and Python is suitable for a variety of applications such as data analysis and machine learning.

Can vscode run ipynb Can vscode run ipynb Apr 15, 2025 pm 07:30 PM

The key to running Jupyter Notebook in VS Code is to ensure that the Python environment is properly configured, understand that the code execution order is consistent with the cell order, and be aware of large files or external libraries that may affect performance. The code completion and debugging functions provided by VS Code can greatly improve coding efficiency and reduce errors.

See all articles