例子1.寻找水仙花数。
说明:水仙花数也被称为超完全数字不变数、自恋数、自幂数、阿姆斯特朗数,它是一个3位数,该数字每个位上数字的立方之和正好等于它本身.
for i in range(100, 1000): a = i//100 b = i//10 % 10 c = i % 10 if i == a**3+b**3+c**3: print(i)
例子2.正整数的反转
num = int(input('请输入正整数')) ## 123456 rever_num = 0 while num >0: rever_num = rever_num*10 + num%10 num //= 10 print(rever_num)
例子3:百钱百鸡问题。
说明:百钱百鸡是我国古代数学家张丘建在《算经》一书中提出的数学问题:
鸡翁一值钱五,
鸡母一值钱三,
鸡雏三值钱一。
百钱买百鸡,
问鸡翁、鸡母、鸡雏各几何?
for i in range(0,21): for j in range(0,34): z = 100 -5*i -3*j if 5*i + 3*j + z//3 ==100 and z % 3 ==0: print(f'公鸡{i}只,母鸡{j}只,小鸡{z}只')
公鸡2只,母鸡30只,小鸡0只
公鸡5只,母鸡25只,小鸡0只
公鸡8只,母鸡20只,小鸡0只
公鸡11只,母鸡15只,小鸡0只
公鸡14只,母鸡10只,小鸡0只
公鸡17只,母鸡5只,小鸡0只
公鸡20只,母鸡0只,小鸡0只
例子4:斐波那契数列。输出前20项。
a, b = 1, 1 # 通过递推公式算出后面的18个数 for _ in range(18): a, b = b, a + b print(b, end=' ')
例子5:输入M和N计算C(M,N)。
用循环做累乘来计算阶乘
m = int(input('m = ')) n = int(input('n = ')) # 计算m的阶乘 fm = 1 for num in range(1, m + 1): fm *= num # 计算n的阶乘 fn = 1 for num in range(1, n + 1): fn *= num # 计算m-n的阶乘 fm_n = 1 for num in range(1, m - n + 1): fm_n *= num # 计算C(M,N)的值 print(fm//fn//fm_n)
用函数修改上面的求组合数
def fac(num): fn = 1 for i in range(1,num+1): fn*=i return fn m = int(input('m = ')) n = int(input('n = ')) print(fac(m)//fac(n)//fac(m-n))
定义默认参数
def add(a=0, b=0, c=0): return a + b + c print(add(1,2))
任意多个参数:可变参数
# 用星号表达式来表示args可以接收0个或任意多个参数 def add(*args): total = 0 # 可变参数可以放在for循环中取出每个参数的值 for val in args: total += val return total print(add(1,2,3,4,5,6,7))
用模块管理函数
module1.py def foo(): print('hello, world!') module2.py def foo(): print('goodbye, world!') test.py import module1 import module2 # 用“模块名.函数名”的方式(完全限定名)调用函数, module1.foo() # hello, world! module2.foo() # goodbye, world!
as关键字
test.py import module1 as m1 import module2 as m2 m1.foo() # hello, world! m2.foo() # goodbye, world!
from...import...
from module1 import foo foo() # hello, world! from module2 import foo foo() # goodbye, world! from module1 import foo as f1 from module2 import foo as f2 f1() # hello, world! f2() # goodbye, world!
函数是功能相对独立且会重复使用的代码的封装
字符串的定义
所谓字符串,就是由零个或多个字符组成的有限序列
s1 = 'hello, world!' s2 = "你好,世界!" print(s1, s2) # 以三个双引号或单引号开头的字符串可以折行 s3 = ''' hello, world! ''' print(s3, end='')
提示:print函数中的end=''表示输出后不换行,即将默认的结束符\n(换行符)更换
为''(空字符)。
转义字符和原始字符串
# 头尾带单引号的hello, world! s1 = '\'hello, world!\'' print(s1) # 头尾带反斜杠的hello, world! s2 = '\\hello, world!\\' print(s2)
反斜杠和字符n
在字符串'hello\n'中,\n表示换行;而在r'hello\n'中,\n不再表示换行,就是反斜杠和字符n。
# 字符串s1中\t是制表符,\n是换行符 s1 = '\time up \now' print(s1) # 字符串s2中没有转义字符,每个字符都是原始含义 s2 = r'\time up \now' print(s2)
拼接和重复
s1 = 'hello' + ' ' + 'world' print(s1) # hello world s2 = '!' * 3 print(s2) # !!! s1 += s2 # s1 = s1 + s2 print(s1) # hello world!!! s1 *= 2 # s1 = s1 * 2 print(s1) # hello world!!!hello world!!!