Python 官方文档:入门教程 => 点击学习
1.if/while/forpython缩进:main: pass c main(param) {} java main(param){}if判断:if 判断条件: 执行语句 elif 判断条件: 执行语句 e
1.if/while/for
python缩进:
main:
pass
c main(param) {}
java main(param){}
if判断:
if 判断条件:
执行语句
elif 判断条件:
执行语句
else:
执行语句
While循环:
whle 判断条件:
执行语句
break 跳出循环
continue 跳出本次循环,进入下一次循环
for 循环:
for item in sequence:
执行语句
for i,j in enumerate(list1):
print(i,j)
切片:
l = ['a','b','c','d','e']
print(l[0:5]) # 0 << x < 5
for x,y in enumerate(l):
print(x,y)
结果:
['a', 'b', 'c', 'd', 'e']
0 a
1 b
2 c
3 d
4 e
print(l[:]) 取到所有
2.Python实例
做题的思路和思想最重要:
例1:
ABCD*9=DCBA A=?B=? C=? D=? 答案: A=1,B=0,C=8,D=9 1089*9=9801
#!/usr/bin/env python
# -*- coding:utf-8 -*-
# @Time: 2018-01-23 16:31
# @Author: Feng Xiaoqing
# @File: if-while-for.py
for a in range(1,10):
for b in range(0,10):
for c in range(0,10):
for d in range(0,10):
Start = a * 1000 + b * 100 + c * 10 + d
End = d * 1000 + c * 100 + b * 10 + a
if Start * 9 == End :
print ('{0} * 9 = {1}'.fORMat(Start,End))
答案:
1089 * 9 = 9801
例2:
求n的阶乘0! + 1! + 2! + 3! ...+ n!
#!/usr/bin/env python
# -*- coding:utf-8 -*-
# @Time: 2018-01-23 15:31
# @Author: Feng Xiaoqing
# @File: if-while-for.py
def one(n):
total = 1
if n == 0:
total = 1
else:
for i in range(1,int(n)+1):
total *= i
return total
while True:
result = 0
n = input("please input a number:")
if not n.isdigit() :
print(" the number is error!")
break
for i in range(0,int(n)+1):
result += one(i)
print("0! + 1! + 2! + 3! ...+ n! = {0}".format(result))
--结束END--
本文标题: Python中的if、while、for
本文链接: https://lsjlt.com/news/184572.html(转载时请注明来源链接)
有问题或投稿请发送至: 邮箱/279061341@qq.com QQ/279061341
2024-03-01
2024-03-01
2024-03-01
2024-02-29
2024-02-29
2024-02-29
2024-02-29
2024-02-29
2024-02-29
2024-02-29
回答
回答
回答
回答
回答
回答
回答
回答
回答
回答
0