我有个任务。它应该做以下事情: -->;输入整数(比如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)
不需要那些布尔人。您可以将代码分解为:
我不明白您为什么调用}。所以我在上面加了一个。现在它可以捕捉到一个错误:)。在
list(map(int, str(num)))
;但我认为您打算在您的输入中加上{现在,要获得一个数字,可以在这里使用另一个
^{pr2}$while
循环:这几乎创建了}调用它。重复这个过程,直到它不再是两位数(或三位数、四位数等)
[1, 0, 0]
,然后{总而言之:
请注意,对于条件语句,执行
a == True
或b == False
并不是python。在从PEP:
你很亲密。你需要改变的是:
在这段代码中,有一个while循环,它在
^{pr2}$sum
大于9时执行。那么为什么要使用另一个变量Sum
(而且,这会使代码非常难以阅读)?请执行以下操作:这只是为了告诉你你的代码出了什么问题。我不建议使用它(看看下面我会怎么做)。首先,您混合了变量命名约定,这是一个非常糟糕的主意,尤其是当您在团队中工作时(即使不是这样,您能想象一个月或六个月后查看您的代码吗?)。}?
第二,你从来没有使用过
goodvalue2
;它有什么用?第三,如果
goodvalue1
只会是bool
,那么为什么要检查{if goodvalue1
更清晰,更具Python味。为了所有的好处,请在代码中使用一些空格。在看了一段时间像
ListOfDigits=list(map(int,str(num)))
这样的表情后,眼睛会变得非常紧张。请改为尝试ListOfDigits = list(map(int, str(num)))
。在就我个人而言,我会这样做:
我的看法是:
对于解释,@Haidro做得很好:https://stackoverflow.com/a/17787707/969534
相关问题 更多 >
编程相关推荐