【问题标题】:Python 3 - Check a list of user inputs for multiples of 5Python 3 - 检查用户输入列表中 5 的倍数
【发布时间】:2017-10-24 19:10:04
【问题描述】:

如何检查用户输入值的列表是否为 5 的倍数?我需要能够打印出这些值中有多少是 5 的倍数。例如:

 intList = [5, 10, 11, 15]
 "75% of values in intList are multiples of 5"

到目前为止,这是我的代码:

 intList = []

 running = True
 while running:
   intAmount = int(input("Enter the amount of integers you are inputting: "))
   if intAmount > 0:
     running = False


 for i in range (intAmount):
   integers = int(input("Enter an integer here: "))
   intList.append(integers)
 print(intList)

【问题讨论】:

    标签: list function python-3.6 defined


    【解决方案1】:

    代码:

    intList = [int(x) for x in input('Enter list of numbers: ').split()]
    count = 0
    
    for num in intList:
        if (num % 5) == 0:
            count+=1
    
    percent = (count / len(intList)) * 100
    print("%.2f%% of values in intList are multiples of 5"%percent)
    

    输入:

    输入数字separated by space

    Enter list of numbers: 4 6 2 10 9 45
    

    输出:

    33.33% of values in intList are multiples of 5
    

    代码 2: (根据用户要求)

    intList = []
    
    running = True
    while running:
        intAmount = int(input("Enter the amount of integers you are inputting: "))
        if intAmount > 0:
            running = False
    
    
    for i in range (intAmount):
        integers = int(input("Enter an integer here: "))
        intList.append(integers)
    print(intList)
    
    count = 0
    for num in intList:
        if (num % 5) == 0:
            count+=1
    
    percent = (count / len(intList)) * 100
    print("%.2f%% of values in intList are multiples of 5"%percent)
    

    【讨论】:

    • 有什么方法可以在我当前的程序中使用该函数而不改变我输入整数的方式?
    • 是的,你可以做到。只需将count = 0 for num in intList: if (num % 5) == 0: count+=1 percent = (count / len(intList)) * 100 print("%.2f%% of values in intList are multiples of 5"%percent) 附加到问题中的代码即可。
    • 我在答案中添加了code 2 部分供您参考。
    猜你喜欢
    • 2016-02-05
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-03-17
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多