在Python 3x中做

时间:2017-03-27 18:31:22

标签: python python-3.x while-loop do-while

晚上堆栈溢出。我是Python的初学者,这就是为什么我决定来这里寻求帮助的原因。具体来说,我无法理解“do-while循环”。

这是我给出的任务:

[设计允许用户输入数字的程序的逻辑。程序将显示从1到输入数字的每个数字的总和。该程序将允许用户连续输入数字,直到用户输入0。]

这是我的代码没有“Do-while循环”:

#Number Sum Conversion Calculator - V 0.0.1
#Author: Dena, Rene

print('Welcome to "Sum Conversion Calculator!"')
print('\nThis script will allow you to insert an integer and will thus display the total \ sum of the number you entered using summation methodology.')

print("\n Let's begin.")
name = input("In starting, what is your name?")

print('\n')
print("Hello %s. Let's get started." % (name))

base_number = 1
user_number = int(input("Insert your integer:"))

par = user_number + 1
n = user_number
num = 2

dom = par * n
answer = dom / num

print ("\n\nThe sum of the integer you entered is %s." % (answer))


print ('\nThank you for using "Number Sum Conversion Calculator". \
Please press ENTER to exit.')

效果很好。基本上做我想做的事。

现在,从作业中......它说:

  

该程序将允许用户连续输入数字,直到用户输入0。

所以这是我的代码/尝试:

#Number Sum Conversion Calculator - V 0.0.1
#Author: Dena, Rene

print('Welcome to "Sum Conversion Calculator!"')
print('\nThis script will allow you to insert an integer and will thus display \
the total sum of the number you entered using summation methodology.')

print("\n Let's begin.")
name = input("In starting, what is your name?")

print('\n')
print("Hello %s. Let's get started." % (name))

base_number = 1
user_number = int(input("Insert your integer:"))

def equation_run(EQ):
    par = user_number + 1
    n = user_number
    num = 2

    dom = par * n
    answer = dom / num

    print ("\n\nThe sum of the integer you entered is %s." % (answer))

zero = 0
while zero < user_number:
   print (equation_run)
elif zero == user_number:
    print ('Thank you for using "Number Sum Conversion Calculator". \
Please press ENTER to exit.')

运行此代码时,我收到语法错误。它突出显示了 elif 部分。我试过试错,但似乎无法让它工作。请帮忙。

任何意见/建议都将不胜感激。提前谢谢你,美好的一天。

2 个答案:

答案 0 :(得分:4)

if来自while,而不是if。将其替换为简单的while zero < user_number: ... if zero == user_number: ...

{{1}}

答案 1 :(得分:1)

类似的东西:

while True:
    number = int(input("Enter a number: "))
    if number == 0:
        break
    print(0.5*number*(number+1))

应该有效