多个数中的一个数

2024-09-30 06:31:24 发布

您现在位置:Python中文网/ 问答频道 /正文

我有个任务。它应该做以下事情: -->;输入整数(比如100) -->;将数字相加,直到总和为一个位数(1)

我现在的计划是:

goodvalue1=False
goodvalue2=False

while (goodvalue1==False):
    try:
        num=input("Please enter a number: ")
    except ValueError:
        print ("Wrong input. Try again.")
    else:
        goodvalue1=True


if (goodvalue1==True):
    ListOfDigits=list(map(int,str(num)))
    sum=10
    while(sum>9):
        Sum=sum(ListOfDigits)
        if (Sum>9):
            ListOfDigits=list(map(int,str(Sum)))
            Sum=sum(ListOfDigits)

Tags: gtfalsetruemapinputifnumlist
3条回答

不需要那些布尔人。您可以将代码分解为:

while True:
    try:
        num = int(input("Please enter a number: ")) # Note how I've added int()
        break # Breaks out of the loop. No need for a boolean.
    except ValueError:
        print("Wrong input. Try again.")

我不明白您为什么调用list(map(int, str(num)));但我认为您打算在您的输入中加上{}。所以我在上面加了一个。现在它可以捕捉到一个错误:)。在

现在,要获得一个数字,可以在这里使用另一个while循环:

^{pr2}$

这几乎创建了[1, 0, 0],然后{}调用它。重复这个过程,直到它不再是两位数(或三位数、四位数等)

总而言之:

while True:
    try:
        num = int(input("Please enter a number: ")) # Note how I've added int()
        break # Breaks out of the loop. No need for a boolean.
    except ValueError:
        print("Wrong input. Try again.")

while num > 9: # While it is a two digit number
    num = sum(map(int, str(num)))

请注意,对于条件语句,执行a == Trueb == False并不是python。在

PEP

Don't compare boolean values to True or False using ==.

Yes: if greeting:

No: if greeting == True:

Worse: if greeting is True:

你很亲密。你需要改变的是:

Sum=sum(ListOfDigits)
while(Sum>9):
    Sum=sum(ListOfDigits)
    if (Sum>9):
        ListOfDigits=list(map(int,str(Sum)))
        Sum=sum(ListOfDigits)

在这段代码中,有一个while循环,它在sum大于9时执行。那么为什么要使用另一个变量Sum(而且,这会使代码非常难以阅读)?请执行以下操作:

^{pr2}$

这只是为了告诉你你的代码出了什么问题。我不建议使用它(看看下面我会怎么做)。首先,您混合了变量命名约定,这是一个非常糟糕的主意,尤其是当您在团队中工作时(即使不是这样,您能想象一个月或六个月后查看您的代码吗?)。
第二,你从来没有使用过goodvalue2;它有什么用?
第三,如果goodvalue1只会是bool,那么为什么要检查{}?if goodvalue1更清晰,更具Python味。
为了所有的好处,请在代码中使用一些空格。在看了一段时间像ListOfDigits=list(map(int,str(num)))这样的表情后,眼睛会变得非常紧张。请改为尝试ListOfDigits = list(map(int, str(num)))。在

就我个人而言,我会这样做:

num = None
while num is None:
    try:
        num = int(raw_input("Enter a number: "))
    except ValueError:
        num = None

num = sum(int(i) for i in str(num))
while num > 9:
    num = sum(int(i) for i in str(num)) # this uses a list comprehension. Look it up, they're very useful and powerful!

我的看法是:

inp = None
while inp is None:
    try:
        inp = int(input('Enter number here: '))
    except ValueError:
        print('Invalid Input, try again')

summed = sum(map(int, str(inp)))
while summed > 9:
    summed = sum(map(int, str(summed)))

print('The result is {}'.format(summed))

对于解释,@Haidro做得很好:https://stackoverflow.com/a/17787707/969534

相关问题 更多 >

    热门问题