User:Milanandreew/Python 3 Programming/Input and Output
x = 50
def fun():
global x
print('x is', x)
x = 20
print('global changed x', x)
Input
[edit | edit source]Python includes the function input()
, which accepts data directly from the user.
There are also very simple ways of reading a file and, for stricter control over input, reading from stdin if necessary.
input()
[edit | edit source]input()
asks the user for a string of data (ended with a newline), and simply returns the string. It can also take an argument, which is displayed as a prompt before the user enters the data.
E.g.
print(input('What is your name? '))
prints out
What is your name? <user input data here>
Example: in order to assign the user's name, i.e. string data, to a variable "x" you would type
x = input('What is your name? ')
Once the user inputs their name, e.g. Delilah, you can call it as x.
print('Your name is ' + x)
prints out
Your name is Delilah
To evaluate a given string returned by input()
as if it were a Python programme, you can use eval(input())
. So entering
[1,2,3]
would return a list containing those numbers, just as if it were assigned directly in the Python script. More complicated expressions are possible. For example, if a script says:
x = input('What are the first 10 perfect squares? ')
it is possible for a user to input:
map(lambda x: x*x, range(10))
which yields the correct answer in list form. Note that no inputted statement can span more than one line.
eval(input())
should not be used for anything but the most trivial programme. Turning the strings returned from input()
into python types using an idiom such as:
x = None
while not x:
try:
x = int(input())
except ValueError:
print('Invalid Number')
is preferable, as the literal is turned into a python type. This will allow a malicious person to run arbitrary code from inside your program trivially.
File Input
[edit | edit source]File Objects
[edit | edit source]In Python, files can be opened by using the built-in open()
function:
f = open('test.txt', 'r')
This means f is open for reading. The first argument is the filename and the second parameter is the mode, which can be 'r', 'w', or 'x', among some others. The most common way to read from a file is simply to iterate over the lines of the file:
f = open('test.txt', 'r')
for line in f:
print(line[0])
f.close()
This will print the first character of each line. Note that a newline is attached to the end of each line read this way. The newer and better way to read from a file:
with open('test.txt', 'r') as f:
for line in f:
print(line)
Here, the opened file will close itself after having read each line. Because files are automatically closed when the file object goes out of scope, there is no real need to close them explicitly. So, the loop in the previous code can also be written as:
for line in open('test.txt', 'r'):
print line[0]
A file object contains a marker to represent the current position. If the file marker should be moved back to the beginning, one can either close the file object and reopen it or just move the marker back to the beginning with:
f.seek(0)
Standard File Objects
[edit | edit source]Like many other languages, there are built-in file objects representing standard input, output, and error. These are in the sys
module and are called stdin
, stdout
, and stderr
. There are also immutable copies of these in __stdin__
, __stdout__
, and __stderr__
. This is for IDLE and other tools in which the standard files have been changed.
You must import the sys module to use the special stdin, stdout, stderr I/O handles.
import sys
For finer control over input, use sys.stdin.read()
. In order to implement the UNIX 'cat' program in Python, you could do something like this:
import sys
for line in sys.stdin:
print(line, end=' ')
Note that sys.stdin.read()
will read from standard input until EOF. (which is usually Ctrl+D.)
Parsing command line
[edit | edit source]Command-line arguments passed to a Python program are stored in sys.argv
list. The first item in the list is the name of the Python program, which may or may not contain the full path depending on the manner of invocation. sys.argv
list is modifiable.
Printing all passed arguments except for the program name itself:
import sys
for arg in sys.argv[1:]:
print(arg)
Parsing passed arguments for flags:
import sys
option_f = False
option_p = False
option_p_argument = ''
i = 1
while i < len(sys.argv):
if sys.argv[i] == '-f':
option_f = True
sys.argv.pop(i)
elif sys.argv[i] == '-p':
option_p = True
sys.argv.pop(i)
option_p_argument = sys.argv.pop(i)
else:
i += 1
In the above code, the arguments at which options are found are removed so that sys.argv
can be looped for all remaining arguments.
Parsing of command-line arguments is further supported by library modules argparse
and getopt
(which can be used in a similar fashion to the C getopt()
function)
Links for further reference:
Output
[edit | edit source]The basic way to do output is the print()
function.
print('Hello, World!')
To print multiple things on the same line separated by spaces, use commas between them, like this:
print('Hello,', 'World!')
This will print out the following:
Hello, World!
While neither string contained a space, a space was added by print()
because of the comma between the two objects. Arbitrary data types can be printed this way:
print(1, 2, 0xff, 0o777, (10+5j), -0.999, map, sys)
This will output the following:
1 2 255 511 (10+5j) -0.999 <class 'map'> <module 'sys' (built-in)>
Objects can be printed on the same line without needing to be on the same line if one uses the end
keyword:
for i in range(10):
print(i, end=' ')
This will output the following:
0 1 2 3 4 5 6 7 8 9
To end the printed line with a newline, add an empty print()
call.
for i in range(10):
print(i, end=' ')
print()
for i in range(10,20):
print(i, end=' ')
This will output the following:
0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19
If the empty function call to print()
were not present, the above output would look like:
0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19
You can use similar syntax when writing to a file instead of to standard output, like this:
print('Hello, World!', file=f)
This will print to any object that implements write()
, which includes file objects.
Examples
[edit | edit source]print('Hello')
print('Hello,', 'World!') # Prints the two words separated with a space.
print('Hello,', 34) # Prints elements of various data types, separating them by a space.
print('Hello, ' + 34) # Throws an error as a result of trying to concatenate a string and an integer.
print('Hello, ' + str(34)) # Uses "+" to concatenate strings, after converting a number to a string.
print('Hello', end='') # Prints 'Hello' without a newline at the end.
print('Hello' 'World!', sep='-') # Prints the two words separated with a dash.
sys.stdout.write('Hello\n') # Prints "Hello" with a newline.
print('An error occurred.', file=sys.stderr) # Outputs to a file handle, in this case the standard error stream.
sys.stderr.write('Hello\n') # Prints to standard error stream.
sum=2+2; print('The sum: {}'.format(sum))# Prints a string that has been formatted with the use of an integer passed as an argument.
formatted_string = 'The sum: {}'.format(2+2); print(formatted_string) # Like the previous, just that the formatting happens outside of the function call.
print('Float: {:6.3f}'.format(1.23456)) # Outputs 'Float: 1.235'. The number 3 after the period specifies the number of decimal digits after the period to be displayed, while 6 before the period specifies the total number of characters the displayed number should take, to be padded with spaces if needed.
print('{} is {} years old'.format('Sultan', 21)) # Passes two arguments to the formatter.
File Output
[edit | edit source]Printing numbers from 1 to 10 to a file, one per line:
f = open('test.txt', 'w')
for i in range(1,10+1):
print(i, file=f)
f.close()
With 'w', the file is opened for writing. The keyword file
specifies that print()
should send its output to a file rather than standard output.
Printing numbers from 1 to 10 to a file, separated with a dash:
file1 = open('test.txt', 'w')
for i in range(1,10+1):
if i>1:
f.write('-')
f.write(str(i))
f.close()
Opening a file for appending rather than overwriting:
f = open('test.txt', 'a')
Formatting
[edit | edit source]Formatting numbers and other values as strings using the format() string method:
v1 = 'Arg 0: {0}'.format(31) # 31
v2 = 'Args 0 and 1: {0}, {1}'.format(31, 65)
v3 = 'Args 0 and 1: {}, {}'.format(31, 65)
v4 = 'Arg indexed: {0[0]}'.format(['e1', 'e2'])
v5 = 'Arg named: {a}'.format(a=31)
v6 = 'Hex: {0:x}'.format(31) # 1f
v7 = 'Hex: {:x}'.format(31) # 1f - arg 0 is implied
v8 = 'Char: {0:c}'.format(65) # A
v9 = 'Hex: {:{h}}'.format(31, h='x') # 1f - nested evaluation
Formatting numbers and other values as strings using literal string interpolation:
int1 = 31; int2 = 41; str1="aaa"; myhex = "x"
v1 = f"Two ints: {int1} {int2}"
v2 = f"Int plus 1: {int1+1}" # 32 - expression evaluation
v3 = f"Str len: {len(str1)}" # 3 - expression evaluation
v4 = f"Hex: {int1:x}" # 1f
v5 = f"Hex: {int1:{myhex}}" # 1f - nested evaluation
Links for further reference:
- Python 3 Documentation -
printf
-style String Formatting - Python 3 Documentation - Built-in
format()
function - Python 3 Documentation - Custom String Formatting
- Python 3 Documentation - Format Specification Mini Language
- Python 3 Documentation - Template Strings
- PEP 3101 - Advanced String Formatting
- PEP 498 - Literal String Interpolation