首页 > 分享 > Python 第五课:语句使用学习

Python 第五课:语句使用学习

1. 条件判断语句

1.1 if使用

判断为Ture时执行,False跳出

if 判断:print() 12

eg. 请输入1,显示Hello,world。

a = int(input('请输入1:')) # 将输入内容转化为整数型 if a == 1: # 判断值是否为1 print('Hello,World!') # True时执行 123

运行结果
在这里插入图片描述
而当判断为False,显示如下图:
在这里插入图片描述
不执行,直接跳出。

补充:input()使用特性

需要输入内容,否则程序不继续执行

eg.

input() print('Hello,World') 12

运行后,无内容显示
在这里插入图片描述
输入任意之后,运行
在这里插入图片描述
2. input()中输入内容,全部为字符串格式,因此为了进行格式转换,可以参考下图

语句效果int()将格式转化为整数型float()将格式转化为浮点型str()将格式转化为字符串list()将格式转化为列表

注意:eval()是去’‘引号操作

1.2 if…else…语句

if 判断:代码块1 # 判断为True时执行1 else:代码块2 # 其余判断结果时执行2 1234

总的来说,必然会有一个执行结果。

eg. 输入性别,男性时擦地,其余做饭。

a = input('请输入性别:') if a == '男':print('擦地') else:print('做饭') 12345

执行结果,判断为True时
在这里插入图片描述
判断结果为False时
在这里插入图片描述

1.3 if…elif…else语句

当遇道多种条件限制是,该语句可以增加条件判断

if 判断:代码块1 elif 判断:代码块2... else:代码块n 123456789

该语句执行顺序为从上到下,目的是找True,一旦执行任意代码块,结束运行。

调试方法

Step1. 鼠标左键点击行数后,空白区域,建立断点
在这里插入图片描述
Step 2. 右键列表中,使用Debug
在这里插入图片描述
Step 3. 查看运行顺序等
在这里插入图片描述

2. 循环控制

2.1 While语句

while 条件判断:代码块1 # 当条件为True时,不断循环执行代码块1 else:代码块2 # 当条件为False时,执行代码块2 1234

三大注意事项:

要有初始值条件判断时对初始值的约束对初始值进行修改

eg. 打印五行‘*****’

a = 0 while a < 5: print('*****') a += 1 else: print('执行结束') 123456

运行结果
在这里插入图片描述

2.2 while语句循环嵌套

while 判断:while 判断: 12

eg. 打印九九乘法表

a = 0 while a < 9: a += 1 b = 0 while b < a: b += 1 print('{}*{}={}'.format(b,a,a*b),end='t') print() 12345678

运行
在这里插入图片描述
总结

外循行,内循列执行上到下循环优先缩进注意

课后练习题~

取1000以内所有水仙花数判断用户输入是否为质数猜拳游戏:
. 出拳阶段:玩家输入,电脑随机
. 判断阶段:玩家胜,电脑胜,平局

# Q1 取1000以内所有水仙花数 a = 0 while a <= 9: b = 0 while b <= 9: c = 0 while c <= 9: num = int('{}{}{}'.format(a,b,c)) if num == a**3 + b**3 +c**3 and a != 0 and int(f'{a}{b}') != 0: print(num) c += 1 b += 1 a += 1 12345678910111213

运行结果
在这里插入图片描述

# Q2 判断用户输入是否为质数 a = eval(input('请输入自然数:')) if type(a) != int: print('不是自然数') elif a > 1: b = 2 while b < a: if a % b == 0: print('不是质数') break b += 1 else: print('是质数') elif 0 <= a <= 1: print('不是质数') else: print('不是自然数')

123456789101112131415161718

# 3. 猜拳游戏: # . 出拳阶段:玩家输入,电脑随机 # . 判断阶段:玩家胜,电脑胜,平局 import random s = '石头' j = '剪刀' b = '布' x = input('请输入'石头、剪刀、布'之一:') y = random.choice(['石头', '剪刀', '布']) print('电脑输入:', y) if x == y: print('平局') elif x == s and y == j: print('玩家胜') elif x == s and y == b: print('电脑胜') elif x == j and y == s: print('电脑胜') elif x == j and y == b: print('玩家胜') elif x == b and y == s: print('玩家胜') elif x == b and y == j: print('电脑胜') else: print('请重新输入!')

123456789101112131415161718192021222324252627

相关知识

Python if语句
8天Python从入门到精通 第四章 Python循环语句 4.8 for循环的嵌套应用
三、Python循环语句
Python机器学习教程——逻辑回归
Python学习手册
使用Python调用mysql
Python流程控制详解
【Python】基础
Python复习题库带答案
老鸟的Python入门教程

网址: Python 第五课:语句使用学习 https://m.huajiangbk.com/newsview1254874.html

所属分类:花卉
上一篇: Java网络编程基础
下一篇: 韩式花束包装技术教学,零基础学习