## Python3---练习题目

```#!/usr/bin/python
# -*- coding: UTF-8 -*-

'''
Python3 练习案例

'''

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)```

```#!/usr/bin/python
# -*- coding: UTF-8 -*-

'''

40万到60万之间时高于40万元的部分，可提成3%；60万到100万之间时，高于60万元的部分，可提成1.5%，高于100万元时，

'''

i = int(input("请输入净利润："))
arr = [1000000,600000,400000,200000,100000]
rat = [0.01,0.015,0.03,0.05,0.075,0.1]
r = 0
for idx in range(0,6):
if i > arr[idx]:
r += (i - arr[idx]) * rat[idx]
print( (i - arr[idx]) * rat[idx] )
i = arr[idx]
print(r)```

```#!/usr/bin/python
# -*- coding: UTF-8 -*-

'''

'''

import math
'''
math模块为浮点运算提供了对底层C函数库的访问:
1;sqrt() 方法返回数字x的平方根。
'''
for i in range(10000):
#将循环数值转化为整数型
x = int(math.sqrt(i + 100))
y = int(math.sqrt(i + 268))
if (x * x == i+ 100) and ( y * y == i + 268):
print(i)```

```#!/usr/bin/python
# -*- coding: UTF-8 -*-

'''

'''

year = int(input("请输入年份：\n"))
month = int(input("请输入月份：\n"))
day = int(input("请输入天数：\n"))

#Python的元组与列表类似，不同之处在于元组的元素不能修改。
months = (0,31,59,90,120,151,181,212,243,273,304,334)
if 0 < month < 12:
sun = months[month - 1]
else:
print("Date error")

sun += day
leap = 0
if (year % 400 == 0) or ((year % 4 == 0) and (year % 100 != 0)):
leap = 1
if (leap == 1) and (month > 2):
sun += 1

print("it is the %dth day." % sun)```

```#!/usr/bin/python
# -*- coding: UTF-8 -*-

'''

'''

l = []
for i in range(3):
x = int(input("integer: \n"))
l.append(x)
l.sort()
print(l)
'''
1；序列是Python中最基本的数据结构.
2；sort() 函数用于对原列表进行排序，如果指定参数，则使用比较函数指定的比较函数。
3；append()函数会将所有的参数视为一个列表元素插入到列表尾部
'''```

```#!/usr/bin/python
# -*- coding: UTF-8 -*-

'''

'''

def fib(n):
if n == 1 or n == 2:
return 1
return fib(n -1)+fib(n-2)

print(fib(10))```

```#!/usr/bin/python
# -*- coding: UTF-8 -*-

'''

'''

a = [1,3,'a',True]
b = a[:]
print(b)```

```#!/usr/bin/python
# -*- coding: UTF-8 -*-

'''

'''

for i in range(1,10):
for j in range(1,10):
result = i * j
print("%d * %d = % -3d" %(i,j,result))
print("")```

```#!/usr/bin/python
# -*- coding: UTF-8 -*-

'''

'''

import time
#dict.items返回可遍历的(键, 值) 元组数组。
MyD = {1:'A',2:'B'}
for key,value in dict.items(MyD):
print(key,value)
time.sleep(1) #暂停1秒```

```#!/usr/bin/python
# -*- coding: UTF-8 -*-

'''

'''

f1 = 1
f2 = 1

for i in range(1,21):
print("%12d %12d" % (f1,f2))
if (i % 2) == 0:
print("")
f1 = f1 + f2
f2 = f1 + f2```

```#!/usr/bin/python
# -*- coding: UTF-8 -*-

'''

'''

from math import sqrt
from sys import stdout
'''
1；sqrt() 方法返回数字x的平方根。
2；sys该模块提供对解释器使用或维护的一些变量的访问，以及与解释器强烈交互的函数。它始终可用。
3；stdout用于print()和表达式的输出和 提示input();
'''

h = 0
leap = 1
for m in range(101,201):
k = int(sqrt(m + 1))
for i in range(2,k+1):
if m % i == 0:
leap = 0
break
if leap == 1:
print("%-4d" % m)
h += 1
if h % 10 == 0:
print("")
leap = 1```

```#!/usr/bin/python
# -*- coding: UTF-8 -*-

'''

'''

for n in range(100,1000):
i = n / 100 # 提取百位数字
j = n / 10 % 10 # 提取出十位数字
k = n % 10 #提取个位数字
if n == i ** 3 + j ** 3 + k ** 3:
print(n)```

```#!/usr/bin/python
# -*- coding: UTF-8 -*-

'''

(1)如果这个质数恰等于n，则说明分解质因数的过程已经结束，打印出即可。
(2)如果nk，但n能被k整除，则应打印出k的值，并用n除以k的商,作为新的正整数你n,重复执行第一步。
(3)如果n不能被k整除，则用k+1作为k的值,重复执行第一步。
'''

from sys import stdout

n = int(input("input number: \n"))
print("n = %d" % n)

for i in range(2 , n + 1):
while n != i:
if n % i == 0:
stdout.write(str(i))
stdout.write("*")
n = n / i
else:
break
print("%d" % n)```

```#!/usr/bin/python
# -*- coding: UTF-8 -*-

'''

'''

score = int(input("input score: \n"))

if score >= 90:
elif score >= 60:
else:

print("%d belongs to %s " % (score,grade))```

第十五题：

```# -*- coding:utf-8 -*-
#!/usr/bin/python

import datetime

if __name__ == "__main__":
# 输出今日日期，格式为dd/mm/yyyy。 更多选项可以查看strftime()方法
print(datetime.date.today().strftime('%d/%m/%Y'))
# 创建日期对象
Date = datetime.date(1941,1,5)
print(Date.strftime('%d/%m/%Y'))
#日期算术运算
DateNext = Date + datetime.timedelta(days=4)
print(DateNext)
#日期替换
DateT = Date.replace(year=Date.year + 1)
print(DateT)```

```# -*- coding:utf-8 -*-
#!/usr/bin/python

import string

'''

'''
'''
Python标准库 - 文本处理服务 - string库
'''
if __name__ == "__main__":
s = str(input('input a string: \n'))
letters = 0
space = 0
digit = 0
others = 0
for c in s:
if c.isalpha():
letters += 1
elif c.isspace():
space += 1
elif c.isdigit():
digit += 1
else:
others += 1

print("char = %d\n space = %d\n digit = %d\n others = %d\n" % (letters,space,digit,others))```

```# -*- coding:utf-8 -*-
#!/usr/bin/python

'''

'''

Tn = 0
Sn = []

n = int(input('n = :\n'))
a = int(input('a = :\n'))

for count in range(n):
Tn = Tn + a
a = a * 10
Sn.append(Tn)
print(Tn)
#reduce() 函数会对参数序列中元素进行累积。
Sn = reduce(lambda x,y : x + y,Sn)
print(Sn)```

```# -*- coding:utf-8 -*-
#!/usr/bin/python

'''

'''

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])```

```# -*- coding:utf-8 -*-
#!/usr/bin/python

'''

'''

Sn = 100.0

Hn = Sn / 2

for n in range(2,11):
Sn += 2 * Hn
Hn /= 2

print("Total of road is %f" % Sn)
print("The tenth is %f meter" % Hn)```

```# -*- coding:utf-8 -*-
#!/usr/bin/python

'''

'''

x2 = 1

for day in range(9 , 0 , -1):
print(day)
x1 = (x2 + 1) * 2
x2 = x1

print(x1)```

第二十一题：

```#!/usr/bin/python
# -*- coding: UTF-8 -*-

'''

'''

'''
a 可能对应 y , z
c 对应 y  -----  a 对应 z ---- b 对应  x
'''
'''

1；ord() 函数是 chr() 函数（对于8位的ASCII字符串）或 unichr() 函数（对于Unicode对象）的配对函数，

2；chr() 用一个范围在 range（256）内的（就是0～255）整数作参数，返回一个对应的字符。

首先我们通过for 循环分别提取出代表三个x , y ,Z 不同的字母的变量，接下来我们根据条件（a说他不和x比，c说他不和x,z比）来设定if语句。
'''

for i in range(ord('x'),ord('z') + 1):
for j in range(ord('x'),ord('z') + 1):
if i != j:
for k in range(ord('x'),ord('z') + 1):
if(i != k) and (j != k):
if(i != ord('x')) and (k != ord('x')) and (k != ord('z')):
print("order is\n a -- %s\n b -- %s\n c -- %s" % (chr(i),chr(j),chr(k)))```

```#!/usr/bin/python
# -*- coding: UTF-8 -*-

'''

*
***
*****
*******
*****
***
*

'''

from sys import stdout

for i in range(4): #提取行数，i 分别表示 （0，1，2，3）
print(i)
for j in range(2 - i + 1):
stdout.write(' ')
for k in range(2 * i + 1):
stdout.write('*')
print

for i in range(3):
print(i)
for j in range(i + 1):
stdout.write(' ')
for k in range(4 - 2 * i + 1):
stdout.write('*')

print```

```#!/usr/bin/python
# -*- coding: UTF-8 -*-

'''

1；使用变量分别表示分子，分母。整个需要钱20项的和，那么分子，分母的规律变化需要循环20次。
2；前面想加的和设定一个变量存储他们的值
'''

a = 2.0
b = 1.0
s = 0

for i in range(1,21):
s += a / b
t = a
a = a + b
b = t
print(s)```

```#!/usr/bin/python
# -*- coding: UTF-8 -*-

'''

'''

n = 0
s = 0
t = 1

for n in range(1,21):
t *= n
s += t
print("1! + 2! + 3! + ... + 20! = %d" % s)```

第二十五题：

```#!/usr/bin/python
# -*- coding: UTF-8 -*-

'''

'''

def fact(j):
sum = 0
if j == 0:
sum = 1
else:
sum = j * fact(j - 1)
return sum

for i in range(5):
print("%d! = %d" % (i,fact(i)))```

```#!/usr/bin/python
# -*- coding: UTF-8 -*-

'''

'''

def output(s,l):
if l == 0:
return
print(s[l-1])
output(s,l-1)

s = input('Input a string : ')
l = len(s)
output(s,l)```

```#!/usr/bin/python
# -*- coding: UTF-8 -*-

'''

'''

def age(n):
if n == 1: c = 10
else:
c = age(n-1) + 2
return c

print(age(5))```

```#!/usr/bin/python
# -*- coding: UTF-8 -*-

'''

'''

x = int(input("请输入一个数：\n"))

a = x // 10000 # 提取第五位数字
b = x % 10000 // 1000 #提取第四位数字
c = x % 1000 // 100 # 提取第三位数字
d = x % 100 // 10 # 提取第二位数字
e = x % 10  # 提取第一位数字

if a != 0:
print("5位数：",e,d,c,b,a)
elif b != 0:
print("4位数：", e, d, c, b)
elif c != 0:
print("3位数：", e, d, c)
elif d != 0:
print("2位数：", e, d)
elif e != 0:
print("1位数：", e)```

```#!/usr/bin/python
# -*- coding: UTF-8 -*-

'''

12321
'''

a = int(input("请输入一个数字：\n"))
x = str(a)
flag = True

for i in range(len(x)//2):
if x[i] != x[-i - 1]:
flag = False
break

if flag:
print("%d 是一个回文数！" % a)
else:
print("%d 不是一个回文数！" % a)```

```#!/usr/bin/python
# -*- coding: UTF-8 -*-

'''

'''

# while letter  != 'Y':
if letter == 'S':
if letter == 'a':
print('Saturday')
elif letter == 'u':
print('Sunday')
else:
print('data error')

elif letter == 'F':
print('Friday')

elif letter == 'M':
print('Monday')

elif letter == 'T':

if letter == 'u':
print('Tuesday')
elif letter == 'h':
print('Thursday')
else:
print('data error')

elif letter == 'W':
print('Wednesday')
else:
print('data error')```

```#!/usr/bin/python
# -*- coding: UTF-8 -*-

'''

'''
'''

[ 1 2 3 4 5 ]
print(a[-1]) ###取最后一个元素
[5]
print(a[:-1])  ### 除了最后一个取全部
[ 1 2 3 4 ]
print(a[::-1]) ### 取从后向前（相反）的元素
[ 5 4 3 2 1 ]
print(a[2::-1]) ### 取从下标为2的元素翻转读取
[ 3 2 1 ]
'''

a = ['one', 213 , True ]
for i in a[::-1]:
print(i)```

```#!/usr/bin/python
# -*- coding: UTF-8 -*-

'''

1；Python join() 方法用于将序列中的元素以指定的字符连接生成一个新的字符串。
'''

L = [1,2,3,"ONE",True,{'A':123}]
S1 = ','.join(str(n) for n in L)
S2 = '666'.join(str(n) for n in L)
print(S1)
print(S2)```

```#!/usr/bin/python
# -*- coding: UTF-8 -*-

'''

'''

def hello_world():
print("hello world")

def three_hellos():
for i in range(3):
hello_world()

if __name__ == "__main__":
three_hellos()```

```#!/usr/bin/python
# -*- coding: UTF-8 -*-

'''

'''

class bcolors:
OKBLUE = '\033[94m'
OKGREEN = '\033[92m'
WARNING = '\033[93m'
FAIL = '\033[91m'
ENDC = '\033[0m'
BOLD = '\033[1m'
UNDERLINE = '\033[4m'

print(bcolors.WARNING + "警告的颜色字体？" + bcolors.ENDC)```

```#!/usr/bin/python
# -*- coding: UTF-8 -*-

'''

'''
from math import sqrt
'''

1；sqrt() 方法返回数字x的平方根。
'''
if __name__ == "__main__":
N = 100
a = range(0,N)
for i in range(2,int(sqrt(N))):
for j in range(i+1 , N):
if (a[i] != 0) and (a[j] != 0):
if a[i] % a[j] == 0:
a[j] = 0

print
for i in range(2,N):
if a[i] != 0:
print("%5d" % a[i])
if (i - 2) % 10 == 0:
print```

```#!/usr/bin/python
# -*- coding: UTF-8 -*-

'''

'''

if __name__ == "__main__":
N = 10
# input data
l = []
for i in range(N):
l.append(int(input("input a number:\n")))
print
for i in range(N):
print(l[i])
print

# sort tem num
for i in range(N - 1):
min = i
for j in range(i + 1 , N):
if l[min] > l[j] : min = j
l[i],l[min] = l[min],l[i]

print("after sorted")
for i in range(N):
print(l[i])```

```#!/usr/bin/python
# -*- coding: UTF-8 -*-

'''

'''

if __name__ == "__main__":
a = []
sum = 0.0
for i in range(3):
a.append([])
for j in range(3):
a[i].append(float(input("input num:\n")))
print(a)
for i in range(3):
sum += a[i][i]

print(sum)```

```#!/usr/bin/python
# -*- coding: UTF-8 -*-

'''

'''

if __name__ == "__main__":
# 方案一：
a = [1,2,3,4,5,6,7,8,9,0]
print("original list is:")
for i in range(len(a)):
print(a[i])

number = int(input("insert a new number: \n"))
end = a[9]
if number > end:
a.append(number)
#a[10] = number
else:
for i in range(10):
if a[i] > number:
temp1 = a[i]
a[i] = number
for j in range(i + 1, 11):
temp2 = a[j]
a[j] = temp1
temp1 = temp2
break

for i in range(11):
print(a[i])```

```#!/usr/bin/python
# -*- coding: UTF-8 -*-

'''

'''

if __name__ == "__main__":
a = [9,3,4,6,1]
N = len(a)

print(a)
for i in range(len(a) // 2):
a[i],a[N -i -1] = a[N -i -1],a[i]
print(a)```

第四十题：

```#！ /usr/bin/python
# -*- coding： UTF-8 -*-

'''

'''
def varfunc():
var = 0
print("var = %d" % var)
var += 1

if __name__ == "__main__":
for i in range(3):
varfunc()

#类的属性
#作为类的一个属性吧
class Static:
StaticVar = 5
def varfunc(self):
self.StaticVar += 1
print(self.StaticVar)

print(Static.StaticVar)
a = Static()
for i in range(3):
a.varfunc()```

```#！ /usr/bin/python
# -*- coding： UTF-8 -*-

'''

'''

num = 2
def autofunc():
num = 1
print("internal block num = %d" % num )
num += 1

for i in range(3):
print("The num = %d" % num)
num += 1
autofunc()```

```#！ /usr/bin/python
# -*- coding： UTF-8 -*-

'''

'''

class Num:
nNum = 1
def inc(self):
self.nNum += 1
print("nNum = %d" % self.nNum)

if __name__ == "__main__":
nNum = 2
inst = Num()
for i in range(3):
nNum += 1
print("The num = %d" % nNum)
inst.inc()

```

```#！ /usr/bin/python
# -*- coding： UTF-8 -*-

'''

'''

tmp = 0
for i in range(1,101):
tmp += i

print("The sum is %d" % tmp)```

```#！ /usr/bin/python
# -*- coding： UTF-8 -*-

'''

'''

TURE = 1
FALSE = 0
def SQ(x):
return x * x

print("如果输入的数字小于 50 ，程序将停止运行。")
again = 1
while again:
num = int(input("Please input number: "))
print("运算结果为%d" % (SQ(num)))
if num >= 50:
again = TURE
else:
again = FALSE```

```#！ /usr/bin/python
# -*- coding： UTF-8 -*-

'''

'''

def exchange(a,b):
a,b = b,a
return (a,b)

if __name__ == "__main__":
x = 10
y = 20
print("x = %d , y = %d" % (x,y))
x,y = exchange(x,y)
print("x = %d , y = %d" % (x,y))```

```#！ /usr/bin/python
# -*- coding： UTF-8 -*-

'''

'''

if __name__ == "__main__":
i = 10
j = 20
if i > j:
print("%d 大于 %d" % (i,j))
elif i == j:
print("%d 等于 %d" % (i, j))
elif i < j:
print("%d 小于 %d" % (i, j))
else:
print("未知")```

```#！ /usr/bin/python
# -*- coding： UTF-8 -*-

'''

'''

MAXIMUM = lambda x,y : (x > y) * x + (x < y) * y
MINIMUM = lambda x,y : (x > y) * y + (x < y) * x

if __name__ == "__main__":
a = 10
b = 20
print("The largar one is %d" % MAXIMUM(a,b))
print("The lower one is %d" % MINIMUM(a, b))```

```#！ /usr/bin/python
# -*- coding： UTF-8 -*-

'''

'''

import random

print(random.uniform(10,20))```

第四十九题：

```#！ /usr/bin/python
# -*- coding： UTF-8 -*-

'''

'''

if __name__ == "__main__":
a = 77
b = a & 3
print("a & b = %d" % b)
b &= 7
print("a & b = %d" % b)```