欢迎来到 SO!
您的想法通常是正确的,以下是您可以如何将其转换为代码的方法。
x_total = 0
y_total = 0
while True:
first_input = input('Enter the next value of x: ')
if first_input == 'add':
break
x_total += float(first_input)
second_input = input('Enter the next value of y: ')
if second_input == 'add':
break
y_total += float(second_input)
print('x = ', x_total)
print('y = ', y_total)
请注意,在 Python 中,我们可以通过将类型 float 称为 number = float(number_string ) 来将字符串 number_string = '1239' 转换为浮点数。对于整数,这同样适用于 int。 documentation 包含有用的食谱和使用示例,通常是我不确定自己需要什么时开始的地方。
既然您提到您是 Python 新手,那么我要提一下,与其他语言相比,Python 中存在强大的习语。 Zen of Python 是对这个想法的一种介绍。询问“这是 Pythonic 吗?”通常很有用。当你第一次开始时,因为可能有既定的方法来做你正在做的任何事情,这些方法会更清晰,更不容易出错,并且可能运行得更快。
slide deck 很好地介绍了一些 Pythonisms,它是为 Python 2.x 量身定制的,因此一些语法有所不同,但这些想法在 3.x 中同样适用。
满足您原始请求的更 Pythonic(尽管对于新 Python 用户可能不太容易理解的方式)是使用任何意外值或转义字符来退出添加过程。
x_total = 0
y_total = 0
while True:
try:
first_input = input('Enter the next value of x: ')
x_total += float(first_input)
second_input = input('Enter the next value of y: ')
y_total += float(second_input)
except (ValueError, EOFError):
break
except KeyboardInterrupt:
print()
break
print('x =', x_total)
print('y =', y_total)
现在您的程序的用户可以键入任何非浮点值来退出,甚至可以使用键中断(例如 ctrl + Z 或 ctrl + C)。我在PowerShell中运行它给你一些使用示例:
退出,一个常见的成语:
Enter the next value of x: 1
Enter the next value of y: 2
Enter the next value of x: 3
Enter the next value of y: exit
x = 4.0
y = 2.0
您的原始案例,添加:
Enter the next value of x: 1
Enter the next value of y: 2
Enter the next value of x: 3
Enter the next value of y: add
x = 4.0
y = 2.0
使用 ctrl + Z:
Enter the next value of x: 1
Enter the next value of y: 2
Enter the next value of x: 3
Enter the next value of y: ^Z
x = 4.0
y = 2.0
使用 ctrl + C:
Enter the next value of x: 1
Enter the next value of y: 2
Enter the next value of x: 3
Enter the next value of y:
x = 4.0
y = 2.0