# Input and Output

Published:

This lesson covers An Informal Introduction to Python 3.10.5, https://docs.python.org/3/tutorial/introduction.html

# Introduction

• There are several ways to present the output of a program
• data can be printed in a human-readable form, or written to a file for future use

## Fancier Output Formatting

# formatted string literals
x = 5
print(f"The value of x is {x}")
print(F"The value of x is {x}")

print(f"""The value of
x is {x}""")

# str.format()
x = 5
print("The value of x is {}".format(x))

# str.format()

yes = 42_572_654
no = 43_132_495

percentage = yes / (yes + no)
print(percentage) # 0.496733912684756

msg = '{} votes = {:2.2%}'.format(yes, percentage)

# str() for human readable
# repr() for interpreter

x = 10 * 3.25
y = 200 * 200

s = "The value of x is " + str(x)
s += ' and y is ' + str(y)
print(s)

s = "The value of x is " + repr(x)
s += ' and y is ' + repr(y)
print(s)

s = 'Hello, world'
print(s) # Hello, world
print(str(s)) # Hello, world # human readbale
print(repr(s)) # 'Hello, world' \$ for interpreter

s = 'Hello, world\n'
print(s) # Hello, world with line gap
print(str(s)) # Hello, world with line gape
print(repr(s)) # 'Hello, world\n'


### Formatted String Literals (f-strings)

# formatting decimal digits
import math
print(f"Pi is approximately {math.pi:.3f}")#3.142

# spaces
table = {'Sjoerd': 4127,
'Jack': 4098,
'Dcab': 7678
}
for name, phone in table.items():
print(f'{name:10} ==> {phone:10d}')

# other modifiers
# !a applies ascii()
# !s applies str()
# !r applies repr()

animals = 'eels'
print(f'My hovercraft is full of {animals}')
# My hovercraft is full of eels

print(f'My hovercraft is full of {animals!r}')
# My hovercraft is full of 'eels'.


### The String format() Method

num1 = 5
num2 = 10
print("{} and {}".format(num1, num2)) #5 and 10
print("{0} and {1}".format(num1, num2))#5 and 10
print("{1} and {0}".format(num1, num2))#10 and 5

table = {'x': 5,
'y': 10,
'z': 15
}

print("""
z: {0[z]:d}
y: {0[y]:d}
x: {0[x]:d}""".format(table))

print("""
x: {x}
z: {z}
y: {y}
""".format(**table))

msg = "{0:2d} {1:3d} {2:4d}"
for x in range(1, 11):
print(msg.format(x, x*x, x*x*x))


### Manual String Formatting

# str.ljust() and str.rjust()
for x in range(1, 11):
print(str(x).ljust(10), end=' ')
print(str(x*x).rjust(10), end=' ')
print(str(x*x*x).rjust(10))

# str.zfill() - fills with zeros
for x in range(1, 11):
print(str(x).zfill(3), end=' ')
print(str(x*x).zfill(3), end=' ')
print(str(x*x*x).zfill(3))


### Old string formatting

import math
print('Value of pi is approximately %f' % math.pi)
print('Value of pi is approximately %5.2f' % math.pi)


f = open('workfile', 'w', encoding="utf-8")
f.close()

# In Binary mode
f = open('workfile', 'wb') # no encoding
f.close()

with open('workfile', encoding="utf-8") as f:
print(f.closed) # True


### Methods of File Objects

f = open("data.txt", "r", encoding="utf-8")
f.close()
print(f.closed) # True
# ---------------------

f = open("data.txt", "r", encoding="utf-8")
# two \n from line and print
# two \n from line and print
f.close()
# ---------------------

f = open("data.txt", "r", encoding="utf-8")
for line in f:
print(line, end="") # no \n from print
f.close()
# ---------------------

f = open("data.txt", "r", encoding="utf-8")
f.close()
for line in lines:
print(line, end="")
# ---------------------

f = open("data.txt", "w", encoding="utf-8")
print(f.write('This is a test\n')) # no of chars 15
f.close()
# ---------------------

f = open("data.txt", "w", encoding="utf-8")
s = str(value)  # convert the tuple to string
print(f.write(s)) # no of chars 18
f.close()


### Saving structured data with ‘json’

• JSON (JavaScript Object Notation)
• The standard module called json can take Python data hierarchies, and convert them to string representations; this process is called serializing.
• Reconstructing the data from the string representation is called deserializing.
• Between serializing and deserializing, the string representing the object may have been stored in a file or data, or sent over a network connection to some distant machine.
import json

# Serialization  - dumps() - string representation
x = [1, 'simple', 'list']
print(json.dumps(x)) # '[1, "simple", "list"]' # json string

x = {"n1": 10, "n2": 20, "n3": 30}
print(json.dumps(x)) # '[1, "simple", "list"]' # json string

# serialization to file - dump
x = {"n1": 10, "n2": 20, "n3": 30}
with open("data.txt", "w", encoding="utf-8") as fp: # write mode
json.dump(x, fp)

# deserialzation
with open("data.txt", "r", encoding="utf-8") as fp: # read mode