python中的循环结构等相关知识

分支结构

1、单分支:一般用于只会发生一种情况的场景,if

#90以上优秀
score=95
if score>90:
    print("优秀")

2、双分支:一般用于会发生两种情况的场景,if,else

#90以上优秀,89到70良好
score=80
if score>90:
    print("优秀")
else:print("良好")
##
score=82
print("优秀")if score>90 else print("良好")    ## 结果一   条件    结果二

3、多分支:一般用于会发生多种情况,if,elif,elif, else

#90以上优秀,89到70良好,69到60分及格,60分以下不及格
s=eval(input("请输入一个分数"))
if s>90:
    print('优秀')
elif s>70:
    print("良好")
elif s>60:
    print("合格")
else:print("不及格")

逻辑运算符

#+-*/
and   #两者必须都满足
or    #两者只要满足一个
not   #非

异常处理

x = 10
try:
    y = int(input('数字:'))  # 10
    y += 10 # y = y + 10
except Exception as e:
    print(f'error: 33[1;35m {e} 33[0m!')  ##设置报错时的颜色
finally:                             # 无论包不报错,都会执行finally下面的代码
    print(1)
print(x + 10)

**********************
x=15
try:
    y=int(input("请输入一个数"))
    y+=x
except Exception as e:
    pass
finally:
    print("结果在下方:")
print(y)

循环结构

1、for循环

for i in range(1,3):   ##只循环1,2的
    print(i,end='')     ##1,2
for i in range(1,10,2):  ##只循环1,9且步长为2
    print(i,end='')   ##1,3,5,7,9

2、while循环

factory = 0.01
base =0
while base < pow(1.01,365):
    factory += 0.001
    base = 1  # 37.78343433288728
    for i in range(365):
        if i % 7 == 0:
            base *= (1 - 0.01)
        elif i % 7 == 6:
            base *= (1 - 0.01)
        else:
            base *= (1 + factory)
print(factory)

3、break和contine的使用

  • break跳出并结束当前整个循环,执行循环后的语句
  • continue结束当次循环,继续执行后续次数循环
  • break和continue可以与for和while循环搭配使用
for c in "PYTHON":
    if c == 'T':
        continue
    print(c, end=',') ##P Y H O N
    
    for c in "PYTHON":
    if c == 'T':
        break
    print(c, end=',')##P Y
random模块
import time
time_ = time.time()
print(str(time_).split('.')[-1][-1])    ##随机数的产生

random.seed(10)
print(random.random())  # 取(0,1)之间的小数

# 如果不自定义种子,则种子按照当前的时间来
print(random.random())  # 取(0,1)之间的小数

lt = [1,2,3,4]
random.shuffle(lt)
print(lt)       ##数组中的数随机排序

lt = [1,2,3,4]
random.shuffle(lt
print(random.choice([1,2,3,4]))  ##在数组中随机选择一个数

案例学习

圆周率的计算
# 蒙特卡洛方法求Π
import random
count = 0
for i in range(100000):
    x, y = random.random(), random.random()
    dist = pow(x ** 2 + y ** 2, 0.5)
    if dist < 1:
        count += 1
print(count / 100000 * 4)
##公式计算
pi = 0
k = 0
while True:

    pi +=  (1/(16**k))* 
          (4/(8*k+1) - 2/(8*k+4) - 1/(8*k+5) - 1/(8*k+6))
    print(pi)
    k += 1

既然选择了远方,只能风雨兼程
原文地址:https://www.cnblogs.com/lzss/p/11203203.html