python程序控制

coding

#!/usr/bin/env python3

# -*- coding: UTF-8 -*-

guess = eval(input())

if guess == 99:

print("yes")

====================== RESTART: C:\Python3.7.0\test.py ======================

1

>>>

====================== RESTART: C:\Python3.7.0\test.py ======================

99

yes

#!/usr/bin/env python3

# -*- coding: UTF-8 -*-

guess = eval(input())

print("猜{}了".format("对" if guess == 99 else "错"))

====================== RESTART: C:\Python3.7.0\test.py ======================

1

猜错了

>>>

====================== RESTART: C:\Python3.7.0\test.py ======================

99

猜对了

  • 用于条件组合的三个保留字
x and y逻辑与

x or y逻辑或

not x逻辑非

  • 异常处理
#!/usr/bin/env python3

# -*- coding: UTF-8 -*-

try:

num = eval(input("please input int num:"))

print(num ** 2)

except:

print("not int")

====================== RESTART: C:\Python3.7.0\test.py ======================

please input int num:

not int

>>>

====================== RESTART: C:\Python3.7.0\test.py ======================

please input int num:11

121

#!/usr/bin/env python3

# -*- coding: UTF-8 -*-

try:

num = eval(input("please input int num:"))

print(num ** 2)

except NameError:

print("not int")

====================== RESTART: C:\Python3.7.0\test.py ======================

please input int num:

Traceback (most recent call last):

File "C:\Python3.7.0\test.py", line 5, in <module>

num = eval(input("please input int num:"))

File "<string>", line 0

^

SyntaxError: unexpected EOF while parsing

>>>

====================== RESTART: C:\Python3.7.0\test.py ======================

please input int num:a

not int

try:

<语句块1>

except:

<语句块2>

else:

<语句块3>

finally:

<语句块4>

- finally对应语句4一定执行

- else对应语句块3在不发生异常时执行

  • 身体质量指数BMI
BMI:Body Mass Index

BMI = 体重(kg) / 身高^2(m^2)

分类 国际BMI值 国内BMI值

偏瘦 <18.5 <18.5

正常 18.5~25 18.5~24

偏胖 25~30 24~28

肥胖 >=30 >=28

#!/usr/bin/env python3

# -*- coding: UTF-8 -*-

height,weight = eval(input("please input you height(m) and weight(kg)[,]:"))

bmi = weight /pow(height,2)

print("BMI is:{:.2f}".format(bmi))

who,nat = "",""

if bmi < 18.5:

who,nat = "偏瘦","偏瘦"

elif 18.5 <= bmi < 24:

who,nat = "正常","正常"

elif 24 <= bmi < 25:

who,nat = "正常","偏胖"

elif 25 <= bmi <28:

who,nat = "偏胖","偏胖"

elif 28 <= bmi < 30:

who,nat = "偏胖","肥胖"

else:

who,nat = "肥胖","肥胖"

print("BMI is:who'{0}',nat'{1}'".format(who,nat))

====================== RESTART: C:\Python3.7.0\test.py ======================

please input you height(m) and weight(kg)[,]:1.74,74

BMI is:24.44

BMI is:who'正常',nat'偏胖'

  • 遍历循环
for i in range(M,N,K):

<语句块>

range(起始值,终止值,步长)

因为程序从0开始,终止值实际是-1

字符串遍历

>>> for i in "Python":

print(i,end=",")

P,y,t,h,o,n,

列表遍历

>>> for i in [123,"AAA",234]:

print(i,end=",")

123,AAA,234,

文件遍历

for line in fi:

<语句块>

- fi是一个文件标识符,遍历其每行,产生循环

  • 无限循环
while <条件>:

<语句块>

  • 循环控制保留字
break跳出并结束当前整个循环,执行循环后的语句(当前层)

continue结束当次循环,继续执行后续次数循环

#continue

for i in "python":

if i == "t":

continue

print(i,end="")

>>>

====================== RESTART: C:\Python3.7.0\test.py ======================

pyhon

#break

for i in "python":

if i == "t":

break

print(i,end="")

====================== RESTART: C:\Python3.7.0\test.py ======================

py

#!/usr/bin/env python3

# -*- coding: UTF-8 -*-

s = "123"

while s != "":

for c in s:

print(c,end="")

s = s[:-1]

====================== RESTART: C:\Python3.7.0\test.py ======================

123121

#!/usr/bin/env python3

# -*- coding: UTF-8 -*-

s = "python"

while s != "":

for c in s:

if c == "t":

break

print(c,end="")

s = s[:-1]

====================== RESTART: C:\Python3.7.0\test.py ======================

pypypypypyp

  • 循环高级用法
for <循环变量> in <遍历结构>:

<语句块1>

else:

<语句块2>

while <>:

<语句块1>

else:

<语句块2>

循环与else

当循环没有被break语句退出时,执行else语句块

else语句块作为正常完成循环的奖励

这里else的用法与异常处理中else用法相似

#!/usr/bin/env python3

# -*- coding: UTF-8 -*-

for c in "python":

if c == "t":

continue

print(c,end="")

else:

print("!")

====================== RESTART: C:\Python3.7.0\test.py ======================

pyhon!

#!/usr/bin/env python3

# -*- coding: UTF-8 -*-

for c in "python":

if c == "t":

break

print(c,end="")

else:

print("!")

====================== RESTART: C:\Python3.7.0\test.py ======================

py

  • random库
伪随机数:采用梅森旋转算法生成的(伪)随机序列中元素

基本随机数函数:seed(),random()

扩展随机数函数:randint(),getrandbits(),uniform(),randrange(),choice(),shuffle()

seed(a = None)

初始化给定的随机数种子,默认当前系统时间

>>> import random

>>> random.seed(10)

random()

生成一个[0.0,1.0]之间的随机小数

>>> random.random()

0.5714025946899135

重复调用随机数相同

>>> random.seed(10)

>>> random.random()

0.5714025946899135

>>> random.seed(10)

>>> random.random()

0.5714025946899135

随机数刷新

#!/usr/bin/env python3

# -*- coding: UTF-8 -*-

import random

import time

random.seed(10)

while 1:

print("\r",random.random(),end="")

time.sleep(0.1)

时间刷新

#!/usr/bin/env python3

# -*- coding: UTF-8 -*-

import random

import time

t = time.gmtime()

while 1:

t = time.gmtime()

print("\r",time.strftime("%Y-%m-%d %H:%M:%S",t),end="")

time.sleep(0.01)

  • 扩展随机数函数
randint(a,b)

生成一个[a,b]之间的整数

>>> random.randint(5,10)

9

randrange(m,n,[k])

生成一个[m,n]之间以k为步长的随机整数

>>> random.randrange(50,100,2)

76

getrandbits(k)

生成一个k比特长的随机整数

>>> random.getrandbits(16)

31625

uniform(a,b)

生成一个[a,b]之间的随机小数

>>> random.uniform(5,10)

7.890456505672352

choice(seq)

从序列seq中随机选择一个元素

>>> random.choice([1,2,3,4,5,6,7,8,9])

4

shuffle(seq)

将序列seq中元素随机排序,返回打乱后的序列

>>> s = [1,2,3,4,5,6,7,8,9]

>>> random.shuffle(s)

>>> print(s)

[6, 7, 5, 9, 4, 2, 8, 1, 3]

随机序列刷新

#!/usr/bin/env python3

# -*- coding: UTF-8 -*-

import random

import time

s = [1,2,3,4,5,6,7,8,9]

while 1:

random.shuffle(s)

print("\r",s,end="")

time.sleep(0.5)

  • 圆周率计算
#!/usr/bin/env python3

# -*- coding: UTF-8 -*-

import random

pi = 0

N = 100

for k in range(N):

pi += 1 / pow(16,k) * \

(4 / (8 * k + 1) - \

2 / (8 * k + 4) - \

1 / (8 * k + 5) - \

1 /(8 * k + 6))

print("pi = {}".format(pi))

====================== RESTART: C:\Python3.7.0\test.py ======================

pi = 3.141592653589793

蒙特卡罗方法

#!/usr/bin/env python3

# -*- coding: UTF-8 -*-

from random import random

from time import perf_counter

DARTS = 1000 * 1000

hits = 0.0

start = perf_counter()

for i in range(1,DARTS + 1):

x,y = random(),random()

dist = pow(x ** 2 + y ** 2,0.5)

if dist < 1.0:

hits = hits + 1

pi = 4 * (hits / DARTS)

print("pi = {}".format(pi))

print("The time is :{:.5f}s".format(perf_counter() - start))

====================== RESTART: C:\Python3.7.0\test.py ======================

pi = 3.14154

The time is :0.88162s

>>>

====================== RESTART: C:\Python3.7.0\test.py ======================

pi = 3.139968

The time is :0.86474s

以上是 python程序控制 的全部内容, 来源链接: utcz.com/z/509732.html

回到顶部