到目前为止,这是我的代码。我正在学习Python中的循环,并且想知道如果用户输入'y',我将如何重复此代码。
while True:
num1 = int(input('Please enter a number: '))
num2 = int(input('Please enter another number: '))
print('The two added together are: ', num1 + num2)
response = print('Would you like to see this again? (Enter "y" for yes): ')
答案 0 :(得分:0)
尝试以下方法:
response = 'y'
while response == 'y':
num1 = int(input("Please enter a number: "))
num2 = int(input("Please enter another number: "))
print("The two added together are: ", num1 + num2)
response = input("Would you like to see this again? (Enter 'y' for yes): ")
答案 1 :(得分:0)
有多种方法可以做到这一点。
两种常见的方法是初始化response = 'y'
并使while
循环while response == 'y': ...
或while True: ...
,如果你没有&while
循环#39; t从用户那里收到y
。你这样做是一个偏好的问题。我更喜欢后者,因为如果我不必这样做,我不想初始化变量,而且当有人正在阅读代码时,IMO会更清楚地发生了什么。
以下是一个例子:
Python 3.3.3 (v3.3.3:c3896275c0f6, Nov 18 2013, 21:19:30) [MSC v.1600 64 bit (AMD64)] on win32
Type "help", "copyright", "credits" or "license" for more information.
>>> while True:
... num1 = int(input('Please enter a number: '))
... num2 = int(input('Please enter a number: '))
...
... print('The two added together are: {}'.format(num1 + num2))
... response = input('Would you like to see this again? (Enter "y" for yes): ')
... if response.lower() != 'y':
... break
...
Please enter a number: 1
Please enter a number: 1
The two added together are: 2
Would you like to see this again? (Enter "y" for yes): y
Please enter a number: 3
Please enter a number: 5
The two added together are: 8
Would you like to see this again? (Enter "y" for yes): n
>>>
作为学生的进一步练习,将其重写为接受并添加一个一次输入的任意数量的整数,以空行结束。添加错误检查的加分点,以确保用户不输入字符串而不是数字。