Python基础学习(二)-条件,循环语句
一,条件语句
1,if else
if 判断条件:
执行语句...
else:
执行语句...
实例
flag = False
name = 'luren'
if name == 'python': # 判断变量是否为 python
flag = True # 条件成立时设置标志为真
print 'welcome boss' # 并输出欢迎信息
else:
print name # 条件不成立时输出变量名称
输出:
luren # 输出结果
当判断条件为多个值时,可以使用以下形式:
if 判断条件1:
执行语句1……
elif 判断条件2:
执行语句2……
elif 判断条件3:
执行语句3……
else:
执行语句4……
二,循环语句
1,while 循环--在给定的判断条件为 true 时执行循环体,否则退出循环体。
while 判断条件(condition):
执行语句(statements)……
实例:
count = 0
while (count < 9):
print 'The count is:', count
count = count + 1
print "Good bye!"
输出:
The count is: 0
The count is: 1
The count is: 2
The count is: 3
The count is: 4
The count is: 5
The count is: 6
The count is: 7
The count is: 8
Good bye!
在 python 中,while … else 在循环条件为 false 时执行 else 语句块:
count = 0
while count < 5:
print count, " is less than 5"
count = count + 1
else:
print count, " is not less than 5"
2, for 循环语句- for循环可以遍历任何序列的项目,如一个列表或者一个字符串。
格式:
for iterating_var in sequence:
statements(s)
实例:
for letter in 'Python': # 第一个实例
print ('当前字母 :', letter)
fruits = ['banana', 'apple', 'mango']
for fruit in fruits: # 第二个实例
print ('当前水果 :', fruit)
print "Good bye!"
通过序列索引迭代
fruits = ['banana', 'apple', 'mango']
for index in range(len(fruits)):
print ('当前水果 :', fruits[index])
print "Good bye!"
三,循环控制语句
控制语句 描述
break 语句 在语句块执行过程中终止循环,并且跳出整个循环
continue 语句 在语句块执行过程中终止当前循环,跳出该次循环,执行下一次循环。
pass 语句 pass是空语句,是为了保持程序结构的完整性。
Python基础学习(二)-条件,循环语句
最新推荐文章于 2024-10-02 10:53:34 发布