1

I'm beginner in Python and I'm trying to read two numbers in a simple programming contest problem.

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

if I try to run the program with 4 2 (separated by a blank space), I get the following error:

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

But if I type 4 [enter] and then 2 [enter], the program runs without any problems.

How do I read from stdin in python just like C++ does?

Edit: Sorry for the mess! I usually run a code with input this way:

C++: ./main < test

Python: python main.py < test

3
  • 2
    You don't need semicolons in Python FYI. Commented Jan 1, 2014 at 20:32
  • In what world C++ does it differently? Commented Jan 1, 2014 at 20:34
  • I think you're confused with what constitutes standard input. Standard input is what's provided on the command line when you invoke the program. You're just reading what the user types in the prompt. Commented Jan 1, 2014 at 20:35

2 Answers 2

2

Based on your syntax, I assume you're using python 2.

Use raw_input to read a string from the console and then manually split it before parsing your ints:

s = raw_input()
tokens = s.split()
a = int(tokens[0])
b = int(tokens[1])
Sign up to request clarification or add additional context in comments.

Comments

1

You can use sys.argv which is similar to many other programming languages:

import sys

for a in sys.argv:
    print a

If you invoke this program from the command line like this:

python test.py 10 20 30 40 50

Then it will print:

test.py
10
20
30
40
50

So you can just access your arguments using indexes:

print sys.argv[2] #prints 20

Remember though that sys.argv contains strings - so if you want to handle the input like integers remember to cast them first like this:

int(sys.argv[2])

2 Comments

Thanks, that's what I'm looking for. If I try to run the program using python test.py < input_file, all the content of the file goes to sys.argv[]?
No it will not. If I were you I would just run "python test.py input_file" and then open the file within the program itself.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.