- 题目:输入一行字符,分别统计出其中英文字母、空格、数字和其它字符的个数。
读入的时候是一个字符串,要将字符串每一个字符逐个读入。
str = input('输入一个字符串:')
words = []
for word in str:
words+=word
letters = 0
space = 0
digit = 0
signal = 0
for i in range(0,len(words)):
if "0"<=words[i]<="9":
digit+=1
elif "a"<=words[i]<="z" or "A"<=words[i]<="Z":
letters+=1
elif words[i]==" ":
space+=1
else:
signal+=1
print("英文字符个数:",letters," 空格个数:",space," 数字字数:",digit," 其他字符个数:",signal)
- 题目:求s=a+aa+aaa+aaaa+aa…a的值,其中a是一个数字。例如2+22+222+2222+22222(此时共有5个数相加),几个数相加由键盘控制。
n = int(input('input the number of intengers:'))
a = int(input('input the number:'))
l = [a]
sum = a
ten = 1
for i in range(1,n):
ten = ten*10
l.append(l[i-1]+a*ten)
sum+=l[i]
print(l)
print(sum)
- 题目:一个数如果恰好等于它的因子之和,这个数就称为"完数"。例如6=1+2+3.编程找出1000以内的所有完数。
l = []
for n in range(1,1001):
sum = 1
for i in range(2,n):
if n%i==0:
sum+=i
if sum == n:
l.append(n)
print(l)
- 题目:求1+2!+3!+…+20!的和。
关键:如何写阶乘
方法一:循环
s = 0
l = range(1,21)
def op(x):
r = 1
for i in range(1,x + 1):
r *= i
return r
s = sum(map(op,l))
print ('1! + 2! + 3! + ... + 20! = %d' % s)
方法二:递归
def fact(j):
sum = 0
if j == 0:
sum = 1
else:
sum = j * fact(j - 1)
return sum
s=0
def fact(n):
if n==1:
return 1
return n*fact(n-1)
for n in range(1,21):
a=fact(n)
s+=a
print(s)
- 列表逆序输出
list = [1,2,3,4,5]
list.reverse()
print(list)
a = ['one', 'two', 'three']
for i in a[::-1]:
print (i)
- 求1~100内的素数(质数)
for n in range(2,100):
for i in range(2,n):
if n%i==0:
break
else:
print(n,end=' ')