请问怎么用python里最简单的while loop完成这几个代码?
1.制作一简单的乘法表,并在输入-1时以“terminated”为结束语退出2.输入任意数并计算其阶乘,并在输入-1时以“terminated”为结束语退出3.判断输入数...
1.制作一简单的乘法表,并在输入-1时以“terminated”为结束语退出2.输入任意数并计算其阶乘,并在输入-1时以“terminated”为结束语退出3.判断输入数字是否为质数,并在输入-1时以“terminated”为结束语退出4.输入数值并进行连续加减运算,并在输入0时输出总和并退出
展开
1个回答
展开全部
只用while
def func1():
while True:
num = int(input('Enter a number: '))
if num == -1:
print('terminated')
break
for i in range(8):
print(f'{num} * {i+1} = {num*(i+1)}')
def func2():
while True:
num = int(input('Enter a number: '))
if num == -1:
print('terminated')
break
fact = 1
for i in range(1, num+1):
fact *= i
print(f'Factorial: {fact}')
def func3():
while True:
num = int(input('Enter a number: '))
if num == -1:
print('terminated')
break
for i in range(2, int(num ** 0.5) + 1):
if num % i == 0:
print('no')
break
else:
print('yes')
def func4():
sum_num = 0
while True:
print(f'Current Sum: {sum_num}')
num = int(input('Number? '))
if num == 0:
print(f'Total Sum = {sum_num}')
return
sum_num += num
func1()
func2()
func3()
func4()
更好一点
def keep_go(f):
def new_f(*args, **kwargs):
while True:
res = f(*args, **kwargs)
if res is not None:
print(res)
break
return new_f
@keep_go
def func1():
num = int(input('Enter a number: '))
if num == -1:
return 'terminated'
for i in range(8):
print(f'{num} * {i+1} = {num*(i+1)}')
@keep_go
def func2():
num = int(input('Enter a number: '))
if num == -1:
return 'terminated'
fact = 1
for i in range(1, num+1):
fact *= i
print(f'Factorial: {fact}')
@keep_go
def func3():
num = int(input('Enter a number: '))
if num == -1:
return 'terminated'
for i in range(2, int(num ** 0.5) + 1):
if num % i == 0:
print('no')
break
else:
print('yes')
def func4(sum_num=0):
print(f'Current Sum: {sum_num}')
num = int(input('Number? '))
if num == 0:
print(f'Total Sum = {sum_num}')
return
func4(sum_num + num)
func1()
func2()
func3()
func4()
本回答被提问者和网友采纳
已赞过
已踩过<
评论
收起
你对这个回答的评价是?
推荐律师服务:
若未解决您的问题,请您详细描述您的问题,通过百度律临进行免费专业咨询