如何在Python的一行中输入2个整数? [英] How to input 2 integers in one line in Python?

查看:136
本文介绍了如何在Python的一行中输入2个整数?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想知道是否可以在一行标准输入中输入两个或多个整数.在C/C++中很简单:

I wonder if it is possible to input two or more integer numbers in one line of standard input. In C/C++ it's easy:

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'

那怎么办?

推荐答案

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

Split the entered text on whitespace:

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

演示:

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

这篇关于如何在Python的一行中输入2个整数?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆