首页 > 解决方案 > 如何创建一个接受变量列表的 if 语句条件?

问题描述

如何在 if 语句中创建一个接受变量列表并打印出可被 5 整除的数字的条件?

firstNumber = input("Write the First Number: ")
secondNumber = input("Write the Second Number: ")
thirdNumber = input("Write the the Third Number: ")
fourthNumber = input("Write the the Fourth Number: ")
list1 = [firstNumber, secondNumber, thirdNumber, fourthNumber]

def divisibleByFive():
    for x in list1:
        if x%5 == 0:
            print(x)

divisibleByFive()

标签: pythonpython-3.xlistif-statementuser-input

解决方案


在函数中获取它作为参数并在调用时传递:

firstNumber = input("Write the First Number: ")
secondNumber = input("Write the Second Number: ")
thirdNumber = input("Write the the Third Number: ")
fourthNumber = input("Write the the Fourth Number: ")
list1 = [firstNumber, secondNumber, thirdNumber, fourthNumber]

def divisibleByFive(l1):
    for x in l1:
        if int(x)%5 == 0:
            print(int(x))

divisibleByFive(list1)

不喜欢路过?使用全局变量,但这太过分了:-(

firstNumber = input("Write the First Number: ")
secondNumber = input("Write the Second Number: ")
thirdNumber = input("Write the the Third Number: ")
fourthNumber = input("Write the the Fourth Number: ")
list1 = [firstNumber, secondNumber, thirdNumber, fourthNumber]

def divisibleByFive():
    global list1
    for x in list1:
        if int(x)%5 == 0:
            print(int(x))

divisibleByFive()

推荐阅读