菜鸟 Python 100例

以下参考:菜鸟教程 python100例 == 推荐博客

有四个数字:

1、2、3、4,能组成多少个互不相同且无重复数字的三位数?各是多少?

import itertools
a = ('1','2','3','4')
for i in range(1,5):
    for k in itertools.permutations(a,i):
        if 3 == len(k):
            print(''.join(k))

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(i,j,k)

企业发放的奖金根据利润提成。

利润(I)低于或等于10万元时,奖金可提10%;利润高于10万元,低于20万元时,低于10万元的部分按10%提成,高于10万元的部分,可提成7.5%;20万到40万之间时,高于20万元的部分,可提成5%;40万到60万之间时高于40万元的部分,可提成3%;60万到100万之间时,高于60万元的部分,可提成1.5%,高于100万元时,超过100万元的部分按1%提成,从键盘输入当月利润I,求应发放奖金总数?

b = [1000000,600000,400000,200000,100000,0]
r = [0.01,0.015,0.03,0.05,0.075,0.1]
cou = 0

you = int(input("你的业绩:"))
for i in range(len(b)):
    if you > b[i]:
        cou += (you - b[i]) * r[i]
        print('提成额度',you-b[i],'提成点',str(r[i]*100)+'%','奖金:',(you - b[i]) * r[i])
        you = b[i]
print(cou)

一个整数,它加上100后是一个完全平方数,再加上168又是一个完全平方数,请问该数是多少?

# 设这个数是 n,
# n+100 = a^2,
# a^2+168=b^2,
# 所以 (b+a)(b-a)=168=84*2 = 42*4 = 28*6 = 14*12,
# 由 b+a=84,b-a=2 解得 a=(84-2)/2=41,所以 n=41^2-100 = 1581,
# 由 b+a=42,b-a=4 解得 a=(42-4)/2=19,所以 n=19^2-100=261,
# 由 b+a=28,b-a=6 解得 a=(28-6)/2=11,所以 n=11^2-100 = 21 ,
# 由 b+a=14,b-a=12 解得 a=(14-12)/2=1,所以 n=1^2-100 = -99

for i in range(1, 85):
    if 168 % i == 0:
        j = 168 / i
        x = 168 / j
        a = (j-x)/2
        n = a*a-100
        if n - int(n) == 0:
            print(int(n))

输入某年某月某日,判断这一天是这一年的第几天?

date = input("请输入日期<例 2019-10-08>:")
days = (0,31,59,90,120,151,181,212,243,273,304,334)
sum = 0
leap = 0
try:
    y,m,d = date.split('-')
    if 0 < int(m) <= 12:
        sum = days[int(m)-1]
        sum += int(d)
        if (int(y) % 400 == 0) or ((int(y) % 4 == 0) and (int(y) % 100 != 0)):
            leap = 1
        if (leap == 1) and (int(m) > 2):
            sum += 1
        print(sum)
    else:
        print("月份输入错误")
except Exception as a:
    print("请按照提示输入")

输入三个整数x,y,z,请把这三个数由小到大输出。

li = []
for i in ("x","y","z"):
    inp = input("输入 %s 数字:" %i)
    li.append(int(inp))
li.sort()
print(li)

输出 9*9 乘法口诀表

for i in range(10):
    for j in range(1,i+1):
        print("%d*%d=%d"%(j,i,i*j),end=' ')
    print()

暂停一秒输出,并格式化当前时间。

import time,datetime
print(datetime.datetime.now())
time.sleep(1)
print(datetime.datetime.now())
time.sleep(1)
print(time.localtime())
time.sleep(1)
print(time.strftime('%Y-%m-%d %H:%M:%S',time.gmtime()))

有一对兔子,

从出生后第3个月起每个月都生一对兔子,小兔子长到第三个月后每个月又生一对兔子,假如兔子都不死,问每个月的兔子总数为多少?

a = 0 #1,1 2 3 5 8 13 21 34
b = 1 #1 2 3 5 8 13 21 34 55
for i in range(1, 13):
    print('%s月:有%s只兔子' % (i, b))
    a, b = b, a + b

判断101-200之间有多少个素数,并输出所有素数

cou = 0
for i in range(101, 201):
    k = 0
    for j in range(2, i):
        if i % j == 0:
            k += 1
            #print(i, j, end=' ')
    if k == 0:
        cou += 1
        print(i)
print("总共" + str(cou) + "个素数")

检查网站是否可以正常访问

import requests
for i in ur:
    try:
        url = 'http://'+i
        r = requests.get(url)
        if r.status_code == 200:
            print(url)
    except Exception as err:
        print()

打印出所有的"水仙花数"

所谓"水仙花数"是指一个三位数,其各位数字立方和等于该数本身。例如:153是一个"水仙花数",因为153=1的三次方+5的三次方+3的三次方。

for x in range(100,1000):
    a = str(x)
    if int(a[0])**3+int(a[1])**3+int(a[2])**3 == x:
        print(x)

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

while True:
    x = int(input("输入整数:"))
    print('%d='%x,end='')
    while x > 1:
        for i in range(2,x+1):
            if x % i == 0:
                x = int(x/i)
                if x == 1:
                    print('%d' % i, end='')
                else:
                    print('%d*' % i,end='')
    print()

输入一行字符,分别统计出其中英文字母、空格、数字和其它字符的个数。

def sum(count):
    number = 0
    string = 0
    space = 0
    other = 0
    for i in count:
        if i.isdigit():
            number += 1
        elif i.isalpha():
            string += 1
        elif i.isspace():
            space += 1
        else:
            other +=1
    return '数字:'+str(number) + ';字母:'+ str(string) + ';空格:'+ str(space) +';其他:' + str(other)

print(sum('my name is fana 1234567'))
xx = input("输入:")
print(sum(xx))

求s=a+aa+aaa+aaaa+aa...a的值

其中a是一个数字。例如2+22+222+2222+22222(此时共有5个数相加),几个数相加由键盘控制

number = int(input("请输入数字:"))
frequency = int(input("次数:"))
x = number
a = []
sum = 0
for i in range(frequency):
    a.append(x)
    c = str(x)+str(number)
    x = c

for j in range(len(a)):
    sum += int(a[j])

for k in a:
    if k == a[-1]:
        print(k,end='')
    else:
        print(str(k),end='+')
print('=%d' % sum,end='')

一球从100米高度自由落下

每次落地后反跳回原高度的一半;再落下,求它在第10次落地时,共经过多少米?第10次反弹多高?

ball = 100
hop = []
for i in range(10):
    if i == 0:
        hop.append(ball)
    else:
        hop.append(ball*2)
    ball = ball / 2
    print("第%s次,反弹%s米" % (i+1, ball))
print("第10次落地,共经历%s米"%(sum(hop)))

猴子吃桃问题:

猴子第一天摘下若干个桃子,当即吃了一半,还不瘾,又多吃了一个第二天早上又将剩下的桃子吃掉一半,又多吃了一个。以后每天早上都吃了前一天剩下的一半零一个。到第10天早上想再吃时,见只剩下一个桃子了。求第一天共摘了多少。

x = 1
for i in range(9,0,-1):
    print(i,end=' = ')
    x = (x+1)*2
    print(x)

一个数如果恰好等于它的因子之和,这个数就称为"完数"。

例如6=1+2+3.编程找出1000以内的所有完数。

from sys import stdout

for j in range(2, 1001):
    k = []
    n = -1
    s = j
    for i in range(1, j):
        if j % i == 0:
            n += 1
            s -= i
            k.append(i)
    if s == 0:
        print(j)
        for i in range(n):
            stdout.write(str(k[i]))
            stdout.write(' ')
        print(k[n])

两个乒乓球队进行比赛,各出三人。

甲队为a,b,c三人,乙队为x,y,z三人。已抽签决定比赛名单。有人向队员打听比赛的名单。a说他不和x比,c说他不和x,z比,请编程序找出三队赛手的名单。

for i in itertools.permutations(red):
    for j in zip(i, blue):
        if j in [('a','x'),('c','x'),('c','z')]:
            break
    else:
        for k in range(len(red)):
            print(i[k], blue[k])
#2 ==========================
for player1 in 'cab':
    for player2 in 'xyz':
        if player1 == 'c' and player2 != 'x' and player2 != 'z':
            remain2 = set('xyz') - set(player2)
            print("{}----{}".format(player1,player2))
        if player1 == 'a' and player2 != 'x' and player2 in remain2:
            remain2 -= set(player2)
            print("{}----{}".format(player1,player2))
        if player1 == 'b' and player2 in remain2:
            print("{}----{}".format(player1,player2))

打印出如下图案(菱形):

   *
  ***
 *****
*******
 *****
  ***
   *
#==1============
a = "*"
c = 1
b = 4
for i in range(b):
    c += 2
for i in range(b):
    print(a.center(c,' '))
    a = a + "**"
for j in range(b):
    if j == 0:
        a = a[:-2]
        continue
    else:
        a = a[:-2]
        print(a.center((c),' '))
#==2============
from sys import stdout
for i in range(4):
    for j in range(2 - i + 1):
        stdout.write(' ')
    for k in range(2 * i + 1):
        stdout.write('*')
    print()
 
for i in range(3):
    for j in range(i + 1):
        stdout.write(' ')
    for k in range(4 - 2 * i + 1):
        stdout.write('*')
    print()

有一分数序列

2/1,3/2,5/3,8/5,13/8,21/13...求出这个数列的前20项之和。

a = 2
b = 1
count = 0
for i in range(20):
    count += a/b
    b, a = a, a+b
    print("%s = %s" %(i,count))

求1+2!+3!+...+20!的和

# c = 0
# for i in range(1,21):
#     c = c+i
#     print("%s = %s + %s"%(c,c-i,i))
# ==== 后面有! 是阶乘 ====
c = 1
x = 0

for i in range(1,21):
    c = c * i
    x = x +c
    #print("%s! = %s" %(i,c))
    if i == 20:
        print("%s" % (i), end='')
    else:
        print("%s+" %(i),end='')
print("=%s"%x,end='')

利用递归方法求5!

def sum(n):
    if n == 0:
        con = 1
    else:
        con = n * sum(n - 1)
    return con

print(sum(5))

利用递归函数调用方式,将所输入的5个字符,以相反顺序打印出来

def fan(inp):
    if len(inp) == 1:
        print(inp[-1])
    else:
        print(inp[-1])
        fan(inp[:-1])

a = input("请输入:")
fan(a)

有5个人坐在一起,问第五个人多少岁?

他说比第4个人大2岁。问第4个人岁数,他说比第3个人大2岁。问第三个人,又说比第2人大两岁。问第2个人,说比第一个人大两岁。最后问第一个人,他说是10岁。请问第五个人多大?

def age(x):
    if x == 1:
        one = 10
    else:
        one = age(x-1) + 2
    return one
print(age(5))

给一个不多于5位的正整数

要求:一、求它是几位数,二、逆序打印出各位数字

x = input("请输入一个数:")
if not x.isdigit():
    print("不是数字")
else:
    n = str(x)
    print('length:', len(n))
    print('numbers: ',end='')
    for i in range(len(n)-1, -1, -1):
        print(n[i],end=' ')

一个5位数,判断它是不是回文数。

即12321是回文数,个位与万位相同,十位与千位相同

x = input("请输入一个数:")
t = True
if x.isdigit():
    n = str(x)
    for i in range(len(n)):
        print(n[i],n[-i-1])
        if n[i] != n[-i-1]:
            t = False
            break
else:
    print("请输入数字")
if t:
    print("%s = %s 是回文数" %(x,t))
else:
    print("%s = %s 不是回文数" %(x,t))

## 2 ###################
if len(n) == 5:
    if n == "".join(reversed(n)):
        print('{0}是回文数'.format(n))
    else:
        print('{0}不是回文数'.format(n))
else:
    print("输入错误")

文本颜色设置

显示方式 效果 字体色 背景色 颜色
0 默认 30 40 黑色
1 高亮 31 41 红色
4 下划线 32 42 绿色
5 闪烁 33 43 黃色
7 反显 34 44 蓝色
8 不可见 35 45 紫红色
22 非粗体 36 46 青蓝色
24 非下划线 37 47 白色
25 非闪烁
27 非反显
	# 常见开头格式:
	# \033[0m            默认字体正常显示,不高亮
	# \033[32;0m       红色字体正常显示
	# \033[1;32;40m  显示方式: 高亮    字体前景色:绿色  背景色:黑色
	# \033[0;31;46m  显示方式: 正常    字体前景色:红色  背景色:青色
	# \033[1;31m  显示方式: 高亮    字体前景色:红色  背景色:无

print('\033[31m 字体红色,但无背景色 \033[0m')  # #红色
print('\033[1;45m 字体不变色,有背景色 \033[0m')  # 有高亮
print('\033[1;35;46m 字体有色,且有背景色 \033[0m')  # 有高亮

print('\033[1;31;44m'+'*' * 45)
print('  错误次数超限,用户已被永久锁定,请联系管理员!')  #字体颜色红色反白处理
print('*' * 45 + "\033[1;31;44m")

按逗号分隔列表

a = [1,2,3,4,5,6]

for i in a:
    if i == a[len(a)-1]:
        print(i,end='')
    else:
        print(i,end=',')
## === 2 ===
str = ','.join(str(i) for i in a)
print(str)

按相反的顺序输出列表的值。

a = [1,2,3,4,5,6]
a.reverse()
print(a)
## --- 2 ----
for i in range(len(a)-1,-1,-1):
    print(a[i])

请输入星期几的第一个字母来判断一下是星期几,

如果第一个字母一样,则继续判断第二个字母。

week = ['Monday','Tuesday','Wednesday','Thursday','Friday','Saturday','Sunday']
a = []
inp = input("week:").upper()
for i in week:
    if inp == i[0]:
        a.append(i)
if len(a) >= 2:
    inp1 = input("输入第二个字母:")
    for j in a:
        if inp1 == j[1]:
            print(j)
else:
    print(''.join(a))

求100之内的素数

## 求100之内的素数
cou = 0
for i in range(1,101):
    k = 0

    for j in range(2,i):
        if i % j == 0:
            k += 1
    if k == 0:
        cou += i
        print(i,end=',')
print("总和是%s" %cou)

对10个数进行排序。

li = [12,3,5,6,89,23,7,34,21,100]
for i in range(1,len(li)):
    for j in range(len(li)-i):
        if li[j] < li[j+1]:
            temp = li[j]
            li[j] = li[j+1]
            li[j+1] = temp
print(li)

## == 2===
for i in range(9):
    for j in range(i+1, 10):
        if li[j-1] > li[j]:
            a = li[j]
            li[j] = li[j-1]
            li[j-1] = a
print(li)

有一个已经排好序的数组。现输入一个数,要求按原来的规律将它插入数组中。

li = [3, 5, 6, 7, 12, 21, 23, 34, 89, 100]
number = int(input("请输入数字:"))
li2 = li
li2.append(number)
for i in range(len(li2)):
    for j in range(i+1, len(li2)):
        if li2[j-1] > li2[j]:
            a = li2[j]
            li2[j] = li2[j-1]
            li2[j-1] = a
print(li2)

将一个数组逆序输出。

li = [3, 5, 6, 7, 12, 21, 23, 34, 89, 90,100]

li.reverse()
print(li)
## === 2 ===
li2 = []
for i in range(len(li)-1,-1,-1):
    li2.append(li[i])
print(li2)
## === 3 ===
for i in range(int(len(li)/2)):
    li[i] = li[len(li) - i - 1]
    li[len(li) - i - 1] = li[i]
print(li)

求一个3*3矩阵主对角线元素之和。

b = [[3, 5, 6], [7, 12, 21], [23, 34, 89]]
for i in range(3):
   print(b[i][i])
   sum1 = sum1 + b[i][i]
print(sum1)

统计 1 到 100 之和。

for i in range(1,101):
    coun += i
print(coun)

计算字符串的长度

while True:
    int = input(">>>\n")
    if int == 'q':
        exit('退出了')
    else:
        print('长度是:',len(int))

Python 两个矩阵相加。

X = [[12,7,3],
    [4 ,5,6],
    [7 ,8,9]]
Y = [[5,8,1],
    [6,7,3],
    [4,5,9]]
n = [[],[],[]]
for i in range(len(X)):
    for j in range(len(Y)):
        print("%s+%s=%s" %(X[i][j],Y[i][j],X[i][j]+Y[i][j]))
        n[i].append(X[i][j]+Y[i][j])
print(n)

注册用户和登陆用户(读写文本版)

username = input('请输入你要注册的用户名:')
password = input('请输入你要注册的密码:')
with open('list_of_info',mode='w',encoding='utf-8') as f:
    f.write('{}\n{}'.format(username,password))
print('恭喜您,注册成功')
lis = []
i = 0
while i < 3:
    usn = input('请输入你的用户名:')
    pwd = input('请输入你的密码:')
    with open('list_of_info',mode='r+',encoding='utf-8') as f1:
        for line in f1:
            lis.append(line)
    if usn == lis[0].strip() and pwd == lis[1].strip():
        print('登录成功')
        break
    else:print('账号和密码错误')
    i+=1

修改文件内容

with open('fan','r',encoding='utf-8') as f,open('fan.bak','w',encoding='utf-8') as f2:
    for line in f:
        if '黄曼' in line:
            line = line.replace('黄曼','香儿')    #把黄曼替换成香儿
        f2.write(line)
import os
os.remove('fan')
os.replace('fan.bak','fan')

按要求完成下列转化

list3 = [
    {"name": "alex", "hobby": "抽烟"},
    {"name": "alex", "hobby": "喝酒"},
    {"name": "alex", "hobby": "烫头"},
    {"name": "alex", "hobby": "Massage"},
    {"name": "wusir", "hobby": "喊麦"},
    {"name": "wusir", "hobby": "街舞"},
]
# 如何把上面的列表转换成下方的列表?
list4 = [
    {"name": "alex", "hobby_list": ["抽烟", "喝酒", "烫头", "Massage"]},
    {"name": "wusir", "hobby_list": ["喊麦", "街舞"]},
]
#####==============#####
list4 = [{'name':None,'hobby':[]},{'name':None,'hobby':[]}]
for i in list3:
    for k,v in i.items():
        if v == 'alex':
            list4[0]['name'] = v
            list4[0]['hobby'].append(i['hobby'])
        if v == 'wusir':
            list4[1]['name'] = v
            list4[1]['hobby'].append(i['hobby'])
print(list4)

输出一个随机6位数的密码。

import random
####1.只有数字=========================
code = ""
for i in range(6):
    add_num = random.randrange(10)
    code+=str(add_num)
print(code)
####2.只有字母=======================
import string
#s = string.ascii_lowercase  # 所有小写字母(a-z)
s=string.ascii_letters #所有大小写字母(a-z,A-Z)
# s=string.ascii_uppercase #所有大写字母(A-Z)
a = ''
for i in range(6):
    r = random.choice(s)
    a += r
print(a)
####3.字母和数字混合的随机验证码==============
#大写字母 chr(random.randrange(65,91))
#小写字母 chr(random.randrange(97,123))
def v_code():
    code1 = ""
    for i in range(6):
        add=random.choice([random.randrange(10),chr(random.randrange(65,91)),chr(random.randrange(97,123))])
        code+=str(add)
    print(code1)
v_code()

生成某年的所有日期

import time
def dateRange(year):
    fmt = '%Y-%m-%d'
    bgn = int(time.mktime(time.strptime(year+'-01-01',fmt)))
    end = int(time.mktime(time.strptime(year+'-12-31',fmt)))
    list_date = [time.strftime(fmt,time.localtime(i)) for i in range(bgn,end+1,3600*24)]
    return [i.replace('-','') for i in list_date]

print(dateRange('1991'))

求输入数字的平方,如果平方运算后小于 50 则退出。

T = True
while T:
    inp = input("请输入:")
    if inp.isdigit():
        c = int(inp) * int(inp)
        if c > 50:
            print(c)
            T = True
        else:
            print(c)
            T = False
    else:
        print("请输入数字")

两个变量值互换。

def exchange(a,b):
    a,b = b,a
    return a,b
a = 12
b = 23
print(exchange(a,b))

数字比较。

def compare(i,j):
    if i > j:
        print('{} 大于 {}'.format(i, j))
    elif i < j:
        print('{} 小于 {}'.format(i, j))
    elif i == j:
        print('{} 小于 {}'.format(i, j))
    else:
        print('输入错误')
sumber = input('请输入2个数字用空格隔开:')
if ' ' in sumber:
    try:
        a, b = sumber.split(' ')
        if a.isdigit() and b.isdigit():
            compare(a,b)
        else:
            print("请输入数字")
    except Exception as error:
        print('输入有误')
else:
    print('请用空格分开')

编写装饰器,为多个函数加上认证功能。

要求只登陆成功一次,后续函数都无需在输入用户名

flag = False
def login(func):
    def inner(*args,**kwargs):
        global flag
        if flag == True:
            ret = func(*args,**kwargs)
            return ret
        else:
            user = input('username:')
            pawd = input("密码:")
            if user == 'fana' and pawd == '123456':
                flag = True
                ret = func(*args,**kwargs)
                return ret
            else:
                print('登陆失败')
    return inner

@login
def shoplist_add():
    print("购买一件商品")
@login
def shoplist_del():
    print("别要了")

shoplist_add()
shoplist_add()
shoplist_del()
shoplist_add()
shoplist_del()

编写装饰器,为多个函数加上记录调用功能,

要求每次调用都将被调用的函数名写入文件

def func_log(fun):
    def inner(*args,**kwargs):
        ret = fun(*args,**kwargs)
        with open("file.txt",'a+',encoding='UTF-8') as f1:
            f1.write(fun.__name__+'\n')
        return ret
    return inner

@func_log
def func():
    print('func')
@func_log
def fana():
    print('fana')

编写下载网页内容的函数

要求功能:输入一个url,函数返回下载页面的结果,

然后为刚刚的函数编写装饰器,实现下载的网页存放在文件中,如果文件内有值(文件大于0)就优先从文件读取,否则就去下载

import requests,os
def cache(func):
    def inner(*args,**kwargs):
        a = args[0][11:-4]
        ret = func(*args,**kwargs)
        if not os.path.exists(a):            #没有这个文件就写
            with open(a,'w',encoding='utf-8') as f:
                f.write(ret)
            return ret
        elif os.path.getsize(a):            #文件大于0 就读文件
            with open(a,'r',encoding='utf-8') as f:
                return f.readlines()
        else:                                #如果有文件,但是0k 就重新写
            with open(a,'w',encoding='utf-8') as f:
                f.write(ret)
            return ret

    return inner

@cache
def user_url(url):
    res = requests.get(url)
    res.encoding = 'utf-8'
    return res.text

print(user_url('http://www.baidu.com'))
print(user_url('http://www.qq.com'))

处理文件

用户指定要查找的文件和内容,将文件中包含要查找内容的每一行都输出到屏幕

def check_file(filename,aim):
    with open(filename,encoding='utf-8') as f:   #句柄 : handler,文件操作符,文件句柄
        for i in f:
            if aim in i:
                yield i

g = check_file('fana','生成器')
for i in g:
    print(i.strip())

写生成器

从文件中读取内容,在每一次读取到的内容之前加上‘***’之后再返回给用户

 def check_file(filename):
     with open(filename,encoding='utf-8') as f:   #句柄 : handler,文件操作符,文件句柄
         for i in f:
             yield '***'+i

 for i in check_file('fana'):
     print(i.strip())

现有两个元组(('a'),('b')),(('c'),('d'))

请使用python中匿名函数生成列表[{'a':'c'},{'b':'d'}]

a = (('a'),('b'))
b = (('c'),('d'))
#1.用函数最简单的做法
dic = {}
# def func():
#     for i in zip(a,b):
#         dic[i[0]] = i[1]
#     print(dic)
# func()
#2.用到匿名函数,这样做肯定不行.所以用到map,就变成这样
def func(tup):
    return {tup[0]:tup[1]}
print(list(map(func,zip(a,b))))

#3.转成匿名函数。
res = map(lambda tup: {tup[0]: tup[1]}, zip(a, b))
print(list(res))

用map来处理字符串列表,把列表中的所有人都变成sb,比如:alex_sb

name = ["alex","wupeiqi","yuanhao","nezha"]
a = map(lambda i: i + '_sb', name)
for j in a:
    print(j)

用filter函数处理数字列表,将列表中所有的偶数筛选出来

num = [1,2,3,4,5,6,7,8]
ret = filter(lambda i : i % 2 == 0,num)
print(list(ret))

#a = lambda i: [j for j in i if j % 2 == 0]
#print(a(num))

运行程序将内容分页存储,每页5条,然后接收用户输入的页码,仅输入当页内容。

with open('fan','r',encoding='utf-8') as f:
    li = f.readlines()
inp = int(input("请输入页码:"))
page,yu = divmod(len(li),5)
if inp > page+1 or inp <= 0:
    print('输入错误')
else:
    if inp == page+1:
        for i in li[-yu:]:
            print(i.strip())
    else:
        for i in range((inp-1)*5,inp*5):
            print(li[i].strip())

用递归方式查找如下列表中66的位置

l = [2,3,5,10,15,16,18,22,26,30,32,35,41,42,43,55,56,66,67,69,72,76,82,83,88]

def find(lis,sumber,start=0,end=None):
    end = len(lis) if end is None else end
    aim = (end - start) // 2 + start
    if start > end or sumber > lis[-1]:
        return '%s 不在列表中。' % sumber
    else:
        if lis[aim] > sumber:
            return find(lis,sumber,start=start,end=aim-1)
        elif lis[aim] < sumber:
            return find(lis, sumber, start=aim+1, end=end)
        else:
            return '%s 的索引是 %s.' % (lis[aim],aim)

print(find(l,66))
#print(l.index(66))

画图,学用circle画圆形

import tkinter

canvas = tkinter.Canvas(width=600, height=600, bg='yellow')
canvas.pack(expand=tkinter.YES, fill=tkinter.BOTH)
k = 1
j = 1
for i in range(0, 26):
    canvas.create_oval(310 - k, 250 - k, 310 + k, 250 + k, width=1)
    k += j
    j += 0.3

tkinter.mainloop()

画图,学用line画直线。

import tkinter

canvas = tkinter.Canvas(width=300, height=300, bg='green')
canvas.pack(expand=tkinter.YES, fill=tkinter.BOTH)
x0 = 263
y0 = 263
y1 = 275
x1 = 275
for i in range(19):
    canvas.create_line(x0, y0, x0, y1, width=1, fill='red')
    x0 = x0 - 5
    y0 = y0 - 5
    x1 = x1 + 5
    y1 = y1 + 5

x0 = 263
y1 = 275
y0 = 263
for i in range(21):
    canvas.create_line(x0, y0, x0, y1, fill='red')
    x0 += 5
    y0 += 5
    y1 += 5

tkinter.mainloop()

###-----------------------------------------------------------
import turtle
def drawline(n):
    t=turtle.Pen()
    t.color(0.3,0.8,0.6)  #设置颜色,在0--1之间
    t.begin_fill()   #开始填充颜色
    for i in range(n): #任意边形
        t.forward(50)
        t.left(360/n)
    t.end_fill()    #结束填充颜色

drawline(8)

###--------------------------------------------------
from tkinter import *
canvas=Canvas(width=300,height=300,bg='white')
canvas.pack(expand=YES, fill=BOTH)
x1,y1=50,20
x2,y2=100,20
x3,y3=75,40
x4,y4=75,100
canvas.create_line(x1,y1,x3,y3, width=3, fill='red')
canvas.create_line(x2,y2,x3,y3, width=3, fill='red')
canvas.create_line(x1,y1,x4,y4, width=3, fill='red')
canvas.create_line(x2,y2,x4,y4, width=3, fill='red')
mainloop()

画图,学用rectangle画方形。

if __name__ == '__main__':
    from tkinter import *

    root = Tk()
    root.title('Canvas')
    canvas = Canvas(root, width=400, height=400, bg='yellow')
    x0 = 263
    y0 = 263
    y1 = 275
    x1 = 275
    for i in range(19):
        canvas.create_rectangle(x0, y0, x1, y1)
        x0 -= 5
        y0 -= 5
        x1 += 5
        y1 += 5

    canvas.pack()
    root.mainloop()

画图,五星红旗

import turtle

turtle.speed(10)
turtle.hideturtle()  #隐藏图标
turtle.pencolor("red")

#外框
turtle.penup()
turtle.goto(-300, 200)
turtle.pendown()
turtle.begin_fill()
turtle.fillcolor("red")
turtle.fd(600)
turtle.right(90)
turtle.fd(400)
turtle.right(90)
turtle.fd(600)
turtle.right(90)
turtle.fd(400)
turtle.right(90)
turtle.end_fill()

turtle.pencolor("yellow")

#大星星
turtle.penup()
turtle.goto(-275, 115)
turtle.pendown()
turtle.begin_fill()
turtle.fillcolor("yellow")
turtle.forward(90)
turtle.right(144)
turtle.forward(90)
turtle.right(144)
turtle.forward(90)
turtle.right(144)
turtle.forward(90)
turtle.right(144)
turtle.forward(90)
turtle.end_fill()

#小星星1
turtle.seth(0)
turtle.left(25)
turtle.penup()
turtle.goto(-187, 169)
turtle.pendown()


turtle.begin_fill()
turtle.fillcolor("yellow")
turtle.forward(30)
turtle.right(144)
turtle.forward(30)
turtle.right(144)
turtle.forward(30)
turtle.right(144)
turtle.forward(30)
turtle.right(144)
turtle.forward(30)
turtle.end_fill()

#小星星2
turtle.penup()
turtle.goto(-275, 115)
turtle.pendown()
turtle.seth(0)
turtle.left(21)
turtle.penup()
turtle.goto(-147, 133)
turtle.pendown()

turtle.begin_fill()
turtle.fillcolor("yellow")
turtle.forward(30)
turtle.right(144)
turtle.forward(30)
turtle.right(144)
turtle.forward(30)
turtle.right(144)
turtle.forward(30)
turtle.right(144)
turtle.forward(30)
turtle.end_fill()

#小星星3
turtle.penup()
turtle.goto(-275, 115)
turtle.pendown()
turtle.seth(0)
turtle.right(21)
turtle.penup()
turtle.goto(-147, 93)
turtle.pendown()


turtle.begin_fill()
turtle.fillcolor("yellow")
turtle.forward(30)
turtle.right(144)
turtle.forward(30)
turtle.right(144)
turtle.forward(30)
turtle.right(144)
turtle.forward(30)
turtle.right(144)
turtle.forward(30)
turtle.end_fill()

#小星星4
turtle.penup()
turtle.goto(-275, 115)
turtle.pendown()
turtle.seth(0)
turtle.right(25)
turtle.penup()
turtle.goto(-187, 41)
turtle.pendown()


turtle.begin_fill()
turtle.fillcolor("yellow")
turtle.forward(30)
turtle.right(144)
turtle.forward(30)
turtle.right(144)
turtle.forward(30)
turtle.right(144)
turtle.forward(30)
turtle.right(144)
turtle.forward(30)
turtle.end_fill()

画图,综合例子

from tkinter import *

canvas = Canvas(width=300, height=300, bg='green')
canvas.pack(expand=YES, fill=BOTH)
x0 = 150
y0 = 100
canvas.create_oval(x0 - 10, y0 - 10, x0 + 10, y0 + 10)
canvas.create_oval(x0 - 20, y0 - 20, x0 + 20, y0 + 20)
canvas.create_oval(x0 - 50, y0 - 50, x0 + 50, y0 + 50)
import math

B = 0.809
for i in range(16):
    a = 2 * math.pi / 16 * i
    x = math.ceil(x0 + 48 * math.cos(a))
    y = math.ceil(y0 + 48 * math.sin(a) * B)
    canvas.create_line(x0, y0, x, y, fill='red')
canvas.create_oval(x0 - 60, y0 - 60, x0 + 60, y0 + 60)

for k in range(501):
    for i in range(17):
        a = (2 * math.pi / 16) * i + (2 * math.pi / 180) * k
        x = math.ceil(x0 + 48 * math.cos(a))
        y = math.ceil(y0 + 48 + math.sin(a) * B)
        canvas.create_line(x0, y0, x, y, fill='red')
    for j in range(51):
        a = (2 * math.pi / 16) * i + (2 * math.pi / 180) * k - 1
        x = math.ceil(x0 + 48 * math.cos(a))
        y = math.ceil(y0 + 48 * math.sin(a) * B)
        canvas.create_line(x0, y0, x, y, fill='red')
mainloop()

画图:画出椭圆

from tkinter import *

x = 360
y = 160
top = y - 30
bottom = y - 30

canvas = Canvas(width=400, height=600, bg='white')
for i in range(20):
    canvas.create_oval(250 - top, 250 - bottom, 250 + top, 250 + bottom)
    top -= 5
    bottom += 5
canvas.pack()
mainloop()

打印出杨辉三角形(要求打印出20行)

# 杨辉三角是(a+b)的n次方展开后各项的系数,各行第一个数和最后一个数都是1,从第三行起第一个数和最后一个数外,其余各数是上一行同列和前一列两数之和
# 可以这样表示  li[i][j]=li[i-1][j]+li[i-1][j-1]
li = []
# 首先添加一个列表,每个列表有20个元素
for i in range(20):
    li.append([])
    for j in range(20):
        li[i].append(0)
# 让前后都是1
for a in range(20):
    li[a][0] = 1
    li[a][a] = 1
# 从第三行开始,中间数都是前个列表同列的和
for k in range(20):
    for u in range(1,k):
        li[k][u] = li[k-1][u] + li[k-1][u-1]
# 最后打印出来每个列表的值
for i in range(20):
    for j in range(i+1):
        print(li[i][j],end=' ')
    print()

输入3个数a,b,c,按大小顺序输出

def bijiao(*args):
    args = list(args)
    for i in range(1,len(args)):
        for j in range(len(args)-i):
            if args[j] > args[j+1]:
                temp = args[j]
                args[j] = args[j+1]
                args[j + 1] = temp
    return args

print(bijiao(12,56,34))

最大的与第一个元素交换,然后最小的与最后一个元素交换。

li = [18,13,9,2,22,1,23,10]

def large(arg):
    max = 0
    for i in range(1,len(arg)):
        if arg[i] > arg[max]:
            max = i
    arg[max],arg[0] = arg[0],arg[max]
    min = 0
    for j in range(1,len(arg)):
        if arg[j] < arg[min]:
            min = j
    arg[min],arg[-1] = arg[-1],arg[min]
print(li)
large(li)
print(li)

有n个数,使其前面各数顺序向后移m个位置,最后m个数变成最前面的m个数。

def move(li,m):
    for i in range(1,m+1):
        li.insert(0,li[-i])
    for j in range(m):
        del li[-1]
#### ====================####
def remove(li,m):
    n = len(li)
    end = li[-1]
    for i in range(n-1,-1,-1):
        li[i] = li[i-1]
    li[0] = end
    m -=1
    if m >0:
        move(li,m)
lis = [2, 8, 6, 1, 78, 45, 34, 9]
print(lis)
move(lis,5)
print(lis)

从第一个人开始报数(从1到3报数),凡报到3的人退出圈子,问最后留下的是原来第几号的那位。

inp = int(input("请输入:"))
li = list(range(1,inp+1))

cou = 0
while len(li) > 1:
    li2 = li[:]         # 把原数组拷贝到新数组中,用于限制内层循环次数
    for i in range(len(li2)):
        cou += 1
        if cou % 3 == 0:        # 如果count能被3整除,则是报到3的人
            li.remove(li2[i])   # 把报到3的人移除原数组,进行下一次循环
print(li)

####-----------------------------
i = 0
k = 0
m = 0
while m < len(li) - 1:
    if li[i] != 0: k += 1
    if k == 3:
        li[i] = 0
        k = 0
        m += 1
    i += 1
    if i == len(li): i = 0
i =0

while li[i] == 0:i+=1
print(li[i])

编写input()和output()函数输入,输出5个学生的数据记录

N = 2
li = []
for i in range(N):
    li.append(['',[]])
print(li)
lis = ["班级","分数","电话"]
def stu_input(stu):
    for i in range(N):
        stu[i][0]=input("请输入 第%s个 学生信息。\n姓名:"%(i+1))
        for j in lis:
            if j == '班级':
                stu[i][1].append(input(j + ':'))
            else:
                stu[i][1].append(int(input(j+':')))

def stu_output(stu):
    for i in range(N):
        print('姓名:%-10s'%(stu[i][0]))
        v = (v for v in range(len(stu[i][1])))
        for k in lis:
            print('%s%s:%s'%(' '*4,k,stu[i][1][next(v)]))

stu_input(li)
print(li)
stu_output(li)

编写一个函数,输入n为偶数时,调用函数求1/2+1/4+...+1/n,当输入n为奇数时,调用函数1/1+1/3+...+1/n

def calc(n):
    cou = 0
    if n % 2 == 0:
        for i in range(2,n+1,2):
            cou += 1 / i
    else:
        for i in range(1,n+1,2):
            cou += 1 / i
    print(cou)

calc(4)

找出最大的数字

li = [12,32,14,23,1,88,67]
a = 0
for i in li:
    if a < i:
        a = i
print(a)
#----------------------------
person = {"li": 18,  "zhang": 2, "sun": 22,"wang": 50,}
b = 'li'
for k in person:
    if person[b] < person[k]:
        b = k
print(b,person[b])

五只猴子来分桃子

第一只猴子把这堆桃子平均分为五份,多了一个,这只猴子把多的一个扔入海中,拿走了一份。第二只猴子把剩下的桃子又平均分成五份,又多了一个,它同样把多的一个扔入海中,拿走了一份,第三、第四、第五只猴子都是这样做的,问海滩上原来最少有多少个桃子?

# 如果多了4个,那么没有桃子被扔入海中,所以最小应该是5**5-4
def fn(n):
    x = 5**n-4
    print(x)
fn(5)
##==参考菜鸟如下:=============================
i = 0
j = 1
x = 0
while (i < 5):
    x = 4 * j
    for i in range(0, 5):
        if (x % 4 != 0):
            break
        else:
            i += 1
        x = (x / 4) * 5 + 1
    j += 1
print(x)
## ==============================
num=int(input("输入猴子的数目:"))
def fn(n):
    if n==num:
        return(4*x)       #最后剩的桃子的数目
    else:
        return(fn(n+1)*5/4+1)
    
x=1
while 1:
    count=0
    for i in range(1,num):
        if fn(i)%4==0 :
            count=count+1
    if count==num-1:
        print("海滩上原来最少有%d个桃子" % int(fn(0)))
        break
    else:
        x=x+1
posted @ 2019-10-29 12:29  博客萨斯州  阅读(2064)  评论(0编辑  收藏  举报