【问题标题】:Sum of Numbers Exercise, Python 3数字总和练习,Python 3
【发布时间】:2013-11-06 11:56:19
【问题描述】:

任何帮助将不胜感激。我是新学习 Python。这是我必须完成的练习。我已经认真地投入了大约 3 到 4 个小时的时间,所以不用担心我“请别人为我做我的工作”。这是练习和我到目前为止所拥有的。在整个学习过程中,我一直对这些问题感到困惑并“破解”我的方式。如果您知道整个代码并且不介意包含它,我将非常感激。 练习:编写一个带有循环的程序,要求用户输入正数。用户应输入负数以表示系列结束。当用户结束程序(通过输入负数)时,应显示正数的总和。这是我目前所拥有的。

# The main function.
def main():
# Variable to control the outer loop.
another = 'y'
while another == 'y' or another == 'Y':
    numbers()
    another = input('Run this program again?\n\
Enter y for yes.')
def numbers():
positive = int(input('Enter a positive number: '))
while positive > 0:
positive = int(input('Enter a positive number, or enter a\n\
negative number to end and calculate the sum: '))
positive = int(input('Enter a positive number: '))
while positive < 0:
for i in range (positive):
    print(i)
# Call the main function.
main()

【问题讨论】:

  • 请说出问题所在。你的缩进正确吗?
  • 请重新格式化代码。我试图为你做到这一点,但未能欺骗它。顺便说一句,您不会将输入的数字存储在任何地方(例如输入值列表或累积总和会很方便)。另外,你知道range函数是做什么的吗?

标签: python sum


【解决方案1】:

怎么样:

# The main function.
def main():
  mysum = 0
  while True:
    positive = int(input('Enter a positive number, or enter a\n\
negative number to end and calculate the sum: '))
    if positive < 0:
      print mysum
      return
    mysum = mysum + positive

# Call the main function. 
main()

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2012-06-27
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-05-01
    • 1970-01-01
    • 2019-07-31
    相关资源
    最近更新 更多