Python零基础入门自学笔记
参考教程【Python教程】《零基础入门学习Python》最新版@B站@鱼C-小甲鱼
本文记录的主要是Python对于分支、循环结构的表达。
import+模块名
e.g. 调用random模块
import random
生成随机数
#获取1到100的随机数
random.randint(1,100)
#alt+p,重复获取随机数
随机数种子,系统时间
#获取系统状态
random.getstate()
if condition:
statement(s)
if anint == 8:
print("对了")
else:
if anint < 8:
print("小了")
else:
print("大了")
score = int(input('输入分数:'))
if 0 <= score < 60:
print('D')
elif 60 <= score < 70:
print('C')
elif 70 <= score < 80:
print('B')
elif 80 <= score < 90:
print('A')
elif score == 100:
print('S')
score = int(input('输入分数:'))
if 0 <= score < 60:
print('D')
elif 60 <= score < 70:
print('C')
elif 70 <= score < 80:
print('B')
elif 80 <= score < 90:
print('A')
elif score == 100:
print('S')
else:
print('请输入0-100的分值')
small = a if a < b else b
if:
else:
if:
else:
只要条件成立,循环体就一直执行
# 无限循环
while 1 < 2:
print("Hello World!")
按Ctrl+C可以中断死循环
# 循环几次
chances = 3
while chances > 0:
print("Hello Python!")
chances = chances - 1
#打印九九乘法表
i = 1
while i <= 9:
j = 1;
while j <= i:
print(j,'*',i,'=',j * i,end=' ')
#end=' '才是空格,' '会换行
j += 1
print() #换行
i += 1
for each in 'Python':
print(each)
for i in range(10): #0-9
for i in range(5,10): #5-9
for i in range(5,10,2): #5 7 9
跳出循环体,执行循环结构后面的语句
只能跳出一个循环体
while 1<2:
print('Hello World!')
break
chances = 3
while chances > 0:
anint = int(input('guess'))
if anint == 8:
print("Yes")
break #跳出循环
else:
print("No")
chances = chances - 1
print('Game Over')
# 查找素数
count = 0
for n in range(2,100):
for x in range(2,n):
if n % x == 0:
break
else:
count += 1
print(n,'是一个素数')
print('共有',count,'个素数')
跳过本次循环,执行下一次循环