python学习笔记(三)条件判断和循环
1.条件判断语句
Python中条件选择语句的关键字为:if 、elif 、else这三个。其基本形式如下:
| 1 2 3 4 5 6 7 8 9 | age_of_cc =27age =int(input("guessage:"))ifage ==age_of_cc:    print("Yes,you got it!")elifage > age_of_cc:    print("猜大啦!")else:    print("猜小啦!") | 
if语句执行的特点是从上往下判断;
其中elif和else语句块是可选的。对于if和elif只有判断为True时,该分支语句才执行,只有当if和所有的elif的判断都为False时,才执行else分支。注意Python中条件选择语句中判断后面有个冒号。
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 =1whilei < 10:    i +=1    ifi%2> 0:     # 非双数时跳过输出        continue    print(i)      # 输出双数2、4、6、8、10 | 
2.2 for循环
for循环需要预先设定好循环的次数(n),然后执行隶属于for的语句n次。
代码示例:
| 1 2 | fori inrange(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 =27count =0whilecount < 3:    age =int(input("guessage:"))    ifage ==age_of_cc:        print("Yes,you got it!")        break    elifage > age_of_cc:        print("猜大啦!")    else:        print("猜小啦!")    count +=1else:    ifcount ==3:        print("错误太多次啦!") | 
for条件判断代码示例:
| 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 | age_of_cc =27count =0fori inrange(3):    age =int(input("guessage:"))    ifage ==age_of_cc:        print("Yes,you got it!")        break    elifage > age_of_cc:        print("猜大啦!")    else:        print("猜小啦!")    count +=1else:    ifcount ==3:        print("错误太多次啦!") | 
3 其他
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()
 
                    
                     
                    
                 
                    
                

 
                
            
         
         浙公网安备 33010602011771号
浙公网安备 33010602011771号