条件控制语句
一. if条件判断语句
条件判断语句(if语句)
执行的流程: 。 if语句在执行时,会先对条件表达式进行求值判断, 。 如果为True,则执行if后的语句 。 如果为False,则不执行
num= 30
if num> 20 and num< 40 :
print ( num)
代码块(代码块)中保存着一组代码,同一个代码块中的代码,要么都执行要么都不执行 代码块以缩进开始,直到代码恢复到之前的缩进级别时结束 代码块就是一种为代码分组的机制
input() 函数
该函数用来获取用户的输入 input()调用后,程序会立即暂停,等待用户输入 用户输入完内容以后,点击回车程序才会继续向下执行 用户输入完成以后,其所输入的的内容会以返回值得形式返回
a = input ( '请输入六位数密码:' )
print ( type ( a) )
if-else语句
语法: if 条件表达式 : 代码块 else : 代码块 执行流程: 。 if-else语句在执行时,先对if后的条件表达式进行求值判断 。 如果为True,则执行if后的代码块 。 如果为False,则执行else后的代码块)
a = int ( input ( '请输入小于12的整数:' ) )
if a < 12 :
print (a)
else :
print ( '输入有误,请重新输入!' )
a, b = 20 , 30
c = a if a > b else b
print ( c)
a, b, c= 20 , 30 , 60
max1 = ( a if a > b else b) if ( a if a > b else b) > c else c
print ( max1)
if-elif-else 语句
语法: if 条件表达式 : 代码块 elif 条件表达式 : 代码块 elif 条件表达式 : 代码块 … else : 代码块
value = int (input ('请输入您的月薪:' ))
if value >= 30000 :
print ( '有钱任性' )
elif value >= 20000 :
print ( '有钱真好' )
elif value >= 10000 :
print ( '哥也月薪上万了' )
elif value >= 5000 :
print ( '工资还说的过去' )
elif value >= 2000 :
print ( '能养活自己了' )
else :
print ( '建议您每个月备一箱泡面!' )
执行流程: 。 if-elif-else语句在执行时,会自上向下依次对条件表达式进行求值判断, 。 如果表达式的结果为True,则执行当前代码块,然后语句结束 。 如果表达式的结果为False,则继续向下判断,直到找到True为止 。 如果所有的表达式都是False,则执行else后的代码块 总结 : if-elif-else中总会有一个代码块会执行,elif提供了更多的条件判断,一条条执行,只要找到其中一条符合条件的其余全部pass掉。
二. 循环控制
while - else语句
循环语句可以使指定的代码块重复指定的次数.循环语句分成两种,while循环 和 for循环 语法: while 条件表达式 : 代码块 else: 代码块 while 循环三条件:设定初始值、条件判断、初始值自增长
i = 0
j = 0
while j < 50 :
j += 1
i += j
print ( i)
break和continue
break 可以用来立即退出循环语句,包括else语句 continue 用来跳过当次循环
三.循环嵌套
循环嵌套
Python 语言允许在一个循环体里面嵌入另一个循环。 while 循环嵌套
while 表达式:
while 表达式:
代码块
代码块
i = 0
while i< 9 :
i += 1
j= 0
while j< i:
j += 1
print ( '{} * {} = {}' . format ( j, i, i* j) , end= '\t' )
print ( )
四.作业 :
i = 99
while i < 999 :
i += 1
a = i // 100
b = ( i - a * 100 ) // 10
c = i - a * 100 - b * 10
if i == a** 3 + b** 3 + c** 3 :
print ( i, end= ' ' )
1. user_input = int ( input ( '请输入任意一个数' ) )
2 .
3 . if user_input <= 1 :
4 . print ( '{}不是质数哦。' . format ( user_input) )
5 .
6 . elif user_input == 2 :
5 . print ( '2是质数哦。' )
8 .
9. i = 2
10 . while i < user_input:
6 . if user_input % i == 0 :
7 . print ( '%d不是质数哦。' % user_input)
8 . break
9 . i += 1
10 .
16 . else :
11 . print ( f'{user_input}是质数哦。' )
猜拳游戏: • 出拳 玩家:手动输入 电脑:随机输入 • 判断输赢: 玩家获胜 电脑获胜 平局
import random
choices = [ '石头' , '剪刀' , '布' ]
win = [
[ '石头' , '剪刀' ] ,
[ '剪刀' , '布' ] ,
[ '布' , '石头' ]
]
your_choice = input ( '请输入石头、剪刀或布' )
if your_choice in choices:
computer_choice = random. choice( choices)
if [ your_choice, computer_choice] in win:
print ( '你出了%s,电脑出了%s,你赢了' % ( your_choice, computer_choice) )
elif your_choice == computer_choice:
print ( '你出了%s,电脑出了%s,平局' % ( your_choice, computer_choice) )
else :
print ( '你出了%s,电脑出了%s,你输了' % ( your_choice, computer_choice) )
else :
print ( '输入有误' )