Python:查找所选数字的和

2024-04-26 01:17:58 发布

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

Sum of Specific Digits: Write a program using loops that gets an integer input from the user in the range 25030 and 999999 and finds the sum of the units digit, the hundreds digit and the ten-thousands digit. Make sure to use a loop to validate the input before you proceed to finding the sum of the

我试过了,但当程序输入特定的数字时,它被关闭了1:(


Tags: andofthetoinputthatprogramwrite
1条回答
网友
1楼 · 发布于 2024-04-26 01:17:58

试试这个,我用了一个Try-and-except循环来捕捉错误

validinput=False
while not validinput:
    try:
        num=input("Input a number:")
        if 25030<=int(num)<=999999:
            validinput=True
        else:
            pass
    except:
        pass

unit=int(num[0])
hundred=int(num[2])
ten_thousand=int(num[4])
sum_of_digits=unit+hundred+ten_thousand
print(sum_of_digits)

相关问题 更多 >