在Python中查找变量总和

时间:2018-11-27 04:35:52

标签: python

我正在开发一个程序,要求用户输入一个数字,并将继续循环直到给出一个正数。当给出一个正数时,它将提醒用户并向他们显示其数字的总和。但是,我以为我已经正确编写了代码,但这给了我一个错误的答案。我做错了什么,该如何解决?

user_input = float(int(input("Please Enter Your Number:")))
s = 0

while user_input < 0:
  float(int(input("Please Enter Another Number: ")))
if user_input > 0:
  s += user_input%10
  user_input //= 10
  print("You've entered a positive number! The sum of the digits is: ", s)

4 个答案:

答案 0 :(得分:1)

四件事:

  1. 不确定为什么将输入存储为floatint就足够了。
  2. 如果输入为负,它将进入while循环。但是,在while循环中,您实际上并未将新输入分配给user_input。通过添加user_input =
  3. 来解决此问题
  4. while循环确保user_input> = 0,因此if user_input > 0:是不必要的。
  5. 可能最重要的是,要计算数字总和,您需要重复除法和求和,而不仅仅是执行一次。因此,添加一个while循环。

最终代码:

user_input = int(input("Please Enter Your Number: "))
s = 0

while user_input < 0:
    user_input = int(input("Please Enter Another Number: "))

while user_input:
    s += user_input % 10
    user_input //= 10

print("You've entered a positive number! The sum of the digits is: ", s)

答案 1 :(得分:0)

if语句通常用于确定是否应一次执行某事。

如果您要继续操作直到user_input变为零,则需要while

此外,我不确定您为什么将数字存储为float,尤其是无论如何,您都是通过int进行存储的。也可能只是int

此外,如果值实际上不是负数,实际上并没有将新值分配给变量,则您要循环输入该值。

您可能还希望简化print语句,以免在您要添加的循环的每次迭代中完成。


当然,有些人可能会建议采用一种 Pythonic 的方式来累加正数的数字很简单:

sum([int(ch) for ch in str(x)])

效果也一样,而不必担心显式循环。

答案 2 :(得分:0)

解决此问题的另一种方法是使用assert和一个函数:

def sum_num():
    # try get user input
    try:
        user_in = input('Enter Number: ')
        assert int(user_in) > 0

    except AssertionError:
        # we got invalid input
        sum_num()

    else:
        s_d = sum([int(i) for i in user_in])

        print('You\'ve entered a positive number! The sum of the digits is: ', s_d)

#run the function
sum_num()

因此这将询问用户输入,如果它不大于零,则将引发断言错误,我们将捕获该错误并通过再次调用该函数使用户返回输入数字。如果一切顺利,我们将输入分成字符并加起来。如list('12')给出['1','2']。我们转换为int并添加它们。 :)

关于这一点的令人敬畏的事情是,您也可以添加更多资产,以捕获其他问题(如浮动,字符作为无效输入)。例如。

假设literal_eval很重要(来自ast importliteral_eval)

assert isinstance(literal_eval(user_in),int) and int(user_in)>0

检查user_in是否为整数且大于0。因此,当用户输入浮点数或字符时,不会出现问题。

答案 3 :(得分:-1)

您不是从用户那里获取其他输入,而是遍历大于零的user_input。

因此while循环将不会执行。 如下修改您的代码。 user_input = float(int(input(“请输入您的电话号码:”)))

s = user_input

new_input = -1
while new_input < 0:
  new_input = float(input("Please Enter Another Number: "))
  s += new_input
  if new_input > 0:
    print("You've entered a positive number! The sum of the digits is: ", s)

输出将如下所示。

> Please Enter Your Number:2000 Please Enter Another Number: -100 Please
> Enter Another Number: -200 Please Enter Another Number: -300 Please
> Enter Another Number: -400 Please Enter Another Number: -500 Please
> Enter Another Number: 100 ("You've entered a positive number! The sum
> of the digits is: ", 600.0)
相关问题