Python条件判断if、for、while
2024-08-22 13:04:08
if条件判断
if 条件判断: 逻辑操作......
......
判断字符串是否为空
if a.strip(): #表示字符串不为空
pass
判断是否为字典
d = dict(a=1)
if isinstance(d,dict):
print("{0} is a dict".format(d))
例子:
age = input("Please input your age: ")
if age.strip():
if age.strip().isdigit(): # str.isdigit() 检查字符串是否只由数字组成
if int(age) >= 18:
print("你是一个成年人!")
else:
print("你还是一个小屁孩!")
else:
print("你输入的不是数字!")
else:
print("你输入的年龄不符合要求")
if 条件判断:
逻辑操作......
......
elif 条件判断:
逻辑操作......
......
else:
逻辑操作......
例子:
number = input("Please input a number: ")
if int(number) > 0:
print("{0} 是正数".format(number))
elif int(number) < 0:
print("{0} 是负数".format(number))
else:
print("输入的数字是{0}".format(number))
while循环
while 条件判断:
逻辑操作......
......
例子:
a = 100
while a >= 1:
print(a)
a -= 1
while中使用break和continue
while 1: 这个比while True效率高,因为1更接近与机器编码格式
break 满足某个条件时,立即结束当前循环
continue 跳过当前循环的剩余语句,继续进行下一轮循环
例子:
while 1:
age = input("Please input your age: ")
if age.strip():
if age.strip().isdigit():
if int(age) >= 18:
print("你是一个成年人!")
break # 遇到break就会终止,break之后的语句就都不会执行了
else:
print("你还是一个小屁孩!")
break
else:
print("你输入的不是数字!")
else:
print("你输入的年龄不符合要求,请重新输入")
continue # 遇到continue会跳出本次循环,进入下一次循环
九九乘法表
分析:
1 1x1=1
2 1x2=2 2x2=4
3 1x3=3 2x3=6 3x3=9 a x b = a*b
a最小是1,最大为行号
b等于行号 代码如下:
for b in range(1, 10):
for a in range(1, b+1):
print("{0}x{1}={2}".format(a,b,a*b),end=" ") # python3中的空格 end=""
if a == b:
print() # 相当于换行 还有一种一行写法:
print('\n'.join(' '.join("{0}x{1}={2}".format(x, y, x*y) for x in xrange(1, y+1) )for y in xrange(1, 10)))
练习1:
输入一行字符,分别统计出其中的英文字母、空格、数字和其他字符个数。
'''
str.isdigit() 检查字符串是否只由数字组成
str.isalpha() 检查字符串是否只由字母组成
str.isspace() 检查字符串是否只由空格组成
'''
something = input("请随便输入一些内容: ")
while len(something) > 0:
digit, letters, space, other = 0, 0, 0, 0
for i in something:
if i.isdigit():
digit += 1
elif i.isalpha():
letters += 1
elif i.isspace():
space += 1
else:
other += 1
print("数字有:{0}个\n英文字母有:{1}个\n空格有:{2}个\n其他字符有:{3}个".format(digit,letters,space,other))
break
练习2:
输入一个数,求它的阶乘。
num = int(input("请输入一个数字: "))
factorial = 1
if num < 0:
print("负数没有阶乘")
elif num == 0:
print("0 的阶乘为 1")
else:
for i in range(1, num + 1):
factorial = factorial * i
print("{0} 的阶乘为:{1}".format(num, factorial))
最新文章
- 第一章-第十五题(谈谈你对压力的看法,以及怎么和别人合作, 帮助别人,把压力转化为动力,在互相帮助的环境中成长。)--By林培文
- js 求点到直线的距离(由2点确定的直线,求到第三点的距离)
- 【Duke-Image】Week_4 Image restoration
- Atitit.病毒木马的快速扩散机制原理nio&#160;内存映射MappedByteBuffer
- ural 2068. Game of Nuts
- PHP 遍历数组的方法汇总
- NBearV3中文教程总目录
- 【转】随身HiFi 安卓OTG功能在音频上的妙用
- emqtt 试用(二)验证 emq 和 mosquito 的共享订阅
- Python django实现简单的邮件系统发送邮件功能
- VIM 编辑器
- 【MySQL经典案例分析】关于数据行溢出由浅至深的探讨
- 05.Python网络爬虫之三种数据解析方式
- ACM/ICPC 2018亚洲区预选赛北京赛站网络赛D-80 Days--------树状数组
- lr使用linux Generator测试https莫名报 SSL protocol error when attempting to connect with host
- 转载:https://blog.csdn.net/qq_22706515/article/details/52595027
- S5PV210开发系列三_简易Bootloader的实现
- 分享一个不错的squid 配置文件
- Windows中杀死某个端口对应的进程
- exBSGS板子