Python Tutorial




CS156

Chris Pollett

Sep 7, 2022

Outline

Introduction

Python as Calculator; Programs in Files

Variables and Arithmetic Expressions

Conditionals

File I/O

Example Files in a Folder as a List

import glob
path = './*'
files = glob.glob(path) 
for name in files:
   print(name)

In-Class Exercise

Strings

Lists

Example Using Lists and Command Line

import sys
if(len(sys.argv)) != 2: 
   #notice sys.argv is a list of command-line args and we found its length
   print("Please supply a filename")
   raise(SystemExit(1)) # throw an error and exit
f = open(sys.argv[1]) #program name is argv[0]
lines = f.readlines() # reads all lines into list one go
f.close()

#convert inputs to list of ints
ivalues = [int(line) for line in lines]

# print min and max
print("The min is ", min(ivalues))
print("The max is", max(ivalues))

Tuples

Sets