如何循环这个Python脚本?

1 投票
2 回答
28959 浏览
提问于 2025-04-17 13:00

我有一个作业,内容是...

创建一个条件循环,要求用户输入两个数字。然后把这两个数字相加,并显示结果。循环还要询问用户是否想要再进行一次操作。如果用户想,那就重复这个循环;如果不想,就结束循环。

这是我目前写的代码...

n1=input('Please enter your first number: ')
print "You have entered the number ",n1,""
n2=input('Pleae enter your second number: ')
print "You have entered the number ",n2,""
total=n1+n2
print "I will now add your numbers together."
print "The result is:",total

y = raw_input('Would you like to run the program again? y=yes n=no')
print'The program will now terminate.'

y='y'
while y=='y':
print 'The program will start over.'

当你运行这个程序时,第一部分会正常工作,但当它询问你是否要重新开始时,它会一直显示“程序将重新开始。”

我该如何让用户输入他们是否想重新开始程序,并且怎么写才能让它循环呢?

2 个回答

1

你需要把 while y=='y' 放在你脚本的开头。

虽然我不认为 y 是一个可以是 'n''y' 的变量,
举个例子:

def program():
    n1 = input('Please enter your first number: ')
    print "You have entered the number ",n1,""
    n2 = input('Pleae enter your second number: ')
    print "You have entered the number ",n2,""
    total = n1+n2
    print "I will now add your numbers together."
    print "The result is:",total


flag = True
while flag:
    program()
    flag = raw_input('Would you like to run the program again? [y/n]') == 'y'

print "The program will now terminate."

不过要说的是,如果用户输入的不是 'y',这样做会让程序结束。

4

你把循环放错地方了。应该像这样做:

y = 'y'

while y == 'y':
    # take input, print sum
    # prompt here, take input for y

一开始y的值是'y',所以程序会进入循环。第一次输入后,提示用户再输入一次y。如果他们输入'y',那么循环会再次执行;否则,循环就会结束。

另一种方法是创建一个无限循环,如果输入的不是'y',就跳出这个循环。可以这样做:

while True:
    # take input, print sum
    # prompt here, take input for y
    # if y != 'y' then break

撰写回答