【问题标题】:How to create an if statement condition that would accept the list of variables?如何创建一个接受变量列表的 if 语句条件?
【发布时间】:2020-11-12 02:34:36
【问题描述】:

如何在 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()

【问题讨论】:

  • 将输入字符串转换为整数:firstNumber = int(input("Write the First Number: "))

标签: python python-3.x list if-statement user-input


【解决方案1】:

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

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()

【讨论】:

  • 如果您打算修改列表,您只需要global - 这里不需要。代码的主要问题是输入数据是字符串,在使用%运算符之前需要转换为int
猜你喜欢
  • 2017-11-04
  • 2012-10-20
  • 1970-01-01
  • 2016-07-11
  • 2022-01-18
  • 1970-01-01
  • 1970-01-01
  • 2023-02-03
  • 2018-09-18
相关资源
最近更新 更多