条件可以在python范围内吗?

时间:2018-06-20 02:23:50

标签: python python-3.x

范围可以在python中有条件吗?例如,我想从位置0开始,但是我希望它一直运行到我的while语句执行完毕。

total = 0
num = int(input ( "Enter a number: " ))
range[0,while num != 0:]
total += num

我希望能够在while循环中保存不同的变量。 我的程序的目的是打印您输入的数字总和,直到您输入0

我的代码

num = int(input ( "Enter a number: " )) #user input
number_enterd = str() #holds numbers enterd
total = 0 #sum of number

while num != 0:
    total += num

    num = int(input ( "Enter a number: " ))

    number_enterd = num


print( "Total is =", total ) 
print(number_enterd) #check to see the numbers ive collected

预期输出: 输入一个整数(0到结尾):10 1 + 2 + 3 + 4 + 5 + 6 + 7 + 8 + 9 + 10 = 55


截至目前,我正在尝试弄清楚如何存储不同的变量,以便在显示总计之前可以打印它们。但由于它处于循环状态,因此变量一直被覆盖到最后。

3 个答案:

答案 0 :(得分:0)

我用一个布尔值退出循环

def add_now():
    a = 0
    exit_now = False
    while exit_now is False:
        user_input = int(input('Enter a number: '))
        print("{} + {} =  {} ".format(user_input, a, user_input + a))
        a += user_input
        if user_input == 0:
            exit_now = True
    print(a)


add_now()

答案 1 :(得分:0)

如果要存储输入的所有数字,则在Python中执行此操作的最简单方法是仅使用列表。这是给您代码的概念,并做了一些修改:

num = int(input ( "Enter a number: " )) #user input
numbers_entered = [] #holds numbers entered
total = 0 #sum of number

while num != 0:
    total += num
    numbers_entered.append(num)
    num = int(input ( "Enter a number: " ))


print("Total is = " + str(total)) 
print(numbers_entered) #check to see the numbers ive collected

要获得这些数字的任何所需格式,只需使用与上面一行相同的字符串串联来修改最后一个打印语句。

答案 2 :(得分:0)

如果要存储所有输入的值然后打印它们,则可以使用列表。您的代码将像这样结束:

#number_enterd = str() # This is totally unnecessary. This does nothing

num = int(input ( "Enter a number: " ))
total = 0 #sum of number
numsEntered = [] # An empty list to hold the values we will enter
numsEntered.append(num) # Add the first number entered to the list
while num != 0:
    total += num
    num = int(input ( "Enter a number: " ))

    #number_enterd = num # Unnecesary as well, this overwrites what you wrote in line 2
                         # It doesn't even make the num a string

    numsEntered.append(num) #This adds the new num the user just entered into the list


print("Total is =", total )
print("Numbers entered:", numsEntered) #check to see the numbers you've collected

例如,用户输入num输入请求中的输入5,2,1,4,5,7,8,0。 您的输出将是:

>>>Total is = 32
>>>Numbers entered: [5, 2, 1, 4, 5, 7, 8, 0]

仅作为指导,这就是我的做法。希望对您有所帮助:

num = int(raw_input("Enter a number: "))
numsEntered = [] # An empty list to hold the values we will enter
total = 0 #sum of numbers
while True:
    numsEntered.append(num) #This adds the num the user just entered into the list
    total += num
    num = int(raw_input("Enter a number: "))

print("Total is =", total)
print("Numbers entered:", numsEntered) #check to see the numbers you've collected

在这种情况下,不会显示最后输入的0以退出循环。至少,我不希望它出现,因为它不会增加总和。 希望你喜欢我的答案!祝你有美好的一天:)