阶乘
方法一:利用循环方法 #!/usr/bin/env python
# coding:utf-8
def fact(n):
total = 1
if n == 0:
total = 1
else:
for i in range(1,n+1):
total *= i
return total
while True:
n = input("Please input a int number(n>0): ")
if not n.isnumeric() or int(n) < 0:
print("Please input a number!")
continue
n = int(n)
result = fact(n)
print("{}!={}".format(n,result))
break
方法二:利用闭包函数 #!/usr/bin/env python
# coding:utf-8
def fact(n):
total = 1
if n == 0:
return total
return n * fact(n-1)
while True:
n = input("Please input a int number(n>0): ")
if not n.isnumeric() or int(n) < 0:
print("Please input a number!")
continue
n = int(n)
result = fact(n)
print("{}!={}".format(n,result))
break
统计字符串中字符和数字的个数 #!/usr/bin/env python
# coding:utf-8
status = 1
while status:
string = input("Please input a string including numbers and strings or other special symbols(input 'quit' to quit): ")
if string == "quit":
exit(1)
digit = alpha = space = other = 0
for i in string:
if i.isdigit():
digit += 1
elif i.isalpha():
alpha += 1
elif i.isspace():
space += 1
else:
other += 1
print("数字:%d"%digit)
print("字母:%d"%alpha)
print("空格:%d"%space)
print("其它:%d"%other)
乘法表 #!/usr/bin/env python
# coding:utf-8
for i in range(1,10):
for j in range(1,i+1):
print("{}X{}={}".format(j,i,i*j),end=" ")
print()