python - 如何在Python中读取用户输入

标签 python input

我是 Python 初学者,我正在尝试在一个简单的编程竞赛问题中读取两个数字。

# Codeforces New Year 2013 Contest;
# http://codeforces.com/contest/379/problem/A

import sys;

def main ():
    a = input ();
    b = input ();
    resto = 0;
    result = 0;

    while (a > 0):
        a-=1
        result += 1;
        resto += 1;

        if (resto >= b):
            resto -= b;
            a += 1;

    print result;

main ();

如果我尝试使用 4 2 (以空格分隔)运行程序,则会收到以下错误:

ValueError: invalid literal for int() with base 10: '4 2'

但是如果我输入 4 [enter],然后输入 2 [enter],程序运行不会出现任何问题。

如何像 C++ 一样从 python 中的 stdin 读取内容?

编辑:抱歉造成困惑!我通常以这种方式运行输入代码:

C++:./main <测试

Python:python main.py <测试

最佳答案

根据您的语法,我假设您使用的是 python 2。

使用 raw_input 从控制台读取字符串,然后在解析整数之前手动拆分它:

s = raw_input()
tokens = s.split()
a = int(tokens[0])
b = int(tokens[1])

关于python - 如何在Python中读取用户输入,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20872941/

相关文章:

python - 如何将 base64 字符串直接解码为二进制音频格式

css - 表单中的标签定位(使用 div)

javascript - 使用 jquery 匹配更改时的输入值

python - 我可以将我的 python/ipython 输入/输出重定向到文本文件吗?

C++顺序读取多个输入文件

python - 元组作为多维数组的索引

python - 在类构造函数中表达兄弟嵌套类的类型提示

python - AWS IOT 连接超时异常

python - Pandas 数据框按日期排序,然后分配字母 A-Z

c++ - 使用来自文件和手册的 cin.get 的输入值差异