如何在Python的一行中输入2个整数?

发布于 2021-01-29 16:50:08

我想知道是否可以在一行标准输入中输入两个或多个整数。在C/C++这很容易:

C++

#include <iostream>
int main() {
    int a, b;
    std::cin >> a >> b;
    return 0;
}

C

#include <stdio.h>
void main() {
    int a, b;
    scanf("%d%d", &a, &b);
}

在中Python,它将不起作用:

enedil@notebook:~$ cat script.py 
#!/usr/bin/python3
a = int(input())
b = int(input())
enedil@notebook:~$ python3 script.py 
3 5
Traceback (most recent call last):
  File "script.py", line 2, in <module>
    a = int(input())
ValueError: invalid literal for int() with base 10: '3 5'

那怎么办呢?

关注者
0
被浏览
245
1 个回答
  • 面试哥
    面试哥 2021-01-29
    为面试而生,有面试问题,就找面试哥。

    在空白处分割输入的文本:

    a, b = map(int, input().split())
    

    演示:

    >>> a, b = map(int, input().split())
    3 5
    >>> a
    3
    >>> b
    5
    


知识点
面圈网VIP题库

面圈网VIP题库全新上线,海量真题题库资源。 90大类考试,超10万份考试真题开放下载啦

去下载看看