1.条件判断语句
Python中条件选择语句的关键字为:if 、elif 、else这三个。其基本形式如下:
1
2
3
4
5
6
7
8
9
|
age_of_cc = 27
age = int ( input ( "guessage:" ))
if age = = age_of_cc:
print ( "Yes,you got it!" )
elif age > age_of_cc:
print ( "猜大啦!" )
else :
print ( "猜小啦!" )
|
if语句执行的特点是从上往下判断;
其中elif和else语句块是可选的。对于if和elif只有判断为True时,该分支语句才执行,只有当if和所有的elif的判断都为False时,才执行else分支。注意Python中条件选择语句中判断后面有个冒号。
AA = input(">>>:") # 输入 aa 或 bb
if (AA == "aa","bb"): # 满足小括号中任意一个条件都会执行
print('输出:',AA) 或 AA = input(">>>:") # 输入 aa 或 bb
if AA in ("aa","bb"): # 满足小括号中任意一个条件都会执行
print('输出:',AA)
2.循环语句
2.1 while循环
用法:
1
2
|
while 条件:
xxxxxx
|
while会不停地循环执行隶属于它的语句,直到条件为假(False)
2.1.1 break跳过循环
代码示例:
age_of_cc = 27
count =0 while count < 3:
age = int(input("guessage:"))
if age == age_of_cc:
print("Yes,you got it!")
break
elif age > age_of_cc:
print("猜大啦!")
else:
print("猜小啦!")
count += 1
else:
if count == 3:
print("错误太多次啦!")
2.1.2 continue跳过该次循环
代码示例:
1
2
3
4
5
6
|
i = 1
while i < 10 :
i + = 1
if i % 2 > 0 : # 非双数时跳过输出
continue
print (i) # 输出双数2、4、6、8、10
|
2.2 for循环
for循环需要预先设定好循环的次数(n),然后执行隶属于for的语句n次。
代码示例:
1
2
|
for i in range ( 10 ):
print (i) #输出0 1 2 3 4 5 6 7 8 9
|
while循环判断语句代码示例:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
|
age_of_cc = 27
count = 0
while count < 3 :
age = int ( input ( "guessage:" ))
if age = = age_of_cc:
print ( "Yes,you got it!" )
break
elif age > age_of_cc:
print ( "猜大啦!" )
else :
print ( "猜小啦!" )
count + = 1
else :
if count = = 3 :
print ( "错误太多次啦!" )
|
for条件判断代码示例:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
|
age_of_cc = 27
count = 0
for i in range ( 3 ):
age = int ( input ( "guessage:" ))
if age = = age_of_cc:
print ( "Yes,you got it!" )
break
elif age > age_of_cc:
print ( "猜大啦!" )
else :
print ( "猜小啦!" )
count + = 1
else :
if count = = 3 :
print ( "错误太多次啦!" )
|
3.1 input
input是输入函数,用户可以输入字符串保存到变量中
代码示例:
1
|
name = input ( "Please input your name" )
|
3.2 print
用print()在括号中加上字符串,就可以向屏幕上输出指定的文字
代码示例:
1
|
print ( "Hello!" )
|
3.3 类型转换
通过上文可以看出,input输入的在python中都会被认为是字符串(见下图),所以我们需要对input的内容进行类型转换:
转换成int示例:
1
|
age = int ( input ( "age is:" ))
|
转换回字符串:str()