Two values from one input in python?

前端 未结 18 2222
小鲜肉
小鲜肉 2020-11-28 03:46

This is somewhat of a simple question and I hate to ask it here, but I can\'t seem the find the answer anywhere else: is it possible to get multiple values from the user in

18条回答
  •  死守一世寂寞
    2020-11-28 04:15

    The Python way to map

    printf("Enter two numbers here: ");
    scanf("%d %d", &var1, &var2)
    

    would be

    var1, var2 = raw_input("Enter two numbers here: ").split()
    

    Note that we don't have to explicitly specify split(' ') because split() uses any whitespace characters as delimiter as default. That means if we simply called split() then the user could have separated the numbers using tabs, if he really wanted, and also spaces.,

    Python has dynamic typing so there is no need to specify %d. However, if you ran the above then var1 and var2 would be both Strings. You can convert them to int using another line

    var1, var2 = [int(var1), int(var2)]
    

    Or you could use list comprehension

    var1, var2 = [int(x) for x in [var1, var2]]
    

    To sum it up, you could have done the whole thing with this one-liner:

    # Python 3
    var1, var2 = [int(x) for x in input("Enter two numbers here: ").split()]
    
    # Python 2
    var1, var2 = [int(x) for x in raw_input("Enter two numbers here: ").split()]
    

提交回复
热议问题