Lecture 8 Introduction To Python
Lecture 8 Introduction To Python
Python
Data types in Python
Programming in Python
Python
Python is another programming language, but it is interpreted (run top to
bottom by an interpreter) and higher-level (including features and libraries that
are more powerful).
For example, we can implement the entire resize program in just a few lines
with Python:
import sys
from PIL import Image
if len(sys.argv) != 4:
sys.exit("Usage: python resize.py n infile outfile")
n = int(sys.argv[1])
infile = sys.argv[2]
outfile = sys.argv[3]
inimage = Image.open(infile)
width, height = inimage.size
outimage = inimage.resize((width * n, height * n))
outimage.save(outfile)
o Unlike in C (whereby braces { } are used for blocks of code), the exact
indentation of each line is what determines the level of nesting in
Python.
Boolean expressions are slightly different, too:
while True:
something
Loops can be created with another function, range, that, in the example below,
returns a range of numbers from 0, up to but not including 50:
for i in range(50):
something
print(f"x + y = {x + y}")
print(f"x - y = {x - y}")
print(f"x * y = {x * y}")
print(f"x / y = {x / y}")
print(f"x mod y = {x % y}")
z = x / y
print(f"x / y = {z}")
o We see the following when we run this program:
$ python floats.py
x: 1
y: 10
x / y = 0.1
x / y = 0.10000000000000000555111512312578270211815834045410
i = 1
while True:
print(i)
i *= 2
sleep(1)
o We use the sleep function to pause our program for one second, but
double i over and over. And it turns out that integers in Python can be as
big as memory allows, so we won’t experience overflow for a much
longer time.
Programming in Python
Let’s take a closer look at conditions:
# Get x from user
x = int (input(("x: "))
# Compare x and y
if x < y:
print("x is less than y")
elif x > y:
print("x is greater than y")
else:
print("x is equal to y")
o Notice that we use consistent indentation, but we don’t need parentheses
or braces for our conditions.
o Comments, too, start with just a single # character.
We can compare strings the way we might expect:
# Prompt user for answer
c = string (input("Answer: "))
# Check answer
if c == "Y" or c == "y":
print("yes")
elif c == "N" or c == "n":
print("no")
def cough():
"""Cough once"""
print("cough")
if __name__ == "__main__":
main()
if __name__ == "__main__":
main()
o n is a variable that can be passed into cough, which we can also pass into
range. And notice that we don’t specify types in Python, so n can be of
any data type (and can even be assigned to have a value of another type).
It’s up to us, the programmer, to use this great power with great
responsibility.
We can define a function to get a positive integer:
def main():
i = get_positive_int("Positive integer: ")
print(i)
def get_positive_int(prompt):
while True:
n = int(input(prompt))
if n > 0:
break
return n
if __name__ == "__main__":
main()
We’ll be using version 3 of Python, which the world is starting to use more and
more, so when searching for documentation, we want to be sure that it’s for the
right version.
We can take command-line arguments with:
from sys import argv
if len(argv) == 2:
print(f"hello, {argv[1]}")
else:
print("hello, world")
for s in argv:
print(s)
This will iterate over each element in the list argv, allowing us to
use it as s.
o And we can iterate over each character, of each argument:
from sys import argv
for s in argv:
for c in s:
print(c)
print()
# Print numbers
print()
for number in numbers:
print(number)
o Here, we create a empty list called numbers with numbers = [], and we
get a number from the user. If that number is not already in our list, we
add it to our list. We can use not in to check if a value is (not) in a list,
and append to add a value to the end of a list.
We can create our own data structures, objects:
# Space for students
students = []
o We create a list called students, and after we get some input from the
user, we append a dictionary of key-value pairs, {"name": name,
"dorm": dorm}, to that list. Here, "name" and "dorm" are the keys, and
we want their values to be the variables we gathered as input. Then, we
can later access each object’s values with student['name'] or
student['dorm'] to print them out. In Python, we can index into
dictionaries with words or strings, as opposed to just numeric indexes in
lists.
Let’s print four question marks, one at a time:
for i in range(4):
print("?", end="")
print()
Now we can revisit resize.py, and it might make more sense to us now:
from PIL import Image
from sys import argv
if len(sys.argv) != 4:
sys.exit("Usage: python resize.py n infile outfile")
n = int(sys.argv[1])
infile = sys.argv[2]
outfile = sys.argv[3]
inimage = Image.open(infile)
width, height = inimage.size
outimage = inimage.resize((width * n, height * n))
outimage.save(outfile)
o We import the Image library from something called PIL, a free open-
source library that we can download and install (which doesn’t come
with Python by default).
o Then, we import argv from the system library, and we check our
arguments, storing them as n, infile, and outfile, converting the string
input for n into an int as we do so.
o By reading the documentation for Python and the Image library, we can
open files as an image, getting its size and calling a resize function on
it to get another image, which we can then save to another file.
Let’s look at another example, a spell-checker in Python:
# Words in dictionary
words = set()
def check(word):
"""Return true if word is in dictionary else false"""
return word.lower() in words
def load(dictionary):
"""Load dictionary into memory, returning true if successful else false"""
file = open(dictionary, "r")
for line in file:
words.add(line.rstrip("\n"))
file.close()
return True
def size():
"""Returns number of words in dictionary if loaded else 0 if not yet
loaded"""
return len(words)
def unload():
"""Unloads dictionary from memory, returning true if successful else
false"""
return True