Python中的条件判断语句与循环语句用法小结
if语句
>>通用格式
if语句一般形式如下:
if <test1>: <statements1> elif <test2>: <statements2> else: <statements3>
另外需要注意的是,Python中是没有switch/case语句的
while循环
while语句是Python语言中最通用的迭代结构,简而言之,只要顶端测试一直计算到真值,就会重复执行一个语句块。
>>一般格式
while <test>: <statements1> else: <statements2> >>break,continue,pass和循环else
break
跳出最近所在的循环(跳过整个循环语句)。
continue
跳到最近所在循环的开头处(来到循环的首行)。
pass
什么事也不做,只是空占位符语句。
循环else块
只有当前循环正常离开时才会执行(也就是没有碰到break语句)
>>一般循环格式
加入break和continue语句后,while的一般格式变为:
while <test1>: <statements1> if <test2>:break if <test3>:continue else: <statements2> >>pass
pass语句是无运算的占位符,当语法需要语句并且还没有任何实用的语句可写时,就可以使用它。
>>循环else
在while语句中加入else和C/C++中的语法不太一样,这里详细说明一下。else后面的代码只有当循环正常结束时才会执行,如果是用break跳出循环的,这部分代码就不会运行,具体看一个求质数的例子:
x = y // 2 while x > 1: if y % x == 0: print(y,'has factor',x) break x -= 1 else: print(y,'is prime')
再看一个对比的例子,没有使用else的情况:
found=False while x and not found: if (matchx[0]): print('Ni') found=True else: x=x[1:] if not found: print('not found') 使用else后的情况: while x: if (match(x[0])): print('Ni') break else: print('not found')
for循环
for循环在Python中是一个通用的序列迭代器:可以遍历任何有序的序列对象内元素。for语句可以用于字符串、列表、元组、其他内置可迭代对象。
>>一般格式
for <target> in <object>: <statements> else: <statements>
此处的else的作用和while语句中的一样。另外需要注意的是,当Python运行for循环时,会逐个将序列对象中的元素赋值给目标,然后为每个元素执行循环体。
编写循环的技巧
内置range函数:返回一系列连续增加的整数,可作为for中的索引
内置zip函数:返回并行元素的元组的列表,可用于在for中遍历数个数列
>>循环计数器:while和range
range
当range函数只有一个参数时,会返回从零算起的整数列表,但其中不包括该参数的值。如果传进两个参数,那第一个参数是上边界,第二个参数是下边界。如果传进三个参数时,第三个参数表示步进值。
range提供了一种简单的方法,重复特定次数的动作:
for i in range(5): print(i,'Pythons')
相应的C++代码则是:
int i; for(i = 0;i < 5;++i) { std::cout<<i<<"Python"; }
>>并行遍历:zip和map
zip会取得一个或多个序列为参数,然后返回元组的列表,将这些序列中的并排的元素配成对。
L1=[1,2,3,4] L2=[5,6,7,8] list(zip(L1,L2))
上述代码的执行结果是:
[(1,5),(2,6),(3,7),(4,8)]
当参数的长度不同时,zip会以最短序列的长度为准来截断所得到的元组。
使用zip构造字典:
keys=['spam','eggs','totast'] values=[1,2,5] D = dict(zip(keys,values))
>>产生偏移和元素:enumerate
enumerate函数一个比较新的内置函数,它能同时返回元素值和偏移值:
s='spam' for (offset,item) in enumerate(s): print(item,'appears at offset',offset)

Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

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

Hot Article

Hot Tools

Notepad++7.3.1
Easy-to-use and free code editor

SublimeText3 Chinese version
Chinese version, very easy to use

Zend Studio 13.0.1
Powerful PHP integrated development environment

Dreamweaver CS6
Visual web development tools

SublimeText3 Mac version
God-level code editing software (SublimeText3)

Hot Topics

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.

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.

Python is more suitable for beginners, with a smooth learning curve and concise syntax; JavaScript is suitable for front-end development, with a steep learning curve and flexible syntax. 1. Python syntax is intuitive and suitable for data science and back-end development. 2. JavaScript is flexible and widely used in front-end and server-side programming.

PHP originated in 1994 and was developed by RasmusLerdorf. It was originally used to track website visitors and gradually evolved into a server-side scripting language and was widely used in web development. Python was developed by Guidovan Rossum in the late 1980s and was first released in 1991. It emphasizes code readability and simplicity, and is suitable for scientific computing, data analysis and other fields.

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.

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.

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.

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.
