Python的基础

一、条件

1.1 if语句

语法:

if expression:
    expr_true_suite

expression条件表达式:

  1. 比较运算符
  2. 成员运算符
  3. 逻辑运算符

expr_true_suite

  1. expression条件为True时执行的代码块
  2. 代码块必须缩进(通常位4个空格)
#Filename:ifpro.py
sd1=3
sd2=3
if sd1==sd2
	print("the square's area is",sd1*sd2)

1.2 else语句

语法:

if ecpression:
	expr_true_suite
else:
    expr_false_suite

expr_false_suite:

  1. expression条件为False时执行的代码块
  2. 代码块必须缩进
  3. else语句不缩进
#Filename:elsepro.py
sd1=int(input('the first side:'))
sd2=int(input('the second side:'))
if sd1==sd2:
    print("the square's area is",sd1*sd2)
else
	print("the rectangle's area is",sd1*sd2)
'''out:
the first side:4
the second side:4
the square's area is:16'''

1.3elif语句

语法:

if expression:
    expr_true_suite
elif expression2:
    expr2_true_suite
		...
        ...
elif expressionN:
    expreN_true_suite
else:
    non_of_the_above_suite

expr2_true_suite

expression2True时执行的代码块

exprN_true_suite

expressionNTrue时执行的代码块

else

none_of_the_above_suite是以上所有条件都不满足时执行的代码块

#Filename:elifpro.py
k=input('input the index of shape:')
if k=='1':
	print('circhle')
elif k=='2':
    print('oval')
elif k=='3'
	print('rectangle')
elif k=='4'
	print('triangle')
else
	print('you input the invalid number')
'''out1:
input the index of shape:3
rectangle

out2:
input the index of shape:8
you input the invalid number
'''

1.5条件嵌套

​ 同等缩进为为同一条件结构

#Filename:ifnestpro.py
k=input('input the index of shape:')
if k=='1':
    print('circle')
elif k=='2':
    print('oval')
elif k=='3':
    sd1=int(input('the first side:'))
    sd2=int(input('the esecond side:'))
    if sd1==sd2
    	print("the square's area is",sd1*sd2)
    else:
        print("the rectangle's area is",sd1*sd2)
    print('rectangle')
elif k=='4':
    print('triangle')
else:
    print('you input the invalid number')

1.6条件表达式

语法

x if E else Y

​ E成立时返回x的值否则返回Y的值

1.7猜数字游戏

​ 程序随机产生一个0~300间的整数,玩家竞猜,系统给出“猜中”,“太大了”或“太小了”的提示

#Filename:guessnum1.py
from random import randint
x=randint(0,300)
digit=int(input('Please input a number between 0~300:'))
if digit==x:
    print('Bingo!')
elif digit>x
	print('Too large,please try again.')
else
	print('Too small,please try again.')

1.8练习题

1.8.1分数等级

​ 编写一个输入分数,输出分数等级的程序,具体为:

ScoreGrade
90~100A
70~89B
60~69C
0~59D
othersInvalid score

​ 请添加必要的输入输出语句,尽量让程序友好。

#my
x=eval(input('请输入成绩'))
if 90<=x<=100:
    print('您的成绩等级是A')
elif 70<=x<=89:
    print('您的成绩等级是B')
elif 60<=x<=69:
    print('您的成绩等级是C')
elif 0<=x<=59:
    print('您的成绩等级是D')
else:
    print('您输入的成绩是Invalid score')
#参考答案
score=eval(input("enter the score:"))
if 0<=score<=100:
    if 90<=score<=100:
        grade="A"
    elif score>=70:
        grade="B"
    elif score>=60:
        grade="C"
    elif score>=0:
        grade="D"
    print("The grade of {} is {}.".format(score,grade))
else:
    print("Invalid score")

1.8.2求方程实根

编写程序,从键盘输入一个一元二次方程ax^2+bx+c=0的三个参数a、b、c(a、b和c均为整数,且a不等于0),求此方程的实根。

如果方程有实根,则输出实根(保留一位小数),如果没有实根则输出没有实根的信息。

input1:
1,0,-1
out1:
x1=1.0,x2=-1.0

input2:
1,2,1
out2:
x=-1.0

input3:
2,2,3
out3:
no real solution
#my
from math import sqrt
a,b,c=eval(input("请输入a,b,c:"))
flag=b*b-4*a*c
if flag>0:
    x1=(-b+sqrt(flag))/(2*a)
    x2=(-b-sqrt(flag))/(2*a)
    print("x1={:.1f},x2={:.1f}".format(x1,x2))
elif flag==0:
    x=(-b+sqrt(flag))/(2*a)
    print("x={:.1f}".format(x))
else:
    print("no real solution")

1.8.3符号函数

​ 请分别用if-elif-else结构和嵌套的if结构实现符号函数(sign function),符号函数的定义为:

在这里插入图片描述

#my
x=eval(input("请输入x:"))
if x>0:
    x=1
elif x<0:
    x=-1
print("该x对应符号函数值为:{.0f}".format(x))

二、range函数

​ 产生一系列整数,返回一个range对象

语法:

range(start,end,step=1)		#不包含end的值
range(start,end)			#缺省step值为1
range(end)					#缺省start值为0,step为1

​ start 起始值(包含) 默认0

​ end 终值(不包含)

​ step 步长(不能为0) 默认1

list(range(3,11,2))
#out:[3,5,7,9]
list(range(3,11))
#out:[3,4,5,6,7,8,9,10]
list(range(11))
#out:[0,1,2,3,4,5,6,7,8,9,10]
异同range()xrange()
语法基本一致
返回列表生成器(类似)
生成真实列表用多少生成多少
异同range()
语法与python 2.x中类似
返回生成器(类似)
生成用多少生成多少

三、循环

3.1while循环

语法:

while expression:
    suite_to_repeat

expression:

  1. 条件表达式
  2. 当expression值为True时执行suite_to_repeat代码块
sumA=0;
j=1
while j<10:
    sumA+=j
    j+=1
sumA
#out:45
j
#out:10

3.2for循环

语法:

for iter_var in iterable_object:
    suite_to_repeat

可以明确循环次数:

  1. 遍历一个数据集内的成员

  2. 在列表解析中使用

  3. 生成器表达式中使用

    iterable_objectx(根据迭代对象产生迭代器)

  4. String

  5. List

  6. Tuple

  7. Dictionary

  8. File

​ range()返回的是一个 iterable_object

​ 字符串也是一个iterable_object

for i in range(3,11,2)
	print(i,end='')
#out:3 5 7 9
s='Python'
for c in s:					#序列项迭代
    print(c,end='')
#out:P y t h o n
for i in range(len(s))		#索引迭代
	print(s[i],end='')

模拟for循环

x=iter(range(3,11,2))
next(x)
#out:3
next(x)
#out:5
next(x)
#out:7
next(x)
#out:9
next(x)
'''Tracebakc (most recent call last):
	File "<pyshell#5>",line 1,in <module>
		next(x)
StopIteration'''

判断是否为可迭代的对象的方法

from collections.abc import Iterator,Iterable
isinstance(range(10),Iterator)		#类似于type(),除了判断某个对象是否为某个类,还能判断是否属于某个子类
#out:False
isinstance(iter(range(10)),Iterator)
#out:True

3.3循环的例子程序

3.3.1多次猜数字游戏

​ 程序随机产生一个0~300间的整数,玩家竞猜,允许猜多次,系统给出“猜中”、“太大了”、“太小了”的提示

#Filename:guessnum2.py
from random import randint

x=randint(0,300)
for	count in range(5)
	digit=int(input('Please input a number between 0~300:'))
    if digit==x;
    	print('Bingo!')
    elif digit>x:
        print('Too large,please try again.')

3.3.2x,y的最大公约数

x=eval(input('x='))
y=eval(input('y='))
if x<y:
    x,y=y,x
while	x%t!=0
	r=x%y
    x=y
    y=r
print('result=',y)

3.3.3钱的兑换方案

i,j,k=0,0,0
count=0
for	i in range(21):
	for j in range(51):
        k=100-5*i-2*j
        if k>0:
            cout+=1
print('count=',count)

3.4练习题

3.4.1求逆序数

​ 输入一个整数,求其逆序数。

​ 注:虽可以通过字符串切片等方法轻松获得一个数的逆序数,但用整数通过循环来获得逆序数是锻炼逻辑思维的一个好例子

#my
n=eval(input("请输入整数n:"))
temp=n
result=0
while n!=0:
    result=result*10+n%10
    n//=10
print("{:d}的逆序数是{:d}".format(temp,result))

3.4.2分解质因数

​ 将一个正整数分解质因数,例如:输入90打印90=2*3*3*5

#my
n=eval(input("请输入n:"))
print(n,'= ')
i=2
while n!=1:
    if n%i==0:
        n//i
        if n==1:
            print("{:d}".format(i))
        else:
            print("{:d}*".format(i),end=' ')
    else:
        i+=1

四、break、continue和else

4.1break语句

#Filename:breakpro.py
sumA=0
i=1
while True:
    sumA+=i
    i+=1
    if sumA>10:
        break
print('i={},sum={}'.format(i,sumA))
#Filename:prime.py
from math import sqrt
j=2
while j<=100
	i=2
	k=sqrt(j)
	while i<k:
		if j%i==0:break
		i=i+1
    if i>k
    	print(j,end='')
    j+=1
    
#写法2
from math import sqrt
for i in rage(2,101):
    flag=1
	k=int(sqrt(i))
    for j in range(2,k+1):
        if i%j==0:
            flag=0
            break
   	if(flag):
        print(i,end='')

4.2continue语句

#Filenmae:continuepro.py
sumA=0
i=1
while i<=5
	sumA+=i
    i+=1
    if i==3
    	continue
   	print('i={},sum={}'.format(i,sumA))

​ 在while和for循环中,continue语句的作用:

  1. 停止当前循环,重新进入循环
  2. while循环则判断循环条件是否满足
  3. for循环则判断迭代是否已经结束

4.3循环中的else语句

4.3.1猜数字游戏

​ 想停就停,非固定次数

#Filename:guessnum3.py
from random import randint
x=randint(0,300)
go='y'
while go=='y':
    digit=int(input('Please input a number between 0~300'))
    if digit==x:
        print('Bingo!')
        	break
    elif digit>x:
        print('Too large,please try again.')
    else:
        print('Too small,please try again.')
    print('Input y if you want to continue.')
    go=input()
    print(go)
else:
    print('Goodbye!')

4.3.2作用

​ 如果循环代码从break出终止,跳出循环

​ 正常结束循环则执行else中的代码

五、自定义函数

5.1自定义函数的创建

语法:

def function_name([arguments]):
"optional documentation string"	#文档字符串	print 函数名.doc
funtion_suite
def addMe2Me(x):
	'apply opeation+to argument'
	return (x+x)

5.2调用

​ 函数名加上函数运行符,一对小括号

  1. 括号之间是所有可选的参数
  2. 即使没有参数,小括号也不能省略
addMe2Me()
'''Traceback(most reecent call last):
	File"<pyshell#6>",line1,in <module>
		addMe2Me()
TypeError:addMe2Me()takes exactly 1 argument(0 given)'''
addMe2Me(3.7)
#out:7.4
addMe2Me(5)
#out:10
addMe2Me('Python')
#out:'PythonPython'

5.3例子

​ 输出1~100之间的素数

#Filename:prime.py
from math import sqrt
def isprime(x):
    if x==1:
        return False
    k=int(sqrt(x))
    for j in range(2,k+1):
        if x%j==0:
            return False
    return True
for i in range(2,101):
    if isprime(i):
        print(i,end='')

5.4默认参数

​ 函数的参数可以有一个默认值,如果提供有默认值,在函数定义中,默认参数以赋值语句的形式提供

def f(x=True)
	'''whether x is a correct word or not'''
    if x:
        print('x is a correct word')
    print('OK')
f()
'''out:x is a correct word
OK'''
f(False)		#默认参数是可修改的
#out:OK
def f(x,y=True):		#默认参数后跟一个非默认参数是不允许的
    '''x and y both correct words or not'''
    if y:
        print(x,'and y both correct')
    print(x,'is OK')
f(68)
'''out:68 and y both correct
68 is OK'''
f(68,False)
#out:68 is OK

​ 默认参数一般需要放置在参数列表的最后

5.5关键字参数

​ 关键字参数是让调用者通过使用参数名区分参数。

​ 允许改变参数列表中的参数顺序

def f(x,y)
	"x and y both correct words or not"
    if y:
        print x,'and y both correct'
    print(x,'is OK')
f(68,Flase)
#out:68 is OK
f(y=False,x=68)
#out:68 is OK
f(y=Flase,68)
#out:SyntaxError:non-keyword arg after keyword arg
f(x=69,False)
#out:SyntaxError:non-keyword arg after keyword arg

5.6传递函数

​ 函数可以像参数一样传递给另外一个函数

def addMe2Me(x)
	return x+x
def self(f,y)
	print(f(y))
self(addMe2Me,2.2)
#out:4.4

5.7lambda函数

​ 匿名函数

def addMe2Me(x):
    'apply operation+to argument'
    return x+X
addMe2Me(5)
#out:10
#等同
r=lambda x:x+x
r(5)
#out:10

在这里插入图片描述

六、递归

6.1例子:实现斐波那契数列

​ 循环实现:

#the nth Fibonacci number
def fib(n):
	a,b=0,1
    count=1
    while count<n:
        a,b=b,a+b
        cout=count+1
    print(a)

​ 递归实现:

#hte nth Fibonacci number
def fib(n):
    if n==0 or n==1:
    	return n
    else:
        return	fib(n-1)+fib(n-2) 

6.2递归的特点

​ 递归必须要有边界条件,即停止递归的条件

​ 递归的代码更加简洁,更符合自然逻辑,更容易理解

​ 递归的执行系统资源消耗比循环大

6.3汉诺塔游戏

​ 三个塔座A,B,C上各有一根针,通过B把64个盘子从A针移动到C针上,移动时必须遵循下列规则:

  1. 圆盘可以插在A,B,C塔座的针上
  2. 每次只能移动一个圆盘
  3. 任何时刻都不能讲一个较大的圆盘压在较小的圆盘之上
#Filenam:Henoi.py
def hanoi(a,b,c,n):
    if n==1:
        print(a,'->',c)
    else:
        hanoi(a,b,c,n-1)
        print(a,'->',c)
        hanoi(b,a,c,n-1)

hanoi('a','b','c',4)

七、变量作用域

7.1全局变量与局部变量

​ 在函数中的变量是局部变量,在程序代码主体部分的是全局变量

#Filename:global.py
global_str='hello'
def foo():
    local_str='world'
    return global_str+local_str
foo()
#Out[4]: 'helloworld'

7.2同名变量

​ 全局变量和局部变量用同一个名字

​ 遵循内层屏蔽外层

#Filename:samename.py
a=3
def f():
    a=5
    print(a**2)
f()
#out:25

7.3改变全局变量的值-global语句

#Fielname:scopeofvar.py
def f(x):
    print(a)
    a=5
    print(a+x)
a=3
f(8)
#out:UnboundLocalError: local variable 'a' referenced before assignment

​ 要将变量设置为全局

​ global语句强调全局变量

#Fielname:scopeofvar.py
def f(x):
    global a
    print(a)
    a=5
    print(a+x)
a=3
f(8)
'''out:3
13'''
print(a)
#out:5

八、Python采用标准库函数

8.1math库

import math

dir(math)
Out[11]: 
['__doc__','__loader__','__name__','__package__','__spec__','acos','acosh','asin', 'asinh','atan','atan2','atanh','ceil','copysign','cos','cosh','degrees','e','erf','erfc','exp','expm1','fabs','factorial','floor','fmod', 'frexp','fsum','gamma','gcd','hypot','inf','isclose','isfinite','isinf','isnan','ldexp','lgamma','log','log10','log1p','log2','modf','nan','pi','pow','radians','sin','sinh','sqrt','tan','tanh','tau','trunc']

math.pi
Out[12]: 3.141592653589793

math.e
Out[13]: 2.718281828459045

help(math.ceil)
Help on built-in function ceil in module math:

ceil(...)
    ceil(x)
    
    Return the ceiling of x as an Integral.
    This is the smallest integer >= x.

math.ceil(3.6)  #向上取整
Out[15]: 4

math.floor(3.6)  #向下取整
Out[16]: 3

math.pow(2,3)   #求次方
Out[17]: 8.0

math.sqrt(4)   #开方
Out[18]: 2.0

math.degrees(3.14)  #弧度转为角度
Out[19]: 179.9087476710785

math.radians(180)   #角度转为弧度
Out[20]: 3.141592653589793

8.2os库

import os

os.getcwd()   #获取当前工作目录
Out[24]: 'C:\\Users\\mumumu-w\\.spyder-py3'

path='C:\\Users\\mumumu-w\\.spyder-py3'
os.chdir(path)   #修改当前目录的路径
os.getcwd()
Out[27]: 'C:\\Users\\mumumu-w\\.spyder-py3'

os.rename('test.txt','test1.test')   #重命名文件

os.remove('test1.test')   #删除文件

8.3random库

import random

random.choice(['c++','java','python'])   #从序列中获取一个随机值
Out[31]: 'java'

random.randint(1,100)   #生成范围内的随机整数
Out[32]: 98

random.randrange(0,10,2)   #从后面range生成的数中获取一个
Out[33]: 0

random.random()   #生成0~1.0中的一个随机浮点数,包含0但是不包含1.0
Out[35]: 0.7401638959297775

random.uniform(5,10)    #生成范围间的一个浮点数
Out[36]: 7.357141094846911

random.sample(range(100),10)   #从给定的序列获取后面指定的个数的随机值,结果用列表返回
Out[38]: [85, 89, 70, 44, 90, 95, 96, 82, 73, 42]

nums=[1001,1002,1003,1004,1005]
random.shuffle(nums)
nums    #nums列表中的值顺序被打乱
Out[41]: [1001, 1005, 1004, 1002, 1003]

8.4datetime库

import datetime

dir(datetime)
Out[43]: 
['MAXYEAR','MINYEAR','__builtins__','__cached__','__doc__','__file__','__loader__','__name__','__package__','__spec__','date','datetime','datetime_CAPI','time','timedelta','timezone','tzinfo']

from datetime import date
date.today()   #今天的日期
Out[45]: datetime.date(2023, 3, 10)

from datetime import time
tm=time(23,20,35)   #创建一个时间变量
print(tm)
23:20:35

from datetime import datetime
dt=datetime.now()   #查看当前的日期和时间
dt
Out[51]: datetime.datetime(2023, 3, 10, 10, 58, 8, 743689)

dt=datetime.now()   #查看当前的日期和时间,带毫秒
dt
Out[53]: datetime.datetime(2023, 3, 10, 10, 58, 38, 471956)

print(dt.strftime('%a,%b %d %Y %H:%M'))   #转为固定格式的时间格式
Fri,Mar 10 2023 10:58

dt=datetime(2017,6,6,23,29)
print(dt)
2017-06-06 23:29:00
ts=dt.timestamp()   #将日期和时间转为时间戳
ts
Out[58]: 1496762940.0
print(datetime.fromtimestamp(ts))   #将时间戳转为本地时间
2017-06-06 23:29:00

九、异常

9.1查看异常类

dir(_builtins_)

类名描述
BaseException所有异常的基类
Exception常规异常的基类
AttributerError对象不存在此属性
IndexError序列中无此索引
IOError输入/输出操作失败
keyboardInterrupt用户中断执行(通常输入Ctrl-C)
keyError映射中不存在此键
NameError找不到名字(变量)
SyntaxErrorPython语法错误
TypeError对类型无效的操作
ValueError传入无效的参数
ZeroDivisionError除(或取模)运算的第二个参数为0

9.2异常处理

​ 对异常的处理可以用if语句,但Python提供try-except

if y!=0:
    print(x/y)
else:
    print('division by zero')

​ tyr-except对异常进行捕捉处理,避免程序因为异常而终止运行

#Filename:exception1.py
num1=int(input('Enter the first number:'))
num2=int(input('Enter the second number:'))
print(num1/num2)
Enter the first number:a
#out:ValueError: invalid literal for int() with base 10: 'a'

9.3try-except语句

try:
    raise		#检测语句
except Exception as er:
    print(err)
#Filename:exception2.py
try:
    num1=int(input('Enter the first number:'))
    num2=int(input('Enter the second number:'))
    print(num1/num2)
except ValueError:
    print('Please input a digit!')
#Filename:exception3.py
try:
    num1=int(input('Enter the first number:'))
    num2=int(input('Enter the second number:'))
    print(num1/num2)
except ZeroDivesionError as err:
    print('The second number cannot be zero!')
    print(err)

多个except子句和一个except块捕捉多个异常

#Filename:exception4.py
try:
    num1=int(input('Enter the first number:'))
    num2=int(input('Enter the second number:'))
    print(num1/num2)
except ValueErrorL:
    print('Please input a digit!')
except ZeroDivesionError:
    print('The second number cannot be zero!')
#Filename:exception5.py
try:
    num1=int(input('Enter the first number:'))
    num2=int(input('Enter the second number:'))
    print(num1/num2)
except (ValueErrorL,ZeroDivesionError):
    print('Invalid input!')

空except子句和as

#Filename:exception6.py			#仅知道出错但不知道出错原因
try:
    num1=int(input('Enter the first number:'))
    num2=int(input('Enter the second number:'))
    print(num1/num2)
except:
    print('Something went wrong!')
#Filename:exception7.py
try:
    num1=int(input('Enter the first number:'))
    num2=int(input('Enter the second number:'))
    print(num1/num2)
except Exception as err:
    print('Something went wrong!')
    print(err)

9.4else子句

#Filename:exception8.py
try:
    num1=int(input('Enter the first number:'))
    num2=int(input('Enter the second number:'))
    print(num1/num2)
except(ValueError,ZeroDivisionError):
    print('Invalid input!')
else:
    print('Aha,everything is OK.')
Enter the first number:3
Enter the second number:5
0.6
Aha,everything is OK.

9.5循环处理异常至正确

#Filename:exception9.py
while True:			#没有正确输入引发异常
    try:
        num1=int(input('Enter the first number:'))
        num2=int(input('Enter the second number:'))
        print(num1/num2)
        break
    except ValueError:
        print('Please input a digit!')
    except ZeroDivisionError:
        print('The second number cannot be zero!')
Enter the first number:a
Please input a digit!

Enter the first number:3
Enter the second number:0
The second number cannot be zero!

Enter the first number:3
Enter the second number:5
0.6

break的位置

#Filename:exception10.py
while True:
    try:
        num1=int(input('Enter the first number:'))
        num2=int(input('Enter the second number:'))
        print(num1/num2)
    except Exception as err:
        print(err)
    else:
        break
#Filename:exception11.py
aList=[1,2,3,4,5]
i=0
while True:
    try:
        print(aList[i])
    except IndexError:
        print('index error')
        break
    else:
        i+=1

9.6finally子句

​ 无论是否异常都会执行

#Filename:exception12.py
def finallyTest():
    try:
        x=int(input('Enter the first number:'))
        y=int(input('Enter the second number:'))
        print(x/y)
        return 1
    except Exception as err:
        print(err)
        return 0
    finally:
        print('It is a finally clause.')
result=finallyTest()
print(result)
Enter the first number:3
Enter the second number:5
0.6
It is a finally clause.
1

Enter the first number:3
Enter the second number:0
division by zero
It is a finally clause.
0

9.7上下文管理器(Context Manageer)和with语句

​ 利用try-finally来处理文件的关闭

​ 不管文件是否正常打开都会关闭,但文件若不能正常打开,f无变量,程序仍然异常

#Filename:exception13.py
try:
    f=open('data.txt')
    for line in f:
        print(line,end='')
except IOError:
    print('Cannot open the file!')
finally:
    f.close()

​ 用上下文管理器定义和控制代码块执行前的准备动作及执行后的收尾动作

#Filename:exception14.py
with open('data.txt') as f:
    for line in f:
        print(line,end='')

9.8异常编程练习题

​ 编写要给程序,让用户输入苹果的个数和单价,然后计算出价格总额。

Enter count:10
Enter price for each one:3.5
Pay:35

​ 运用try-except语句让程序可以处理非数字输出的情况,如果是非数字输入,打印消息并允许用户再次输入,知道输入正确类型值计算出结果后退出,以下是程序的执行结果:

Enter count:20
Enter price for each one:four
Error,please enter numeric one.

Enter count:twenty
Error,please enter numeric one.

Enter count:20
Enter price for each one:4
The price is 80.
#my     
while True:
    try:
        cnt=int(input("Enter count:"))
        price = float(input("Enter price for each one: "))
        pay=cnt*price
        print(pay)
    except ValueError:
        print("Error, please enter numeric one.")

十、控制结构和函数编程练习

10.1身体质量指数

​ 身体质量指数 (BMI,Body Mass index) 是国际上常用的衡量人体肥胖程度和是否健康的重要标准,计算公式为: BMI=体重/身高的平方(国际单位 kg/m) 。中国的成年人BMI 数值定义为:
​ 过轻:低于 18.5
​ 正常: 18.5-23.9
​ 过重:24-27.9
​ 肥胖: 高于 28
​ 请输入体重和身高,输出相应的 BMI 值和体重肥胖程度判断结果 (too thin、normal、overweight 或 fat).

[输入样例]
60,1.6
[输出样例]
Your BMI is 23.4
normal
[提示]
程序中体重和身高的输入可用“weight, height = eval(input())”语句表示。
#my
w,h=eval(input())
bmi=w/h**2
if bmi>=28:
    flag="fat"
elif bmi>=24:
    flag="overweight"
elif bmi>=18.5:
    flag="normal"
else:
    flag="too thin"
print("Your BMI is {0:.1f}".format(bmi))
print(flag)

10.2温度转换

​ 按公式:C= 5/9x(F-32),将华氏温度转换成摄氏温度,并产生一张华氏 0~300 度与对应的摄氏温度之间的对照表 (每隔 20 度输出一次)

#my
for i in range(0,320,20):
    c=5/9*(i-32)
    print("华氏度",i,"对应摄氏度{0:.1f}".format(c))

10.3角谷猜想

​ 角谷静夫是日本的一位著名学者,他提出了一个猜想(称为角谷猜想) : 对于个正整数 n,若为偶数则除以 2,若为奇数则乘以 3 加1,得到一个新的数后按照之前的两条规则继续演算,若干次后得到的结果必然为 1。输入任一正整数,输出演算过程。

[输入样例]
110
[输出样例]
10/2=5
5*3+1=16
16/2=8
8/2=4
4/2=2
2/2=1
#my
def CornucopiaConjecture(n):
    if n==2:
        print('2/2=1')
    else:
        t=n
        if n%2==0:
            n/=2
            print('{:.0f}'.format(t),'/2=','{:.0f}'.format(n))
            CornucopiaConjecture(n)
        else:
            n=n*3+1
            print('{:.0f}'.format(t),'*3+2=','{:.0f}'.format(n))
            CornucopiaConjecture(n)
x=eval(input())
CornucopiaConjecture(x)

10.4求n!和

​ 输入 n,用递推法(例如前项之间的关系推导后项,本题为一重循环) 编程求1+2!+3!+…+n!的和并输出。

[输入样例]
5
[输出样例]
153
#my
def SumOfStrata(n,sum):
    if n==1:
        sum+=n;
        print(++sum)
    else:
        y=1
        for i in range(1,n+1,1):
            y*=i
        sum+=y
        n-=1
        SumOfStrata(n,sum)

x=eval(input())
sum=0
SumOfStrata(x,sum)

10.5求数字组合

​ 编程求解 1-4 这 4 个数字可以组成多少个无重复的三位数,按从小到大的顺序输出这些数字

#my
for i in range(1,5):
    for j in range(1,5):
        for k in range(1,5):
            if i!=k and i!=j and j!=k:
                print(100*i+10*j+k)

10.6命题-37的倍数

​ 验证命题: 如果一个三位整数是 37 的倍数,则这个整数循环左移后得到的另两个 3 位数也是 37 的倍数。(注意验证命题的结果输出方式,只要输出命题为真还是假即可,而非每一个三位数都有一个真假的输出)

#my
x=int(input())
flag=0
if x%37==0:
    x=x*10%1000
    if x%37==0:
        x=x*100%1000
        if x%37==0:
            flag=1
        else:
            flag=0
    else: 
        flag=0
else:
    flag=0
if flag==0:
    print("False")
else:
    print("True")
#参考答案
for num in range(100,1000):
    if num%37==0:
        num1=num%100*10+num//100
        num2=num%10*100+num//10
        if num1%37!=0 or num2%37!=0:
            print("it's a false proposition.")
            break
    else:
        print("It's a true proposition")

10.7完数

​ 一个数如果等于它的因子之和则称这个数为完数,例如 6,6=1+2+3,编程计算 1000之内的所有完数并输出。

#my
for i in range(0,1001):
    sum=0
    for j in range(1,i):
        if i%j==0:
            sum+=j
    if sum==i:
        print(i)
#参考答案
for i in range(1,1001):
    s=0
    for j in range(1,i):
        if i%j==0:
            s+=j
    if s==i:
        print("\n",i," ",end="")
        print("its factors are",end="")
        for j in range(1,i):
            if i%j==0:
                print(j,end=" ")

10.8哥德巴赫猜想

​ 验证哥德巴赫猜想之一: 2000 以内的正偶数(大于等于 4) 都能够分解为两个质数之和。每个偶数表达成形如: 4=2+2 的形式。

import math
def isPrimeNumber(x):
    if x==1:
        return 0
    n=int(math.sqrt(x))
    for i in range(2,n+1):
        if x%i==0:
            return 0
    return 1

def gc(n):
    k=3
    while k<n:
        t=n-k
        if t<k:
            break
        if isPrimeNumber(k) and isPrimeNumber(t):
            return k,t
        k+=2

n=int(input())
if n>4:
    a,b=GC(n)
    print("{}={}+{}".format(n,a,b))
elif n==4:
    print("{}={}+{}".format(4,2,2))

十一、单元测试编程题

11.1寻找n以内的亲密数对

​ 代码格式如下:

    def fac(n):
        ...
        return  xxx
    n = int(input())   # 此处输入由系统自动完成不需要自己输入,只要写这样一条语句即可...(3分)

题目内容:

​ 对于两个不同的整数A和B,如果整数A的全部因子(包括1,不包括A本身)之和等于B;且整数B的全部因子(包括1,不包括B本身)之和等于A,则将A和B称为亲密数。自定义函数fac(x)计算x包括1但不包括本身的所有因子和并返回。从键盘输入整数n,调用fac()函数寻找n以内的亲密数并输出。注意每个亲密数对只输出一次,小的在前大的在后,例如220-284。

输入格式:

​ 按提示用input()函数输入

输出格式:

​ 按样例形式,可使用形如“print(“{}-{}”.format(参数1, 参数2))”输出语句进行亲密数对的输出

输入样例:

500

输出样例:

220-284

​ 时间限制:1500ms内存限制:100000kb

#my
def fac(n):
    sum=0
    for i in range(1,n):
        if n%i==0:
            sum+=i
    return  sum
n = int(input())
for i in range(1,n):
    x=fac(i)
    y=fac(x)
    if y==i and x<n and x!=i:
        if x<i:
            x1,x2=x,i
        else:
            x1,x2=i,x
        print("{}-{}".format(x1,x2))

11.2寻找第n个默尼森数

​ 代码格式如下:

def prime(num):
        ...
def monisen(no):
        … …
        return  xxx
print(monisen(int(input())))    # 此处输入由系统自动完成不需要自己输入,只要写这样一条语句即可(3分)

题目内容:

​ 找第n个默尼森数。P是素数且M也是素数,并且满足等式M=2P-1,则称M为默尼森数。例如,P=5,M=2P-1=31,5和31都是素数,因此31是默尼森数。

输入格式:

​ 按提示用input()函数输入

输出格式:

​ int类型

输入样例:

4

输出样例:

127

​ 时间限制:1000ms内存限制:32000kb

import math
def prime(num):
    x=int(math.sqrt(num))
    for j in range(2,x):
        if num%j==0:
            return 0
    return 1
            
def monisen(no):
    i=2
    m=0
    while no>=0:
        if prime(i)==1:
            m=2**i-1
            if prime(m)==1:
                no-=1
        i+=1
    return  m
print(monisen(int(input())))

11.3判断丑数

​ 代码格式如下:

def isUglyNumber (n):
    … …
    
print(isUglyNumber(int(input())))  # 此处输入由系统自动完成不需要自己输入,只要写这样一条语句即可(3分)(3分)

题目内容:

​ 编写一个程序判断给定是否是丑数。丑数就是只包含质因数 2, 3, 5 的正整数。

​ 说明:1是丑数

输入格式:

​ 按提示用input()函数输入

输出格式:

​ True/False

输入样例:

14

输出样例:

False(解释:因为 14=2*7,还包含质因数7,所以14不是丑数)

时间限制:500ms内存限制:32000kb

def isUglyNumber (n):
    while n>1:
        if n%2==0:
            n//=2
        elif n%3==0:
            n//=3
        elif n%5==0:
            n//=5
        else:
            break
    if n==1:
        return True
    else:
        return False
print(isUglyNumber(int(input())))

11.4泰波那契数

​ 给你整数 n,请返回第 n 个泰波那契数 Tn 的值。(3分)

题目内容:

​ 泰波那契序列 Tn 定义如下:

​ T0 = 0, T1 = 1, T2 = 1, 且在 n >= 0 的条件下 Tn+3 = Tn + Tn+1 + Tn+2

def tribonacci(n):
    return res
print(tribonacci(int(input())))

输入格式:

​ 按照input()提示输入

输出格式:

​ 整数

输入样例:

4

输出样例:

4(解释:T_3 = 0 + 1 + 1 = 2, T_4 = 1 + 1 + 2 = 4)

时间限制:500ms内存限制:32000kb

def tribonacci(n):
    l=[0,1,1]
    if n<4:
        return l[n]
    else:
        for i in range(3,n+1):
            x=l[i-1]+l[i-2]+l[i-3]
            l.append(x)
        return l[n]
print(tribonacci(int(input())))

十二、参考资料

[1]用Python玩转数据
1

def monisen(no):
i=2
m=0
while no>=0:
if prime(i)==1:
m=2**i-1
if prime(m)==1:
no-=1
i+=1
return m
print(monisen(int(input())))


## 11.3判断丑数

​		代码格式如下:

```python
def isUglyNumber (n):
    … …
    
print(isUglyNumber(int(input())))  # 此处输入由系统自动完成不需要自己输入,只要写这样一条语句即可(3分)(3分)

题目内容:

​ 编写一个程序判断给定是否是丑数。丑数就是只包含质因数 2, 3, 5 的正整数。

​ 说明:1是丑数

输入格式:

​ 按提示用input()函数输入

输出格式:

​ True/False

输入样例:

14

输出样例:

False(解释:因为 14=2*7,还包含质因数7,所以14不是丑数)

时间限制:500ms内存限制:32000kb

def isUglyNumber (n):
    while n>1:
        if n%2==0:
            n//=2
        elif n%3==0:
            n//=3
        elif n%5==0:
            n//=5
        else:
            break
    if n==1:
        return True
    else:
        return False
print(isUglyNumber(int(input())))

11.4泰波那契数

​ 给你整数 n,请返回第 n 个泰波那契数 Tn 的值。(3分)

题目内容:

​ 泰波那契序列 Tn 定义如下:

​ T0 = 0, T1 = 1, T2 = 1, 且在 n >= 0 的条件下 Tn+3 = Tn + Tn+1 + Tn+2

def tribonacci(n):
    return res
print(tribonacci(int(input())))

输入格式:

​ 按照input()提示输入

输出格式:

​ 整数

输入样例:

4

输出样例:

4(解释:T_3 = 0 + 1 + 1 = 2, T_4 = 1 + 1 + 2 = 4)

时间限制:500ms内存限制:32000kb

def tribonacci(n):
    l=[0,1,1]
    if n<4:
        return l[n]
    else:
        for i in range(3,n+1):
            x=l[i-1]+l[i-2]+l[i-3]
            l.append(x)
        return l[n]
print(tribonacci(int(input())))

十二、参考资料

[1]用Python玩转数据

  • 1
    点赞
  • 12
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值