if condition:
do something
elif other_condition:
do something
Python条件语句是通过一条或多条语句的执行结果(True或者False)来决定执行的代码块。
Python程序语言指定任何非0和非空(null)值为true,0 或者 null为false。
Python 编程中 if 语句用于控制程序的执行,基本形式为:
if判断条件:执行语句……else:执行语句……
其中"判断条件"成立时(非零),则执行后面的语句,而执行内容可以多行,以缩进来区分表示同一范围。
else 为可选语句,当需要在条件不成立时执行内容则可以执行相关语句,具体例子如下:
实例
#!/usr/bin/python# -*- coding: UTF-8 -*-# 例1:if 基本用法flag = Falsename = 'luren'ifname == 'python': # 判断变量否为'python'flag = True# 条件成立时设置标志为真print'welcome boss'# 并输出欢迎信息else: printname# 条件不成立时输出变量名称
输出结果为:
luren# 输出结果
if 语句的判断条件可以用>(大于)、<(小于)、==(等于)、>=(大于等于)、<=(小于等于)来表示其关系。
当判断条件为多个值时,可以使用以下形式:
if判断条件1:执行语句1……elif 判断条件2:执行语句2……elif 判断条件3:执行语句3……else:执行语句4……
#if statement example
number = 59
guess = int(input('Enter an integer : '))
if guess == number:
# New block starts here
print('Bingo! you guessed it right.')
print('(but you do not win any prizes!)')
# New block ends here
elif guess < number:
# Another block
print('No, the number is higher than that')
# You can do whatever you want in a block ...
else:
print('No, the number is a lower than that')
# you must have guessed > number to reach here
print('Done')
# This last statement is always executed,
# after the if statement is executed.

Python for循环可以遍历任何序列的项目,如一个列表或者一个字符串。
语法:
for循环的语法格式如下:
for iterating_var in sequence:statements(s)
流程图:

python_for_loop
实例:
实例
#!/usr/bin/python# -*- coding: UTF-8 -*-forletterin'Python': # 第一个实例print'当前字母 :', letterfruits = ['banana', 'apple', 'mango']forfruitinfruits: # 第二个实例print'当前水果 :', fruitprint"Good bye!"
尝试一下 »
以上实例输出结果:
当前字母: P 当前字母: y 当前字母: t 当前字母: h 当前字母: o 当前字母: n 当前水果: banana 当前水果: apple 当前水果: mango Good bye!
Code:
#the for loop example
for i in range(1, 10):
print(i)
else:
print('The for loop is over')
a_list = [1, 3, 5, 7, 9]
for i in a_list:
print(i)
a_tuple = (1, 3, 5, 7, 9)
for i in a_tuple:
print(i)
a_dict = {'Tom':'111', 'Jerry':'222', 'Cathy':'333'}
for ele in a_dict:
print(ele)
print(a_dict[ele])
for key, elem in a_dict.items():
print(key, elem)
-->
1
2
3
4
5
6
7
8
9
The for loop is over
1
3
5
7
9
1
3
5
7
9
Tom
111
Jerry
222
Cathy
333
Tom 111
Jerry 222
Cathy 333