0% found this document useful (0 votes)
30 views171 pages

Lecture Slides

The document provides an introduction to Python programming, covering basic concepts such as the Python prompt, functions, variables, loops, and data types. It includes examples of simple programs, explaining how to define functions, use input statements, and perform calculations. Additionally, it discusses the software development process and the importance of understanding numeric data types in Python.

Uploaded by

puneethapatkar
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
30 views171 pages

Lecture Slides

The document provides an introduction to Python programming, covering basic concepts such as the Python prompt, functions, variables, loops, and data types. It includes examples of simple programs, explaining how to define functions, use input statements, and perform calculations. Additionally, it discusses the software development process and the importance of understanding numeric data types in Python.

Uploaded by

puneethapatkar
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 171

Python: Introduction

1
Magic of Python
• When you start Python, you will see something like this
Python 3.9.7 (default, Sep 16 2021, 16:59:28) [MSC v.1916 64
bit (AMD64)] :: Anaconda, Inc. on win32
Type "help", "copyright", "credits" or "license" for more
information.

2
Magic of Python
• The “>>>” is a Python prompt indicating that Python is ready for
us to give it a command. These commands are called statements.
• >>> print("Hello, world“)

Hello, world

>>> print(2+3)

>>> print("2+3=", 2+3)


>>>
3
• Usually, we want to execute several statements together
that solve a common problem. One way to do this is to use a
function.
• >>> def hello():
print("Hello")
print("Computers are Fun")

>>>

4
• What’s the deal with the ()’s?
• Commands can have changeable parts called parameters that
are placed between the ()’s.
• >>> def greet(person):
print("Hello",person)
print ("How are you?")

>>>

5
• >>> greet(“RAM")

Hello RAM
How are you?

>>> greet(“Ravi")

Hello Ravi
How are you?
>>>
• When we use parameters, we can customize the output of our
function

6
• When we exit the Python prompt, the functions we’ve
defined cease to exist!
• Programs are usually composed of functions, modules, or
scripts that are saved on disk so that they can be used again
and again.
• A module file is a text file created in text editing software
(saved as “plain text”) that contains function definitions.
• A programming environment is designed to help
programmers write programs and usually includes automatic
indenting, highlighting, etc.

7
# File: chaos.py
# A simple program illustrating chaotic behaviour

def main():
print("This program illustrates a chaotic function")
x = eval(input("Enter a number between 0 and 1: "))
for i in range(10):
x = 3.9 * x * (1 - x)
print(x)

main()
• We’ll use filename.py when we save our work to indicate it’s
a Python program.
• In this code we’re defining a new function called main.
• The main() at the end tells Python to run the code.

8
# File: chaos.py
# A simple program illustrating chaotic behaviour
• Lines that start with # are called comments
• Intended for human readers and ignored by Python
• Python skips text from # to end of line
• def main():
• Beginning of the definition of a function called main
• Since our program has only this one module, it could have
been written without the main function.
• The use of main is customary, however.

9
print("This program illustrates a chaotic function")

• This line causes Python to print a message introducing the


program.
x = eval(input("Enter a number between 0 and 1: "))

• x is an example of a variable
• A variable is used to assign a name to a value so that we can
refer to it later.
• The quoted information is displayed, and the number typed
in response is stored in x

10
for i in range(10):
• For is a loop construct
• A loop tells Python to repeat the same thing over and over.
• In this example, the following code will be repeated 10
times.
x = 3.9 * x * (1 - x)
print(x)
• These lines are the body of the loop.
• The body of the loop is what gets repeated each time
through the loop.
• The body of the loop is identified through indentation.
• The effect of the loop is the same as repeating this two
lines 10 times!
11
12
x = 3.9 * x * (1 - x)

• This is called an assignment statement


• The part on the right-hand side (RHS) of the “=“ is a
mathematical expression.
• * is used to indicate multiplication
• Once the value on the RHS is computed, it is stored back
into (assigned) into x
main()

• This last line tells Python to execute the code in the


function main

13
• Chaos and Computers
• The chaos.py program:
def main():
print("This program illustrates a chaotic function")
x = eval(input("Enter a number between 0 and 1: "))
for i in range(10):
x = 3.9 * x * (1 - x)
print(x)
main()
• For any given input, returns 10 seemingly
random numbers between 0 and 1
• It appears that the value of x is chaotic
14
S/W Development Process

• Analyze the Problem


• Determine Specifications
• Create a Design
• Implement the Design
• Test/Debug the Program
• Maintain the Program

15
Example
#convert.py
# A program to convert Celsius temps to Fahrenheit
# by: writer’s name

def main():
celsius = eval(input("What is the Celsius temperature? "))
fahrenheit = (9/5) * celsius + 32
print("The temperature is ",fahrenheit," degrees Fahrenheit.")

main()

16
Elements of Programs

• Names
• Names are given to variables (celsius, fahrenheit), modules (main,
convert), etc.

• These names are called identifiers

• Every identifier must begin with a letter or underscore (“_”),


followed by any sequence of letters, digits, or underscores.

• Identifiers are case sensitive.

17
Elements of Programs
• Some identifiers are part of Python itself.
• These identifiers are known as reserved words. This means they are not
available for you to use as a name for a variable, etc. in your program.
• and, del, for, is, raise, assert, elif, in, print, etc

• Expressions
• The fragments of code that produce or calculate new data values are
called expressions.
• Literals are used to represent a specific value, e.g. 3.9, 1, 1.0
• Simple identifiers can also be expressions

18
Elements of Programs
>>> a = 5
>>> print(a)
5
>>> print(key)
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
NameError: name 'key' is not defined
>>>
• NameError is the error when you try to use a variable without a value
assigned to it.

19
• Simpler expressions can be combined using operators.
• +, -, *, /, **
• Spaces are irrelevant within an expression.
• The normal mathematical precedence applies.
• ((x1 – x2) / 2*n) + (key / k**3)
• Output Statements
• A print statement can print any number of expressions.
• Successive print statements will display on separate lines.
• A bare print will print a blank line.

20
21
Assignment Statements

• Simple Assignment
• <variable> = <expr>
variable is an identifier, expr is an expression
• The expression on the RHS is evaluated to produce a
value which is then associated with the variable named
on the LHS.

22
Assignment Statements
• Variables can be reassigned as many times as you want!
>>> myVar = 10
>>> myVar
10
>>> myVar = 6
>>> myVar
6
>>> myVar = myVar + 8
>>> myVar

>>>

23
Assignment statements

• Variables are like a box we can put values in.


• When a variable changes, the old value is erased and a new
one is written in.

24
Assignment Statements

• Technically, this model of assignment is simplistic


for Python.
• Python doesn't overwrite these memory locations
(boxes).
• Assigning a variable is more like putting a “sticky
note” on a value and saying, “this is x”.

25
Assigning Input
• The purpose of an input statement is to get input from the
user and store it into a variable.
• <variable> = eval(input(<prompt>))
• First the prompt is printed
• The input part waits for the user to enter a value and press
<enter>
• The expression that was entered is evaluated to turn it
from a string of characters into a Python value (a number).
• The value is assigned to the variable.

26
Simultaneous Assignment
• Several values can be calculated at the same time
• <var>, <var>, … = <expr>, <expr>, …
• Evaluate the expressions in the RHS and assign them to the
variables on the LHS
• sum, diff = x+y, x-y
• How could you use this to swap the values for x and y?
• Why doesn’t this work?
x=y
y=x
• We could use a temporary variable…

27
Simultaneous Assignment
• We can swap the values of two variables quite easily in
Python!
• x, y = y, x
>>> x = 3
>>> y = 4
>>> print x, y
34
>>> x, y = y, x
>>> print x, y
43

28
Definite Loop
• A definite loop executes a definite number of times, i.e., at
the time Python starts the loop it knows exactly how many
iterations to do.
• for <var> in <sequence>:
<body>
• The beginning and end of the body are indicated by
indentation
for <var> in <sequence>:
<body>
• The variable after the for is called the loop index. It takes
on each successive value in sequence.

29
>>> for i in [0,1,2,3]:
print (i)

0
1
2
3
>>> for odd in [1, 3, 5, 7]:
print(odd*odd)

1
9
25
49

>>>

30
• >>> list(range(10))
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
• range is a built-in Python function that generates a sequence
of numbers, starting with 0
• In chaos.py, what did range(10) do?
list is a built-in Python function that turns the sequence into
an explicit list
• The body of the loop executes 10 times

31
For loop
• for loops alter the flow of program execution, so they are
referred to as control structures.

32
Example Program: Future Value
• Analysis
• Money deposited in a bank account earns interest.
• How much will the account be worth 10 years from now?
• Inputs: principal, interest rate
• Output: value of the investment in 10 years
• Specification
• User enters the initial amount to invest, the principal
• User enters an annual percentage rate, the interest
• The specifications can be represented like this …

33
Example Program: Future Value
• Design
Print an introduction
Input the amount of the principal (principal)
Input the annual percentage rate (apr)
Repeat 10 times:
principal = principal * (1 + apr)
Output the value of principal

34
Example Program: Future Value
• Implementation
• Each line translates to one line of Python (in this case)
• Print an introduction
print ("This program calculates the future")
print ("value of a 10-year investment.")
• Input the amount of the principal
principal = eval(input("Enter the initial principal: "))

35
• Input the annual percentage rate
apr = eval(input("Enter the annual interest rate: "))
• Repeat 10 times:
for i in range(10):
• Calculate principal = principal * (1 + apr)
principal = principal * (1 + apr)
• Output the value of the principal at the end
of 10 years
print ("The value in 10 years is:", principal)

36
# futval.py
# A program to compute the value of an investment
# carried 10 years into the future

def main():
print("This program calculates the future value of a 10-year investment.")

principal = eval(input("Enter the initial principal: "))


apr = eval(input("Enter the annual interest rate: "))

for i in range(10):
principal = principal * (1 + apr)

print ("The value in 10 years is:", principal)

main()

37
>>> main()
This program calculates the future value of a 10-year
investment.
Enter the initial principal: 100
Enter the annual interest rate: .03
The value in 10 years is: 134.391637934
>>> main()
This program calculates the future value of a 10-year
investment.
Enter the initial principal: 100
Enter the annual interest rate: .10
The value in 10 years is: 259.37424601

38
Working with numbers
• To understand the concept of data types.
• To be familiar with the basic numeric data types in Python.
• To understand the fundamental principles of how numbers
are represented on a computer.
• To be able to use the Python math library.
• To understand the accumulator program pattern.
• To be able to read and write programs that process
numerical data.

39
• The information that is stored and manipulated bu
computers programs is referred to as data.
• There are two different kinds of numbers!
• (5, 4, 3, 6) are whole numbers – they don’t have a fractional part
• (.25, .10, .05, .01) are decimal fractions
• Inside the computer, whole numbers and decimal fractions are
represented quite differently!
• We say that decimal fractions and whole numbers are two
different data types.
• The data type of an object determines what values it can
have and what operations can be performed on it.

40
Numeric data types
• Whole numbers are represented using the integer (int for
short) data type.
• These values can be positive or negative whole numbers.
• Numbers that can have fractional parts are represented as
floating point (or float) values.
• How can we tell which is which?
• A numeric literal without a decimal point produces an int value
• A literal that has a decimal point is represented by a float (even if
the fractional part is 0)

41
• Python has a special function to tell us the data type of
any value.
>>> type(3)
<class 'int'>
>>> type(3.1)
<class 'float'>
>>> type(3.0)
<class 'float'>
>>> myInt = 32
>>> type(myInt)
<class 'int'>
>>>

42
• Why do we need two number types?
• Values that represent counts can’t be fractional (you
can’t have 3 ½ quarters)
• Most mathematical algorithms are very efficient with
integers
• The float type stores only an approximation to the real
number being represented!
• Since floats aren’t exact, use an int whenever possible!
• Operations on ints produce ints,
operations on floats produce floats
(except for /).

43
>>> 3.0+4.0
7.0
>>> 3+4
7
>>> 3.0*4.0
12.0
>>> 3*4
12
>>> 10.0/3.0
3.3333333333333335
>>> 10/3
3.3333333333333335
>>> 10 // 3
3
>>> 10.0 // 3.0
3.0

44
• Integer division produces a whole number.
• That’s why 10//3 = 3!
• Think of it as ‘gozinta’, where 10//3 = 3 since 3
gozinta (goes into) 10 3 times (with a remainder of 1)
• 10%3 = 1 is the remainder of the integer division of
10 by 3.
• a = (a/b)(b) + (a%b)
• Besides (+, -, *, /, //, **, %, abs), we have lots of
other math functions available in a math library.
• A library is a module with some useful definitions
/functions.
45
Math Library
• Write a program to compute the roots of a quadratic
equation!
−𝑏 ± 𝑏 2 − 4𝑎𝑐
𝑥=
2𝑎

Try yourself.
• The only part of this we don’t know how to do is find a
square root… but it’s in the math library!
• To access the sqrt library routine, we need to access it as
math.sqrt(x).

46
• Using this dot notation tells Python to use the sqrt function
found in the math library module.
• To calculate the root, you can do
discRoot = math.sqrt(b*b – 4*a*c)

47
# quadratic.py
# A program that computes the real roots of a quadratic equation.
# Illustrates use of the math library.
# Note: This program crashes if the equation has no real roots.

import math # Makes the math library available.

def main():
print("This program finds the real solutions to a quadratic")
print()

a, b, c = eval(input("Please enter the coefficients (a, b, c): "))

uneqRoot = math.sqrt(b * b - 4 * a * c)
root1 = (-b + discRoot) / (2 * a)
root2 = (-b - discRoot) / (2 * a)

print()
print("The solutions are:", root1, root2 )

main()

48
This program finds the real solutions to a quadratic

Please enter the coefficients (a, b, c): 3, 4, -1

The solutions are: 0.215250437022 -1.54858377035

• What do you suppose this means?


This program finds the real solutions to a quadratic

Please enter the coefficients (a, b, c): 1, 2, 3

Traceback (most recent call last):


File "<stdin>", line 1, in <module>
File "<stdin>", line 5, in main
ValueError: math domain error
>>>
Why this error?

49
Accumulating Results: Factorial

• n ! = 1 x 2 x 3 x4 x…xn
• n! = n(n-1) (n-2)….1
• 5! = 5*4*3*2*1
• Note 0! = 1 (justify)
• How we could we write a program to do this?
• Input number to take factorial of, n
Compute factorial of n, fact
Output fact

50
• It looks like we’ll need a loop!
fact = 1
for factor in [6, 5, 4, 3, 2, 1]:
fact = fact * factor
• Let’s trace through it to verify that this works!
• Why did we need to initialize fact to 1? There are a couple
reasons…
• Each time through the loop, the previous value of fact is
used to calculate the next value of fact. By doing the
initialization, you know fact will have a value the first
time through.
• If you use fact without assigning it a value, what does
Python do?
51
• Since multiplication is associative and commutative, we can
rewrite our program as:
fact = 1
for factor in [2, 3, 4, 5, 6]:
fact = fact * factor
• Great! But what if we want to find the factorial of some
other number??

52
• What does range(n) return?
0, 1, 2, 3, …, n-1
• range has another optional parameter! range(start, n)
returns
start, start + 1, …, n-1
• But wait! There’s more!
range(start, n, step)
start, start+step, …, n-1
• list(<sequence>) to make a list

53
• Let’s try some examples!
>>> list(range(10))
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
>>> list(range(5,10))
[5, 6, 7, 8, 9]
>>> list(range(5,10,2))
[5, 7, 9]

54
• Using this souped-up range statement, we can do the
range for our loop a couple different ways.
• We can count up from 2 to n:
range(2, n+1)
(Why did we have to use n+1?)
• We can count down from n to 2:
range(n, 1, -1)

55
# factorial.py
# Program to compute the factorial of a number
# Illustrates for loop with an accumulator

def main():
n = eval(input("Please enter a whole number: "))
fact = 1
for factor in range(n,1,-1):
fact = fact * factor
print("The factorial of", n, "is", fact)

main()
56
• What is 100!?
>>> main()
Please enter a whole number: 100
The factorial of 100 is
93326215443944152681699238856266700490715968264
381621468592963895217599993229915608941463976156
51828625369792082722375825118521091686400000000
0000000000000000
• Wow! That’s a pretty big number!

57
• Typical PCs use 64 bits
• That means there are 232 possible values, centered at 0.
• This range then is –231 to 231-1. We need to subtract one
from the top end to account for 0.
• But our 100! is much larger than this. How does it work?
• HW: If PC uses 64 bits, then ??

58
• Does switching to float data types get us around the
limitations of ints?
• If we initialize the accumulator to 1.0, we get
>>> main()
Please enter a whole number: 15
The factorial of 15 is 1.307674368e+012
• We no longer get an exact answer!

59
• Very large and very small numbers are expressed in
scientific or exponential notation.
• 1.307674368e+012 means 1.307674368 * 1012
• Here the decimal needs to be moved right 12 decimal places
to get the original number, but there are only 9 digits, so 3
digits of precision have been lost.

60
• Floats are approximations
• Floats allow us to represent a larger range of values, but
with lower precision.
• Python has a solution, expanding ints!
• Python Ints are not a fixed size and expand to handle
whatever value it holds.
• Newer versions of Python automatically convert your ints to
expanded form when they grow so large as to overflow.
• We get indefinitely large values (e.g. 100!) at the cost of
speed and memory

61
• We know that combining an int with an int produces
an int, and combining a float with a float produces a
float.
• What happens when you mix an int and float in an
expression?
x = 5.0 + 2
• What do you think should happen?

62
• For Python to evaluate this expression, it must
either convert 5.0 to 5 and do an integer addition, or
convert 2 to 2.0 and do a floating point addition.
• Converting a float to an int will lose information
• Ints can be converted to floats by adding “.0”
• In mixed-typed expressions Python will convert ints
to floats.
• Sometimes we want to control the type conversion.
This is called explicit typing

63
Type Conversions
>>> float(22//5)
4.0
>>> int(4.5)
4
>>> int(3.9)
3
>>> round(3.9)
4
>>> round(3)
3

64
65
Sequences: Strings, Lists, and Files

66
The String Data Type

• Text is represented in programs by the string data type.


• A string is a sequence of characters enclosed within
quotation marks (") or apostrophes (').

67
The String Data Type
>>> str1="Hello"
>>> str2='spam'
>>> print(str1, str2)
Hello spam
>>> type(str1)
<class 'str'>
>>> type(str2)
<class 'str'>

68
The String Data Type
• Getting a string as input
>>> firstName = input("Please enter your name: ")
Please enter your name Ram
>>> print("Hello", firstName)
Hello RAM

• Notice that the input is not evaluated. We want to store the


typed characters, not to evaluate them as a Python
expression.

69
The String Data Type
• We can access the individual characters in a string through
indexing.
• The positions in a string are numbered from the left,
starting with 0.
• The general form is <string>[<expr>], where the value of
expr determines which character is selected from the
string.

70
The String Data Type
H e l l o B o b

0 1 2 3 4 5 6 7 8
>>> greet = "Hello Bob"
>>> greet[0]
'H'
>>> print(greet[0], greet[2], greet[4])
Hlo
>>> x = 8
>>> print(greet[x - 2])
B

71
The String Data Type
H e l l o B o b

0 1 2 3 4 5 6 7 8
• In a string of n characters, the last character is at
position n-1 since we start counting with 0.
• We can index from the right side using negative
indexes.
>>> greet[-1]
'b'
>>> greet[-3]
'B'

72
The String Data Type
• Indexing returns a string containing a single character from
a larger string.
• We can also access a contiguous sequence of characters,
called a substring, through a process called slicing.

73
The String Data Type
• Slicing:
<string>[<start>:<end>]
• start and end should both be ints
• The slice contains the substring beginning at position start
and runs up to but doesn’t include the position end.

74
The String Data Type
H e l l o B o b

0 1 2 3 4 5 6 7 8
>>> greet[0:3]
'Hel'
>>> greet[5:9]
' Bob'
>>> greet[:5]
'Hello'
>>> greet[5:]
' Bob'
>>> greet[:]
'Hello Bob'

75
The String Data Type
• If either expression is missing, then the start or the end of
the string are used.
• Can we put two strings together into a longer string?
• Concatenation “glues” two strings together (+)
• Repetition builds up a string by multiple concatenations of a
string with itself (*)

76
The String Data Type
• The function len will return the length of a string.
>>> "spam" + "eggs"
'spameggs'
>>> "Spam" + "And" + "Eggs"
'SpamAndEggs'
>>> 3 * "spam"
'spamspamspam'
>>> "spam" * 5
'spamspamspamspamspam'
>>> (3 * "spam") + ("eggs" * 5)
'spamspamspameggseggseggseggseggs'

77
The String Data Type
>>> len("spam")
4
>>> for ch in "Spam!":
print (ch, end=" ")

Spam!

78
The String Data Type
Operator Meaning
+ Concatenation
* Repetition
<string>[] Indexing
<string>[:] Slicing
len(<string>) Length
for <var> in <string> Iteration through characters

79
Simple String Processing
• Usernames on a computer system
• First initial, first seven characters of last name

# get user’s first and last names


first = input("Please enter your first name (all lowercase): ")
last = input("Please enter your last name (all lowercase): ")

# concatenate first initial with 7 chars of last name


uname = first[0] + last[:7]

80
Strings, Lists, and Sequences
• It turns out that strings are really a special kind of
sequence, so these operations also apply to sequences!
>>> [1,2] + [3,4]
[1, 2, 3, 4]
>>> [1,2]*3
[1, 2, 1, 2, 1, 2]
>>> grades = ['A', 'B', 'C', 'D', 'F']
>>> grades[0]
'A'
>>> grades[2:4]
['C', 'D']
>>> len(grades)
5

81
Strings, Lists, and Sequences
• Strings are always sequences of characters, but lists can be
sequences of arbitrary values.
• Lists can have numbers, strings, or both!

myList = [1, "Spam ", 4, "U"]

82
Strings, Lists, and Sequences
• We can make a list of months:
months = ["Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov",
"Dec"]

• To get the months out of the sequence, do this:


monthAbbrev = months[n-1]
print(monthAbbrev)

83
Strings, Lists, and Sequences
# month2.py
# A program to print the month name, given it's number.
# This version uses a list as a lookup table.

def main():

# months is a list used as a lookup table


months = ["Jan", "Feb", "Mar", "Apr", "May", "Jun",
"Jul", "Aug", "Sep", "Oct", "Nov", "Dec"]

n = eval(input("Enter a month number (1-12): "))

print ("The month abbreviation is", months[n-1] + ".")

main()

• Note that the months line overlaps a line. Python knows that the
expression isn’t complete until the closing ] is encountered.

84
Strings, Lists, and Sequences
# month2.py
# A program to print the month name, given it's number.
# This version uses a list as a lookup table.

def main():

# months is a list used as a lookup table


months = ["Jan", "Feb", "Mar", "Apr", "May", "Jun",
"Jul", "Aug", "Sep", "Oct", "Nov", "Dec"]

n = eval(input("Enter a month number (1-12): "))

print ("The month abbreviation is", months[n-1] + ".")

main()

• Since the list is indexed starting from 0, the n-1 calculation is


straight-forward enough to put in the print statement without
needing a separate step.

85
Strings, Lists, and Sequences

• This version of the program is easy to extend to print out


the whole month name rather than an abbreviation!
months = ["January", "February", "March", "April", "May", "June",
"July", "August", "September", "October", "November", "December"]

86
Strings, Lists, and Sequences
• Lists are mutable, meaning they can be changed. Strings can not
be changed.
>>> myList = [34, 26, 15, 10]
>>> myList[2]
15
>>> myList[2] = 0
>>> myList
[34, 26, 0, 10]
>>> myString = "Hello World"
>>> myString[2]
'l'
>>> myString[2] = "p"

Traceback (most recent call last):


File "<pyshell#16>", line 1, in -toplevel-
myString[2] = "p"
TypeError: object doesn't support item assignment

87
Strings and Character Numbers
• Inside the computer, strings are represented as sequences
of 1’s and 0’s, just like numbers.
• A string is stored as a sequence of binary numbers, one
number per character.
• It doesn’t matter what value is assigned as long as it’s done
consistently.

88
Strings and Character Numbers
• In the early days of computers, each manufacturer used
their own encoding of numbers for characters.
• ASCII system (American Standard Code for Information
Interchange) uses 127 bit codes
• Python supports Unicode (100,000+ characters)

89
Strings and Character Numbers
• The ord function returns the numeric (ordinal) code of a single
character.
• The chr function converts a numeric code to the corresponding
character.
>>> ord("A")
65
>>> ord("a")
97
>>> chr(97)
'a'
>>> chr(65)
'A'

90
Other String Methods
• There are a number of other string methods. Try them all!
• s.capitalize() – Copy of s with only the first character capitalized
• s.title() – Copy of s; first character of each word capitalized
• s.center(width) – Center s in a field of given width

91
Other String Operations
• s.count(sub) – Count the number of occurrences of sub in s
• s.find(sub) – Find the first position where sub occurs in s
• s.join(list) – Concatenate list of strings into one large string using s
as separator.
• s.ljust(width) – Like center, but s is left-justified

92
Other String Operations
• s.lower() – Copy of s in all lowercase letters
• s.lstrip() – Copy of s with leading whitespace removed
• s.replace(oldsub, newsub) – Replace occurrences of oldsub in s with
newsub
• s.rfind(sub) – Like find, but returns the right-most position
• s.rjust(width) – Like center, but s is right-justified

93
Other String Operations
• s.rstrip() – Copy of s with trailing whitespace removed
• s.split() – Split s into a list of substrings
• s.upper() – Copy of s; all characters converted to uppercase

94
Input/Output as String Manipulation
• Often we will need to do some string operations to prepare
our string data for output (“pretty it up”)
• Let’s say we want to enter a date in the format
“05/24/2003” and output “May 24, 2003.” How could we do
that?

95
Input/Output as String Manipulation
• Input the date in mm/dd/yyyy format (dateStr)
• Split dateStr into month, day, and year strings
• Convert the month string into a month number
• Use the month number to lookup the month name
• Create a new date string in the form “Month Day, Year”
• Output the new date string

96
Input/Output as String Manipulation
• The first two lines are easily implemented!
dateStr = input("Enter a date (mm/dd/yyyy): ")
monthStr, dayStr, yearStr = dateStr.split("/")
• The date is input as a string, and then “unpacked” into the
three variables by splitting it at the slashes and using
simultaneous assignment.

97
Input/Output as String Manipulation
• Next step: Convert monthStr into a number
• We can use the int function on monthStr to convert "05",
for example, into the integer 5. (int("05") = 5)

98
Input/Output as String Manipulation
• Note: eval would work, but for the leading 0
>>> int("05")
5
>>> eval("05")
Traceback (most recent call last):
File "<pyshell#9>", line 1, in <module>
eval("05")
File "<string>", line 1
05
^
SyntaxError: invalid token

• This is historical baggage. A leading 0 used to be


used for base 8 (octal) literals in Python.

99
Input/Output as String Manipulation
months = [“January”, “February”, …, “December”]
monthStr = months[int(monthStr) – 1]
• Remember that since we start counting at 0, we need to
subtract one from the month.
• Now let’s concatenate the output string together!

100
Input/Output as String Manipulation
print ("The converted date is:", monthStr, dayStr+",", yearStr)

• Notice how the comma is appended to dayStr with


concatenation!
• >>> main()
Enter a date (mm/dd/yyyy): 01/23/2010
The converted date is: January 23, 2010

101
Input/Output as String Manipulation
• Sometimes we want to convert a number into a string.
• We can use the str function.
>>> str(500)
'500'
>>> value = 3.14
>>> str(value)
'3.14'
>>> print("The value is", str(value) + ".")
The value is 3.14.

102
Input/Output as String Manipulation
• If value is a string, we can concatenate a period onto the
end of it.
• If value is an int, what happens?
>>> value = 3.14
>>> print("The value is", value + ".")
The value is

Traceback (most recent call last):


File "<pyshell#10>", line 1, in -toplevel-
print "The value is", value + "."
TypeError: unsupported operand type(s) for +: 'float' and 'str'

103
Input/Output as String Manipulation
• We now have a complete set of type conversion operations:

Function Meaning

float(<expr>) Convert expr to a floating point value

int(<expr>) Convert expr to an integer value

str(<expr>) Return a string representation of expr

eval(<string>) Evaluate string as an expression

104
String Formatting
• String formatting is an easy way to get beautiful output!
Change Counter

Please enter the count of each coin type.


Quarters: 6
Dimes: 0
Nickels: 0
Pennies: 0

The total value of your change is 1.5

• Shouldn’t that be more like $1.50??

105
String Formatting
• We can format our output by modifying the print statement
as follows:
print("The total value of your change is ${0:0.2f}".format(total))

• Now we get something like:


The total value of your change is $1.50

• Key is the string format method.

106
String Formatting
• <template-string>.format(<values>)
• {} within the template-string mark “slots” into which the
values are inserted.
• Each slot has description that includes format specifier
telling Python how the value for the slot should appear.

107
String Formatting
print("The total value of your change is ${0:0.2f}".format(total)
• The template contains a single slot with the description:
0:0.2f
• Form of description:
<index>:<format-specifier>
• Index tells which parameter to insert into the slot. In this
case, total.

108
String Formatting
• The formatting specifier has the form:
<width>.<precision><type>
• f means "fixed point" number
• <width> tells us how many spaces to use to display the value.
0 means to use as much space as necessary.
• <precision> is the number of decimal places.

109
String Formatting
>>> "Hello {0} {1}, you may have won ${2}" .format("Mr.", "Smith", 10000)
'Hello Mr. Smith, you may have won $10000'

>>> 'This int, {0:5}, was placed in a field of width 5'.format(7)


'This int, 7, was placed in a field of width 5'

>>> 'This int, {0:10}, was placed in a field of witdh 10'.format(10)


'This int, 10, was placed in a field of witdh 10'

>>> 'This float, {0:10.5}, has width 10 and precision 5.'.format(3.1415926)


'This float, 3.1416, has width 10 and precision 5.'

>>> 'This float, {0:10.5f}, is fixed at 5 decimal places.'.format(3.1415926)


'This float, 3.14159, has width 0 and precision 5.'

110
String Formatting
• If the width is wider than needed, numeric values are right-
justified and strings are left- justified, by default.
• You can also specify a justification before the width.
>>> "left justification: {0:<5}.format("Hi!")
'left justification: Hi! '
>>> "right justification: {0:>5}.format("Hi!")
'right justification: Hi!'
>>> "centered: {0:^5}".format("Hi!")
'centered: Hi! '

111
Better Change Counter
• With what we know now about floating point numbers, we
might be uneasy about using them in a money situation.
• One way around this problem is to keep trace of money in
cents using an int or long int, and convert it into dollars and
cents when output.

112
Better Change Counter
• If total is a value in cents (an int),
dollars = total//100
cents = total%100
• Cents is printed using width 0>2 to right-justify it with
leading 0s (if necessary) into a field of width 2.
• Thus 5 cents becomes '05'

113
Better Change Counter
# change2.py
# A program to calculate the value of some change in dollars.
# This version represents the total cash in cents.

def main():
print ("Change Counter\n")

print ("Please enter the count of each coin type.")


quarters = eval(input("Quarters: "))
dimes = eval(input("Dimes: "))
nickels = eval(input("Nickels: "))
pennies = eval(input("Pennies: "))
total = quarters * 25 + dimes * 10 + nickels * 5 + pennies

print ("The total value of your change is ${0}.{1:0>2}"


.format(total//100, total%100))

114
Better Change Counter
>>> main() >>> main()
Change Counter Change Counter

Please enter the count of each coin Please enter the count of each coin
type. type.
Quarters: 0 Quarters: 12
Dimes: 0 Dimes: 1
Nickels: 0 Nickels: 0
Pennies: 1 Pennies: 4

The total value of your change is $0.01 The total value of your change is $3.14

115
Files: Multi-line Strings
• A file is a sequence of data that is stored in secondary
memory (disk drive).
• Files can contain any data type, but the easiest to work with
are text.
• A file usually contains more than one line of text.
• Python uses the standard newline character (\n) to mark line
breaks.

116
Multi-Line Strings
• Hello
World

Goodbye 32
• When stored in a file:
Hello\nWorld\n\nGoodbye 32\n

117
Multi-Line Strings

• This is exactly the same thing as embedding \n in print


statements.
• Remember, these special characters only affect things when
printed. They don’t do anything during evaluation.

118
File Processing
• The process of opening a file involves associating a file on disk with an
object in memory.
• We can manipulate the file by manipulating this object.
• Read from the file
• Write to the file

119
File Processing
• When done with the file, it needs to be closed. Closing the file causes
any outstanding operations and other bookkeeping for the file to be
completed.
• In some cases, not properly closing a file could result in data loss.

120
File Processing
• Reading a file into a word processor
• File opened
• Contents read into RAM
• File closed
• Changes to the file are made to the copy stored in memory, not on the disk.

121
File Processing
• Saving a word processing file
• The original file on the disk is reopened in a mode that will allow writing (this
actually erases the old contents)
• File writing operations copy the version of the document in memory to the
disk
• The file is closed

122
File Processing
• Working with text files in Python
• Associate a disk file with a file object using the open function
<filevar> = open(<name>, <mode>)
• Name is a string with the actual file name on the disk. The mode is either ‘r’
or ‘w’ depending on whether we are reading or writing the file.
• Infile = open("numbers.dat", "r")

123
File Methods
• <file>.read() – returns the entire remaining contents of the file as a
single (possibly large, multi-line) string
• <file>.readline() – returns the next line of the file. This is all text up to
and including the next newline character
• <file>.readlines() – returns a list of the remaining lines in the file. Each
list item is a single line including the newline characters.

124
File Processing
# printfile.py
# Prints a file to the screen.

def main():
fname = input("Enter filename: ")
infile = open(fname,'r')
data = infile.read()
print(data)

main()

• First, prompt the user for a file name


• Open the file for reading
• The file is read as one string and stored in the variable data

125
File Processing
• readline can be used to read the next line from a file, including the
trailing newline character
• infile = open(someFile, "r")
for i in range(5):
line = infile.readline()
print line[:-1]

• This reads the first 5 lines of a file


• Slicing is used to strip out the newline characters at the ends of the
lines

126
File Processing
• Another way to loop through the contents of a file is to read it in with
readlines and then loop through the resulting list.
• infile = open(someFile, "r")
for line in infile.readlines():
# Line processing here
infile.close()

127
File Processing
• Python treats the file itself as a sequence of lines!
• Infile = open(someFile, "r")
for line in infile:
# process the line here
infile.close()

128
File Processing
• Opening a file for writing prepares the file to receive data
• If you open an existing file for writing, you wipe out the file’s
contents. If the named file does not exist, a new one is created.
• Outfile = open("mydata.out", "w")
• print(<expressions>, file=Outfile)

129
Example Program: Batch Usernames
• Batch mode processing is where program input and output are done
through files (the program is not designed to be interactive)
• Let’s create usernames for a computer system where the first and last
names come from an input file.

130
Example Program: Batch Usernames
# userfile.py
# Program to create a file of usernames in batch mode.

def main():
print ("This program creates a file of usernames from a")
print ("file of names.")

# get the file names


infileName = input("What file are the names in? ")
outfileName = input("What file should the usernames go in? ")

# open the files


infile = open(infileName, 'r')
outfile = open(outfileName, 'w')

131
Example Program: Batch Usernames
# process each line of the input file
for line in infile:
# get the first and last names from line
first, last = line.split()
# create a username
uname = (first[0]+last[:7]).lower()
# write it to the output file
print(uname, file=outfile)

# close both files


infile.close()
outfile.close()

print("Usernames have been written to", outfileName)

132
Example Program: Batch Usernames
• Things to note:
• It’s not unusual for programs to have multiple files open for reading and
writing at the same time.
• The lower method is used to convert the names into all lower case, in the
event the names are mixed upper and lower case.

133
Objects & Graphic

134
Graphical User Interface (GUI)
• Most applications you’re familiar with have
Graphical User Interfaces (GUI) that provide
windows, icons, buttons, menus, and drawings.
• Before the invention of GUIs by Xerox,
applications were text-based and used
computer terminals.
• Apple and Microsoft integrated GUIs in the
Macintosh and PCs.
• Now GUIs are widely available.

135
Object-Oriented Languages
• Modern computer languages are “Object Oriented”
• When representing the world it is easier to model the world based on
Objects: (Physical objects)
• teacher
• student
• apple
Methods: (What you can do with objects)
teacher.ask(question)
student.study(book)
apple.eat()
• Example of object-oriented computer languages are: Java, C#, C++,
Python
• Languages that are not object-oriented: C, Basic, Fortran, Pascal.

136
graphics.py
• There’s a graphics library (graphics.py) written specifically
to go with the textbook. It’s based on Tkinter.
• You can download it from:
http://mcsp.wartburg.edu/zelle/python/graphics.py
• Save it in the same directory where your graphics programs
are located.
• Alternatively you can put it in Python’s Lib directory with
other libraries

137
Simple Graphics Programming
• Since this is a library, we need to import the graphics
commands
import graphics
• A graphics window is a place on the screen where the
graphics will appear.
win = graphics.GraphWin()
• This command creates a new window titled “Graphics
Window.”

138
Simple Graphics Programming
• GraphWin is an object assigned to the variable win. We can
manipulate the window object through this variable, similar to
manipulating files through file variables.
• Windows can be closed/destroyed by issuing the command
win.close()
• If you don’t close the window you have to kill the program.

139
Simple Graphics Programming
• It’s tedious to use the graphics. notation to access the graphics
library routines.
• from graphics import *
The “from” statement allows you to load specific functions from a
library module. “*” will load all the functions, or you can list specific
ones.

140
Simple Graphics Programming
• Doing the import this way eliminates the need to preface graphics
commands with graphics.

from graphics import *


win = GraphWin()

141
Simple Graphics Programming
• A graphics window is a collection of points called pixels (picture
elements).
• The default GraphWin is 200 pixels tall by 200 pixels wide (40,000
pixels total).
• One way to get pictures into the window is one pixel at a time, which
would be tedious. The graphics routine has a number of predefined
routines to draw geometric shapes.

142
Scaling the Window
• To scale the window we do
win = GraphWin('Shapes', 400, 400)
win.setCoords(0.0, 0.0, 10.0, 10.0)
• This will make the lower left corner to be (0,0) and the upper right
corner to be (10,10)
• The size of the window is 400x400 pixels
• This will make drawing on the screen easier.

143
The screen
(0,10) (10,10)

400 pixels

(0,0) (10,0)

144
400 pixels
Simple Drawing
(0,10) (10,10)

(0,0) (10,0)

145
400 pixels
Simple Graphics Program
#
# graphics1.py - Simple graphics program.
#

from graphics import *

def Main():

#Create a window 400x400 pixels


win = GraphWin('Shapes', 400, 400)

# Make the window scaled


# bottom leftmost corner is (0,0)
# top rightmost corner is (10,10)
win.setCoords(0.0, 0.0, 10.0, 10.0)

146
Simple Graphics Program
#Draw a circle centered at 5,5
center = Point(5, 5)
circ = Circle(center, 4)
circ.setFill('yellow')
circ.draw(win)

# Draw left eye


eye1 = Circle(Point(3,6), 1)
eye1.setFill("red")
eye1.draw(win)

# Draw right eye


eye2 = Circle(Point(7,6), 1)
eye2.setFill("red")
eye2.draw(win)

147
Simple Graphics Program
# Draw mouth
rect = Rectangle(Point(4, 2), Point(6, 3))
rect.setFill("blue");
rect.draw(win)

# Draw line
line = Line(Point(1, 8), Point(9, 8))
line.draw(win)

# Draw message
message = Text(Point(5, 0.5), "Click anywhere to quit")
message.draw(win)

# Wait until we click mouse in the window


win.getMouse()

win.close()

Main()

148
Simple Graphics Programming
• The simplest object is the Point. Like points in geometry, point
locations are represented with a coordinate system (x, y), where x is
the horizontal location of the point and y is the vertical location.
• The origin (0,0) in a graphics window is the upper left corner.
• X values increase from right to left, y values from top to bottom.
• Lower right corner is (199, 199)

149
Simple Graphics Programming
from graphics import *
def Main():
win = GraphWin('Shapes', 400, 400)
p = Point(50, 50)
p.draw(win)

# draw the other point


p = Point(350, 350)
p.draw(win)

# Wait for a clink on the window


win.getMouse()

# Close window
win.close()

Main()

150
Simple Graphics Programming
>>> ### Open a graphics window
>>> win = GraphWin('Shapes')
>>> ### Draw a red circle centered at point (100, 100)
with radius 30
>>> center = Point(100, 100)
>>> circ = Circle(center, 30)
>>> circ.setFill('red')
>>> circ.draw(win)
>>> ### Put a textual label in the center of the circle
>>> label = Text(center, "Red Circle")
>>> label.draw(win)
>>> ### Draw a square using a Rectangle object
>>> rect = Rectangle(Point(30, 30), Point(70, 70))
>>> rect.draw(win)
>>> ### Draw a line segment using a Line object
>>> line = Line(Point(20, 30), Point(180, 165))
>>> line.draw(win)
>>> ### Draw an oval using the Oval object
>>> oval = Oval(Point(20, 150), Point(180, 199))
>>> oval.draw(win)

151
Using Graphical Objects
• Computation is preformed by asking an object to carry out one of its
operations.
• In the previous example we manipulated GraphWin, Point, Circle,
Oval, Line, Text and Rectangle. These are examples of classes.

152
Getting Mouse Clicks
• The following code reports the coordinates of a mouse click:
from graphics import *
win = GraphWin("Click Me!")
p = win.getMouse()
print("You clicked", p.getX(), p.getY())

• We can use the accessors like getX and getY or other methods on
the point returned.

153
Getting Mouse Clicks
# triangle.pyw
# Interactive graphics program to draw a triangle

from graphics import *

def main():
win = GraphWin("Draw a Triangle")
win.setCoords(0.0, 0.0, 10.0, 10.0)
message = Text(Point(5, 0.5), "Click on three points")
message.draw(win)

# Get and draw three vertices of triangle


p1 = win.getMouse()
p1.draw(win)
p2 = win.getMouse()
p2.draw(win)
p3 = win.getMouse()
p3.draw(win)

154
Getting Mouse Clicks
# Use Polygon object to draw the triangle
triangle = Polygon(p1,p2,p3)
triangle.setFill("peachpuff")
triangle.setOutline("cyan")
triangle.draw(win)

# Wait for another click to exit


message.setText("Click anywhere to quit.")
win.getMouse()

main()

155
Getting Mouse Clicks

156
Getting Mouse Clicks
• Notes:
• If you are programming in a windows environment, using the .pyw extension
on your file will cause the Python shell window to not display when you
double-click the program icon.
• There is no triangle class. Rather, we use the general polygon class, which
takes any number of points and connects them into a closed shape.

157
Getting Mouse Clicks
• Once you have three points, creating a triangle polygon is easy:
triangle = Polygon(p1, p2, p3)
• A single text object is created and drawn near the beginning of the program.
message = Text(Point(5,0.5), "Click on three points")
message.draw(win)
• To change the prompt, just change the text to be displayed.
message.setText("Click anywhere to quit.")

158
Handling Textual Input
• The triangle program’s input was done completely through mouse
clicks. There’s also an Entry object that can get keyboard input.
• The Entry object draws a box on the screen that can contain text. It
understands setText and getText, with one difference that the
input can be edited.

159
Handling Textual Input

160
Handling Textual Input
# convert_gui.pyw

# Program to convert Celsius to Fahrenheit using a simple

# graphical interface.

from graphics import *

def main():

win = GraphWin("Celsius Converter", 300, 200)

win.setCoords(0.0, 0.0, 3.0, 4.0)

# Draw the interface

Text(Point(1,3), " Celsius Temperature:").draw(win)

Text(Point(1,1), "Fahrenheit Temperature:").draw(win)

input = Entry(Point(2,3), 5)

input.setText("0.0")

input.draw(win)

output = Text(Point(2,1),"")

output.draw(win)

button = Text(Point(1.5,2.0),"Convert It")

button.draw(win)

Rectangle(Point(1,1.5), Point(2,2.5)).draw(win)

161
Handling Textual Input
# wait for a mouse click
win.getMouse()

# convert input
celsius = eval(input.getText())
fahrenheit = 9.0/5.0 * celsius + 32

# display output and change button


output.setText(fahrenheit)
button.setText("Quit")

# wait for click and then quit


win.getMouse()
win.close()

main()

162
Handling Textual Input

163
Handling Textual Input
• When run, this program produces a window with an entry box for
typing in the Celsius temperature and a button to “do” the
conversion.
• The button is for show only! We are just waiting for a mouse click anywhere in
the window.

164
Handling Textual Input
• Initially, the input entry box is set to contain “0.0”.
• The user can delete this value and type in another value.
• The program pauses until the user clicks the mouse – we don’t care
where so we don’t store the point!

165
Handling Textual Input
• The input is processed in three steps:
• The value entered is converted into a number with eval.
• This number is converted to degrees Fahrenheit.
• This number is then converted to a string and formatted for display in the
output text area.

166
167
168
169
170
171

You might also like