Learn Python from Scratch 2023: Module 4

Amir Torkashvand
2 min readApr 19, 2023

--

Module 4: Input and Output

In this module, we’ll learn about input and output in Python. Input refers to getting data into our program, while output refers to sending data out of our program. We’ll cover how to read and write files, how to work with standard input and output, and how to format strings.

  1. Reading and Writing Files Python has built-in functions for reading and writing files. To read a file, we use the open() function, which returns a file object. The file object has methods for reading the contents of the file. For example:
file = open("myfile.txt", "r")
contents = file.read()
print(contents)
file.close()

This code reads the contents of the file “myfile.txt” and prints it to the console.

To write to a file, we use the open() function with the "w" argument, which tells Python that we want to write to the file. For example:

file = open("myfile.txt", "w")
file.write("Hello, world!")
file.close()

2. Standard Input and Output Standard input is the input that is provided to our program through the keyboard or command line. Standard output is the output that our program sends to the console. In Python, we can use the input() function to get input from the user, and the print() function to send output to the console. For example:

name = input("What is your name? ")
print("Hello, " + name + "!")

This code asks the user for their name, and then prints a greeting with their name.

3. String Formatting

String formatting allows us to insert variables into a string. There are several ways to format strings in Python, but the most common is using the format() method. For example:

name = "Alice"
age = 30
print("My name is {} and I am {} years old.".format(name, age))

This code inserts the variables name and age into the string using placeholders {}. The format() method replaces the placeholders with the values of the variables.

4. Working with CSV Files CSV (Comma Separated Values) files are a common way to store and exchange data. Python has a built-in module called csv that makes it easy to read and write CSV files. For example:

import csv

with open("mydata.csv", "w") as file:
writer = csv.writer(file)
writer.writerow(["Name", "Age"])
writer.writerow(["Alice", 30])
writer.writerow(["Bob", 25])

with open("mydata.csv", "r") as file:
reader = csv.reader(file)
for row in reader:
print(row)

This code creates a CSV file with the headers “Name” and “Age”, and two rows of data. It then reads the data from the file and prints it to the console.

That’s it for Module 4! With these concepts, you should be able to read and write files, work with standard input and output, format strings, and work with CSV files in Python. In the next module, we’ll cover control flow statements, which will allow us to write more complex programs.

--

--