>>> a, b, c = 1, 4, 9 >>> print "The first three squares are", a, b, "and", c The first three squares are 1 4 and 9 >>> print "The first three squares are", a, ",", b, "and", c, "." The first three squares are 1 , 4 and 9 . >>> print "The first three squares are %s, %s and %s." % (a, b, c) The first three squares are 1, 4 and 9. >>> import sys >>> sys.stdout.write("The first three squares are %s, %s and %s.\n" % ... (a, b, c)) The first three squares are 1, 4 and 9 >>>In a future lesson we will learn how to write to something other than sys.stdout.
>>> import sys >>> s = sys.stdin.readline() This is a line of text. The line ends when I press 'Enter'. >>> s "This is a line of text. The line ends when I press 'Enter'.\n" >>>
You can also use the raw_input function to get a string from sys.stdin. This function takes an optional argument which is used as the prompt.
>>> name = raw_input("What is your name? ") What is your name? Andrew >>> print name, "is a nice name" Andrew is a nice name >>>
#!/usr/bin/env python # file: dog_years.py age = raw_input("Enter your age: ") print "Your age in dog years is", float(age)/7
> dog_years.py Enter your age: 42 Your age in dog years is 6.0 >You should only use raw_input when you ask a question interactively. Most of the time you will use the readline method.
#!/usr/bin/env python # file: dog_years.py import sys sys.stdout.write("Enter your age: ") age = sys.stdin.readline() print "Your age in dog years is", float(age)/7
We will learn later how to take input from a file rather than the terminal.
The readline() function includes the end of line character, except possibly for the last line.
>>> name = sys.stdin.readline() Andrew >>> name 'Andrew\n' >>>Sometimes it causes a problem, as in
>>> print "Hello %s, happy to meet you?" % name Hello Andrew , happy to meet you! >>>There are a few ways to get rid of the trailing newline. In most cases you should use the strip method, which removes spaces and newlines from the front and back of the string.
>>> s = " Andrew \n" >>> s ' Andrew \n' >>> s.strip() 'Andrew' >>>This program works right:
#!/usr/bin/env python # hello.py import sys sys.stdout.write("Enter your name: ") name = sys.stdin.readline() name = name.strip() sys.stdout.write("Hello %s, happy to meet you!\n" % name)
> hello.py Enter your name: Andrew Hello Andrew, happy to meet you! >
This page based on Basic I/O