Python学习新手必看——那几个炫酷的逻辑语句,if、while、for
一、前言
在前面已经学习了基本的Python语句,现在的我们应该可以看懂一些简单的代码了。例如函数的定义、变量的运算、简单的输入和输出、读取文件等简单的语句。接下来我们应该学习一些更高级的东西——逻辑语句。是我们的程序看起来更加连贯和有一定的逻辑可言,同时学习逻辑语句后我们可以写出一些更高级的东西。
二、各个语句功能及其用法
再讲各个逻辑语句之前我们先了解一些“布尔表达式”。我们可以在cmd中运行Python中输入以下命令,试着去理解他们。
有没有看懂其中存在的一些简单的是非逻辑。那么咱们准备进入正题
1、if
先看一段代码
people = 20
cats = 30
dogs = 15
if people < cats:
print("Too many cats! The world is doomed!")
if people > cats:
print("Not many cats! The world is saved!")
if people < dogs:
print("The world is drooled on!")
if people > dogs:
print("The world is dry!")
运行结果如下,
Too many cats! The world is doomed!
The world is dry!
这是将if分成了一层一层的来,在一些相对高级的代码当中不仅会显得我们的代码冗长而且会有一点的逻辑断层。因此我们又引入了else和elif。运行代码如下:
people = 30
cars = 40
if cars > people:
print("We should take the cars!")
elif cars < people:
print("We should not take the cars!")
else:
print("We can't decide.")
运行结果如下:
We should take the cars!
如果多个elif块都是True,Python会如何进行处理?
Python 只会运行它遇到的是True的第一个块,所以只有第一个为True的快会运行。
2、for
the_count = [1, 2, 3, 4, 5]
for number in the_count:
print(f"This is count {number}")
运行如下:
This is count 1
This is count 2
This is count 3
This is count 4
This is count 5
为什么for循环可以使用未定义的变量?
for循环开始时这个变量就被定义了,每次循环碰到它的时候,它都会被重新初始化为当前循环中的元素值。
通过以上代码的运行,我们应该大致知道了for循环的使用条件和方法。
3、while
接下来是一个更难理解的概念——while循环。只要循环语句中的布尔值为True,while循环就会不停的执行它下面的代码块。
i = 0
numbers = []
while i < 3:
print(f"At the top i is {i}")
number.append(i)
i = i + 1
print("Numbers now:", numbers)
print(f"At the bottom i is {i}")
print("The numbers: ")
for num in numbers:
print(num)
运行如下:
At the top i is 0
Numbers now: [0]
At the bottom i is
At the top i is 1
Numbers now: [0, 1]
At the bottom i is 2
At the top i is 2
Numbers now: [0, 1, 2]
At the bottom i is 3
At the top i is 3
The numbers:
0
1
2
for循环和while循环有何不同?
for循环只能对一些东西的集合进行循环,while循环可以对任何对象进行循环。然而,相比起来while循环更难弄对,而一般的任务用for循环更容易一些。