Warning - This site is moving to https://getthecodingbug.anvil.app
Topics covered
​ Output and String Formatting
Input
File I/O
Output
We have already covered Output, when we use the print statement.
print("This sentence is output to the screen")
When you print variables and text Python automatically inserts a space as a separator:
var1 = 25
print('the value of var1 is:', var1)
results in
The value of var1 is: 25
print(1,2,3,4)
results in:
1 2 3 4
You can change the separator with the sep= parameter in the print statement:
print(1,2,3,4,sep='*')
which results in:
1*2*3*4
Output and String Formatting
Sometimes we would like to format our output to make it look attractive.
There are 3 methods for formatting strings in python.
The first two I show, so that if you see them in other people's code, you can follow what is being done.
However, I recommend you learn and use method 3
Method 1: %-formatting (Old-school method)
Method 2: str.format() (Introduced in Python 2.6)
Method 3: f-strings (Introduced in Python 3.6)
Method 1:
print("Hello, %s." % name)
Hello, Justin.
print("Hello, %s. You are %s." % (name, age))
Hello, Justin. You are 25.
Method 2:
print("Hello, {}. You are {}.".format(name, age))
Hello, Justin. You are 25.
Method 3:
print(f"Hello, {name}. You are {age}.")
Hello, Justin. You are 25.
Here's how to limit the number of decimal places to 2
number = 22/7
print(f"{number}")
3.142857142857143
print(f"{number:.2f}")
3.14
Why not copy'n'paste this code, below, and keep it as a reference:
# stringFormatting.py # Lets start by creating two variables to be included in the formatted string name = 'Justin' age = 25 # There are 3 methods for formatting strings in python # The first two I show, so that if you see them in other people's code, # you can follow what is being done, however, I recommend you learn and use method 3 # Method 1: %-formatting (Old-school method) # Method 2: str.format() (Introduced in Python 2.6) # Method 3: f-strings (Introduced in Python 3.6) # Method 1: print("Hello, %s." % name) # Hello, Justin. print("Hello, %s. You are %s." % (name, age)) # Hello, Justin. You are 25. # Method 2: print("Hello, {}. You are {}.".format(name, age)) # Hello, Justin. You are 25. # Method 3: print(f"Hello, {name}. You are {age}.") # Hello, Justin. You are 25. # Here's how to limit the number of decimal places to 2 number = 22/7 print(f"{number}") # 3.142857142857143 print(f"{number:.2f}") # 3.14
Python Input
Up until now, our programs were static. The value of variables were defined or hard coded into the source code.
To allow flexibility we might want to take the input from the user. In Python, we have the input() function to allow this.
num = input('Enter a number: ')
results in a prompt to the user, and the computer waits for the user to enter some characters and press the Return (or Enter) key.
Enter a number: 10
When the Return key is pressed the characters entered will be stored in num
You can then print out the variable to check what has been entered:
print(num)
Here, we can see that the user entered '10'. This is a string, not a number, and therefore cannot be used in calculations.
To convert this into a number we can use int() or float() functions.
num = input('Enter a number: ')
x = int(num)
print(x * 2)
results in:
20
x = float(num)
print(x * 2)
results in:
20.0
We can now prompt the user to enter a number representing the temperature in degrees Celsius and return the same temperature in the Fahrenheit scale.
# First, we should define a function to perform the Celcius to Fahrenheit conversion:
def tempCtoF(c):
f = ((c/5)*9)+32
return(f)
# Now get the user to enter the degrees in Celcius
answer = input('Enter a temperature in degrees C: ')
deg = float(answer)
fah = tempCtoF(deg)
print('The temperature in degrees Fahrenheit is: ', fah)
Python File I/O
This is about Python file operations. More specifically, opening a file, reading from it, writing into it, closing it and various file methods you should be aware of.
When we set a variable to a value it is stored random access memory (RAM). Since, RAM is volatile which loses its data when computer is turned off, we use files for future use of the data.
How to open a file
f = open("test.txt") # open file in current directory
f = open("C:/Users/W7/myfile.txt") # or specifying full path
We can specify the mode while opening a file. In mode, we specify whether we want to read 'r', write 'w' or append 'a' to the file.
We also specify if we want to open the file in text mode or binary mode.
f = open("test.txt") # equivalent to 'r'
f = open("test.txt",'w') # write in text mode
f = open("img.bmp",'r+b') # read and write in binary mode
How to close a file Using Python
When we are done with operations to the file, we need to properly close the file.
f = open("test.txt",encoding = 'utf-8')
# perform file operations
f.close()
This method is not entirely safe. If an exception occurs when we are performing some operation with the file, the code exits without closing the file.
A safer way is to use a try...finally block.
try:
f = open("test.txt",encoding = 'utf-8')
# perform file operations
finally:
f.close()
This way, we are guaranteed that the file is properly closed even if an exception is raised, causing program flow to stop.
The best way to do this is using the 'with' statement. This ensures that the file is closed when the block inside with is exited. We don't need to explicitly call the close() method. It is done internally.
with open("test.txt",'w',encoding = 'utf-8') as f:
# perform file operations
How to write to File Using Python
In order to write into a file in Python, we need to open it in write 'w', append 'a' or exclusive creation 'x' mode.
We need to be careful with the 'w' mode as it will overwrite into the file if it already exists. All previous data are erased.
# How to write to File Using Python
with open("test.txt",'w',encoding = 'utf-8') as f:
f.write("The quick \n")
f.write("brown fox \n")
f.write("jumps over the lazy dogs.\n")
This results in a file called 'text.txt' in the same folder as you program.
It can be viewed with a text editor such as Notepad, and should look like this:
The quick
brown fox
jumps over the lazy dogs.
How to read files in Python
To read a file in Python, we must open the file in reading mode.
f = open("test.txt",'r',encoding = 'utf-8')
data = f.read(4) # read the first 4 data bytes 'The '
print("data=", data)
data = f.read(4) # read the next 4 data bytes 'quic'
print("data=", data)
data = f.read() # read in the rest till end of file
# 'k'
# 'brown fox'
# 'jumps over the lazy dogs.'
print("data=", data)
results in:
data= The
data= quic
data= k
brown fox
jumps over the lazy dogs.
More reading and writing
Lets write out a list:
# Lets create a list:
fruitList = ['banana', 'apple', 'pear', 'orange', 'grape']
# Lets write out a list:
with open("fruit.txt",'w',encoding = 'utf-8') as f:
for item in fruitList:
f.write(item + "\n") # And read it back:
with open("fruit.txt",'r') as f:
while True:
line = f.readline()
if not line: break
print("data=", line[:-1])
results in:
data= banana
data= apple
data= pear
data= orange
data= grape
You could also open the file: fruit.txt with a text editor, to view its contents and it should look like this:
banana
apple
pear
orange
grape
Exercise 1
Write a poem to a text file using Python.
Copy'n'paste this code into a new, empty text editor file and save as 'writeTextFile.py'.
# writeTextFile2.py filename = 'poem.txt' f1 = open(filename, 'wt') f1.write("Mary had a little lamb,") f1.write("It's fleece was white as snow;") f1.write("And everywhere that Mary went") f1.write("The lamb was sure to go.") f1.close()
Why did I use the double-quotes (") around the text in the f1.write statements?
What would happen if I had used single-quotes (')?
Don't know? - try it and see.
Now open and read the file 'poem.txt' in a text editor like SublimeText or Notepad.
Why does the text all appear on one line?
How can you change your program to make sure each line of the poem appears on a new-line?
Tip: A new-line character can be represented using this string: "\n"
Exercise 2
Here is a sample file to practice reading using Python.
Copy'n'paste this into a new, empty text editor file and save as 'shakespeare.txt'.
To be, or not to be, that is the question: Whether 'tis nobler in the mind to suffer The slings and arrows of outrageous fortune, Or to take Arms against a Sea of troubles, And by opposing end them: to die, to sleep; No more; and by a sleep, to say we end The heart-ache, and the thousand natural shocks That Flesh is heir to? 'Tis a consummation Devoutly to be wished. To die, to sleep, perchance to Dream; aye, there's the rub, For in that sleep of death, what dreams may come, When we have shuffled off this mortal coil, Must give us pause. There's the respect That makes Calamity of so long life.
Now read 'shakespeare.txt' using Python, then:
1. Display the contents of the file, just read,
2. Count the number of lines
3. Count the number of words,
4. Count the number of alphabetic letters (ignore spaces and punctuation)
Copy'n'paste the following into a new text editor file and save as 'readTextFile.py'.
Then add code to get the four results as requested above.
# readTextFile.py filename = 'shakespeare.txt' f1 = open(filename, 'rt') data = f1.read() f1.close() # 1. Show what has been read # 2. Count how many lines # 3. Count how any words # 4. Count how many letters (a-z or A-Z)
Tip: You can split text into a list using the split() method.
For example, if you had a string like this: foxes = "The quick brown fox" - you could split it into a list like this:
mylist = foxes.split(" ")
This removes the spaces (" ") and puts the sub-strings on either side into a list.
Then you could count the number of items in the list using len() function:
print(len(mylist))
Note: You can use the split() function to split strings using any character or string inside the brackets.