关于用for循环求和
我试图让用户输入出生日期,然后在这些数字中添加各个整数。此外,如果这些数字中的任何一个的总和大于或等于 10,则循环会重复,并且该过程会针对该值再次运行。到目前为止,这是我的代码,
if (sumYear >= 10):
sumYear2=0
for num in str(sumYear):
sumYear2 += int(num)
print(sumYear2)
这有效,但我认为最好将其作为循环来完成。如果有某种方法我不必使用像 sumYear2
这样的东西,那就太好了。请注意,我认为我无法使用 sum()
函数。
谢谢大家的帮助。不过我有一个问题。我不知道为什么当我提供月份 02 和日期 30 时这段代码没有被评估
while True:
year=input("Please enter the year you were born: ")
month=input("Please enter the month you were born: ")
day=input("Please enter the day you were born: ")
if(int(month)==2 and int(day)<=29):
break
elif(int(month)==1 or 3 or 5 or 7 or 8 or 10 or 12 and int(day)<=31 ):
break
elif(int(month)==4 or 6 or 9 or 11 and int(day)<=30):
break
else:
print("Please enter a valid input")
I'm trying to get the user to input a birth date and then add the individual ints in those numbers. Also, if a sum of any of these digits is greater than or equal to 10, the loop repeats and the process runs again for the value. Here's my code so far
if (sumYear >= 10):
sumYear2=0
for num in str(sumYear):
sumYear2 += int(num)
print(sumYear2)
This works however I think it would be better done as a loop. And if there's some way I won't have to use something like sumYear2
that would be great. Note, I don't think I can use the sum()
function.
Thanks guys for the help. I'm having an issue though. I'm not sure why this code isn't being evaluated when I provide the month as 02 and the day as 30
while True:
year=input("Please enter the year you were born: ")
month=input("Please enter the month you were born: ")
day=input("Please enter the day you were born: ")
if(int(month)==2 and int(day)<=29):
break
elif(int(month)==1 or 3 or 5 or 7 or 8 or 10 or 12 and int(day)<=31 ):
break
elif(int(month)==4 or 6 or 9 or 11 and int(day)<=30):
break
else:
print("Please enter a valid input")
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
工作量太大了。
请注意,对于小于 1 的数字,此操作将会失败。
Too much work.
Note that this will fail for numbers less than 1.
@Ignacio Vazquez-Abrams 的答案提供了公式。但是,如果没有,那么您的代码作为不使用
sumYear2
的循环可能如下所示:如果您不允许使用
sum
(作业),那么:对于第二个假设 Python 3 的问题:
如果不允许使用 try/ except 那么:
其中
get_int()
:和
number_of_days_in_month()
:@Ignacio Vazquez-Abrams's answer provides the formula. But if there were none then your code as a loop without using
sumYear2
could look like:If you're not allowed to use
sum
(a homework) then:For the second question assuming Python 3:
If you are not allowed to use try/except then:
Where
get_int()
:And
number_of_days_in_month()
:你可以这样做
You can do this