因此,我要创建的只是该程序的循环,这样它可以在不重新运行Shell的情况下多次使用,我还想学习如何在任何涉及函数的程序中执行此操作
一切
print('Welcome to the prime checker!')
num = int(input("Enter any number between 1 - 5000: "))
def is_prime(num):
if num > 1:
for i in range(2, num):
if (num % i) == 0:
print(num, "is not prime")
break
else:
print(num, "is prime")
else:
print(num, "is not a prime number")
is_prime(num)
def print_factors(num):
print("The factors of",num,"are:")
for i in range(1, num + 1):
if num % i == 0:
print(i)
print_factors(num)
def main():
choice = "y"
while choice.lower() == "y":
# get input
#num = int(input("Enter any number between 1 - 5000: "))
# see if the user wants to continue
choice = input("Repeat? (y/n): ")
print()
print("Bye!")
if __name__ == "__main__":
main()
print('Finished!')
我只希望它在您按y并重新运行整个程序(如第一次)时起作用
答案 0 :(得分:0)
结构化代码。创建功能。调用功能。尊重缩进。
def check_primes():
print('Welcome to the prime checker!')
num = int(input("Enter any number between 1 - 5000: "))
def is_prime(num):
# do checking -your current code makes not much sense
# and does not do what the methodnames imply
# see f.e. https://stackoverflow.com/questions/1801391/what-is-the-best-algorithm-for-checking-if-a-number-is-prime
print("Did prime checking")
def main():
choice = "y"
while choice.lower() == "y":
check_primes()
# see if the user wants to continue
choice = input("Repeat? (y/n): ")
if __name__ == "__main__":
main()