运行后若输入:5
结果输出:
*
***
*****
***
*
# 方法一
def func(a):
x = a//2+1
i = 1
while i<=x:
print(" "*(x-i),end="")
print("*"*(i*2-1))
i+=1
j = i-2
while j>0:
print(" "*(x-j),end="")
print("*"*(j*2-1))
j-=1
# 方法二
def func2(a):
x=n//2+1
for i in range(1,n+1,2)
print(('*'*i).center(n))
for i in reversed(range(1,n-1,2)):
print(('*'*i).center(n))
n = eval(input())
func(n)
#func2(n)
【Python】center()居中填充
运行后若输入:
a1 &!%b2
结果输出:
(2,2,1,3)
送行后若输入:
Python3
则结果输出:
(6,1,0,0)
#方法一:
def func(s):
a = 0
b = 0
c = 0
d = 0
for i in s:
if i>='A' and i<='Z':
a+=1
elif i>='a' and i<='z':
a+=1
elif i>='0' and i<='9':
b+=1
elif i==' ':
c+=1
else:
d+=1
return (a,b,c,d)
#方法二:
def func2(s):
a = 0
b = 0
c = 0
d = 0
for i in s:
if i.isalpha():
a+=1
elif i.isnumeric():
b+=1
elif i.isspace():
c+=1
else:
d+=1
return (a,b,c,d)
s = input()
print(func(s))
print(func2(s))
运行后若输入:
1 7 2
贝结果输出:
1 2 7 & 7 2 1
运行后若输入:
5 2.8 1
贝结果输出:
1 2.8 5 & 5 2.8 1
def func(a):
s = a.split()
s.sort()
for i in s:
print(i,end=" ")
print("&",end=" ")
#s.sort(reverse=True)
#for i in s:
for i in reversed(s):
print(i,end=" ")
a = input()
func(a)
输入:2
结果输出:
def draw(n):
a,b,c,d = '+','-','|',' '
for i in range(n):
print(a,end='')
print(b*4,end='')
print(a)
for i in range(n):
for j in range(n):
print(c,end='')
print(d*4,end='')
print(c)
for j in range(n):
print(c,end='')
print(d*4,end='')
print(c)
for i in range(n):
print(a,end='')
print(b*4,end='')
print(a)
def draw2(n):
line = 3*n+1
for i in range(1,line+1):
if i%3 == 1:
print("+----"*n,end="")
print("+")
else:
print("| "*n,end="")
print("|")
n = eval(input())
#draw(n)
draw2(n)
运行后若输入:2020 10 8
则输出结果:2020-10-08
运行后若输入:2021 2 16 f2
则输出结果:February 16,2021
from datetime import datetime
def func(d,n="f1"):
if n=="f1":
print(d.strftime("%Y-%m-%d"))
if n=="f2":
print(d.strftime("%B %d,%Y"))
ls = input().split()
d = datetime(int(ls[0]),int(ls[1]),int(ls[2]))
if len(ls)==3:
func(d)
else:
func(d,ls[3])
编程:设计一个函数func(*a),该函数实现对任意个整数求平均并返回。
运行后若输入:2 4
则结果输出:3.0
运行后若输入:1 2 3
则结果输出:2.0
def func(*a):
sum=0
for i in a:
sum+=eval(i)
return sum/len(a)
ls = input().split()
print(func(*ls))
编程:设计一个函数fuxe (m),该凶数使用递归方法实现将一个十进制整数转换为二进制字符串并返回。
运行后若输入:250
则结果输出:11111010
运行后若输入:10
则结果输出:1010
def func(n):
s = ''
if n==0:
return s
else:
s = func(n//2)
return s+str(n%2)
#不使用递归
def func2(n):
s = bin(n)
return s[2:]
n = eval(input())
print(func(n))
#print(func2(n))