0% found this document useful (0 votes)
8 views

Introductory Python

Python

Uploaded by

dave128969544
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
8 views

Introductory Python

Python

Uploaded by

dave128969544
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 65

An Introduction to:

Programming with Python

Variables, types, statements, functions

1
Last Time

¤Brief History of Computing


¤Due:
¤ PA1 (Tuesday Night)
¤ PS1 (now!)

2
Reminders

¤ Lab Today

¤ My OH are today

¤ OLI Iteration Module Tonight

¤PS2 due Friday, July 5th at 9:00AM

3
Questions

¤ How was submission process:


¤ Gradescope – PA/PS/Lab

¤ How was the OLI module?

4
Today’s Lecture

¤ Introduction to Python

¤ Mechanics

¤ Some Specifics:
¤ Programming Languages
¤ Basic datatypes
¤ Variables
¤ Functions

5
Hardware versus Software

software

….. hardware

6
Execution of Python Programs

When you write a


program in Python,
Java etc. It does not
run directly on the OS.

Another program
called an
interpreter or virtual
machine takes it and
runs it for you
translating your
commands into the

language of the OS.
7
Execution of Python Programs

We will write Python


programs that are
executed by the
Python Interpreter.

A Python Interpreter
for your OS already
exists. You can use the
one on lab machines,
install one for your
laptop, or use one
remotely

8
Using a Python Interpreter

There are two ways to interact with a Python interpreter:

1. Tell it to execute a program that is saved in a file with a


.py extension

2. Interact with it in a program called a shell

You will interact with Python in


both ways.

9
A Short Introduction to Python

¤ Starting the Python interpreter either using a Unix Server


at CMU or on your own computer
¤ See the Resources page for specific instructions

¤ Creating .py files with a text editor


¤ Files with the .py extension can be created by any editor but
needs a Python interpreter to be read.
¤ We have chosen editor editor for the course but you
may use an editor of your own choice if you feel comfortable.
¤ Why IDE? Why Not?

10
Programming Languages

11
A programming “language” is a
formal notation

12
Not a natural language

Recipe Computer program


Toast and cereal for i in range(5):
Toast the bread. Butter it. Put pritn(whatever I want)
some cereal in a bowl. Add mikl.
¤ Interpreted by a person ¤ Interpreted by a machine

¤ Unclear? Can be figured out ¤ …for a human (“somebody wants to


(What kind of bread? Butter? What print something”)
kind of milk?)
¤ Unclear? Not a program
¤ Typos? Can be figured out (“whatever I want”????)
(“mikl” means “milk”)
¤ Typos? Program errors
(“pritn”???)

13
A programming “language” is a
formal notation
for generalized problem solving

14
Programs should be general

Recipe Program
def force(mass, accel) :
¤
return mass*accel

Specific: “output” is two cups of General: output is force for any


sauce. combination of mass and
acceleration.

15
Python

¤ Python is one of many programming languages.

¤ 2 widely used versions. We will use Python 3.

¤ Running Python on the command line:

$ python3

or

$ python3 –i filename.py

16
Command Line Interfaces
Be aware of the difference between
“talking to the shell” and “talking to Python”

$ ssh [email protected]
[email protected]'s password:

[annpenny@unix2 ~]$ pwd
Talking to /afs/andrew.cmu.edu/usr14/annpenny
the shell [annpenny@unix2 ~]$ python3
Python 3.3.2 (default, Aug 12 2013, 13:12:23)
[GCC 4.6.3] on linux
Type "help", "copyright", "credits" or
"license" for more information.
Talking to >>> quit()
Python

17
Command Line Interfaces
Be aware of the difference between
“talking to the shell” and “talking to Python”

Shell $ ssh [email protected]


prompt [email protected]'s password:
… User input
[annpenny@unix2 ~]$ pwd
Talking to /afs/andrew.cmu.edu/usr14/annpenny Ask shell to
the shell [annpenny@unix2 ~]$ python3 run Python
Python 3.3.2 (default, Aug 12 2013, 13:12:23)
Shell [GCC 4.6.3] on linux
response Type "help", "copyright", "credits" or
"license" for more information.
Talking to >>> quit() Input to python
Python

18
Data Types

19
Data Types
¤ Integers 4 15110 -53 0

4.0 0.80333333333
¤ Floating Point Numbers 7.34e+014

"hello” "A" " " ””


¤ Strings 'there' '"' '15110’

¤ Booleans True False

¤ Literal None None


20
Arithmetic Expressions

¤ Mathematical Operators
+ Addition
- Subtraction // Integer division
* Multiplication ** Exponentiation
/ Division % Modulo (remainder)

¤ Python is
like a calculator: type an expression and it tells
you the value.
>> 2 + 3 * 5
Þ17

21
Order of Evaluation
Order of operator precedence:
() ** * / % + -

Use parentheses to force alternate precedence


5*6+7 ≠ 5 * (6 + 7)

Left associativity except for **


2 + 3 + 4 = (2 + 3) + 4
2 ** 3 ** 4 = 2 **(3 ** 4)

22
Integer Division

In Python3:

¤ 7 / 2 equals 3.5

¤ 7 // 2 equals 3

¤ 7 // 2.0 equals 3.0

¤ 7.0 // 2 equals 3.0

¤ -7 // 2 equals -4
¤ beware! // rounds down to smaller number,
not towards zero

23
Expressions and Statements
Know the difference!

¤ Python evaluates an expression to get a result (number or


other value)

¤ Python executes a statement to perform an action that has


an effect (printing something, for example)

24
Variables

25
Variables
¤ A variable is not an “unknown” as in algebra.

¤ In computer programming, a variable is a place where you can store a value.

¤ In Python we store a value using an assignment statement

>> a = 5
>> a a: 5
=> 5

26
Variables
¤ A variable is not an “unknown” as in algebra.

¤ In computer programming, a variable is a place where you can store a value.

¤ In Python we store a value using an assignment statement

>> a = 5
>> a a: 5
=> 5

27
Variables
¤ A variable is not an “unknown” as in algebra.

¤ In computer programming, a variable is a place where you can store a value.

¤ In Python we store a value using an assignment statement

>> a = 5
>> a a: 5
=> 5

28
Variables

>> a
Þ5 a: 5

>> b = 2 * a
>> b b: 10
Þ10

29
Variables

>> a
Þ5 a:
>> b “Woof”
Þ10
>> a = “Woof”
>> a b: 10
Þ“Woof”
>> b Variable b does not “remember” that its
Þ10 value came from variable a.

30
Variable Names

¤ All variable names must start with a letter (lowercase recommended).

¤ The remainder of the variable name (if any) can consist of any combination of:
¤ uppercase letters
¤ lowercase letters
¤ digits and underscores (_).

¤ Identifiers in Python are case sensitive.


¤ Example: Value is not the same as value.

31
Syntax and Semantics

32
Syntax vs. Semantics

Syntax Semantic
¤ Rules, structure ¤ Meaning

¤ Errors result when code is ¤ Error results when


not well formed expression/statement can’t
be evaluated or executed
due to meaning

Colorless green ideas sleep furiously

33
Colorless green ideas sleep furiously

It can only be the thought of verdure to come, which


prompts us in the autumn to buy these dormant white lumps
of vegetable matter covered by a brown papery skin, and
lovingly to plant them and care for them. It is a marvel to
me that under this cover they are laboring unseen at such a
rate within to give us the sudden awesome beauty of spring
flowering bulbs. While winter reigns the earth reposes but
these colorless green ideas sleep furiously.

34
Functions

35
Function Syntax

def functionname(parameterlist):
☐☐☐☐instructions

36
Function Syntax
def is a reserved word and
cannot be used as a variable name

def functionname(parameterlist):
☐☐☐☐instructions

37
Function Syntax
def is a reserved word and
cannot be used as a variable name

The name you give


to your function

def functionname(parameterlist):
☐☐☐☐instructions

38
Function Syntax
The parameter list can contain 1 or more
def is a reserved word and
variables that represent data to be used
cannot be used as a variable name
in the function’s computation

The name you give


to your function

def functionname(parameterlist):
☐☐☐☐instructions

39
Function Syntax
The parameter list can contain 1 or more
def is a reserved word and
variables that represent data to be used
cannot be used as a variable name
in the function’s computation

The name you give


to your function

def functionname(parameterlist):
☐☐☐☐instructions

Declares the start


of an indented block

40
Function Syntax
The parameter list can contain 1 or more
def is a reserved word and
variables that represent data to be used
cannot be used as a variable name
in the function’s computation

The name you give


to your function

def functionname(parameterlist):
☐☐☐☐instructions

Declares the start


of an indented block
Indentation is critical.
Use spaces only, not tabs!
41
Function Syntax
The parameter list can contain 1 or more
def is a reserved word and
variables that represent data to be used
cannot be used as a variable name
in the function’s computation

The name you give


to your function

def functionname(parameterlist):
☐☐☐☐instructions

Declares the start


of an indented block
Indentation is critical. Block of code
Use spaces only, not tabs!
42
Functions are general
¤ Function that takes 1 parameter: ¤ A function can also have no
parameters – but now it can only do
def multiply_5(val): one thing!

return val*5 def hello_world():

print("Hello World!\n”)

¤ Function that takes 3 parameters

def multiply(v1,v2,v3) :

return v1*v2*v3

43
Functions are general
¤ Function that takes 1 parameter: ¤ A function can also have no
parameters – but now it can only do
def multiply_5(val): one thing!

return val*5 def hello_world():

print("Hello World!\n”)

¤ Function that takes 3 parameters


No parameters,
def multiply(v1,v2,v3) : but parentheses
must be present!!
return v1*v2*v3

(\n is a newline character)

44
Example: area of a countertop

?
4/2=2

4/2=2

45
countertop.py
def compute_area():
empty parameter list
square_area = 4 * 4
triangle_area = 0.5 * (4 / 2) * (4 / 2)
total_area = square_area – triangle_area
return total_area

To call (use) the function in python3:

python3 –i countertop.py
>>> compute_area() empty argument
14.0 list
46
Generalizing the problem
X

?
X/2

X/2

47
countertop.py
parameter
def compute_area(side):
square_area = side * side
triangle_area = 0.5 * (side / 2 * side / 2)
total_area = square_area – triangle_area
return total_area

To call (use) the function in python3:

python3 –i countertop.py
argument
>>> compute_area(109) (run function with side = 109)

48
Function Outputs

49
Function Outputs
Return value Return None

¤ Function does some action and ¤ Function does some action and (by
returns a value: default) returns None:

def three_x(x): def hello_world():

return x * 3 print("Hello World!\n”)

50
Function Outputs
¤ >>> three_x(12)
36 value returned
>>> print(three_x(12))
36
value returned and printed
¤ >>> hello_world()
Hello World! value printed by method
>>> print(hello_world())
Hello World! valueprinted by method
None
value returned and printed

51
Function Outputs

¤ To use a function, we “call” the function.

¤ A function can return either one answer or no answer (None) to its “caller”.

¤ The hello_world function does not return anything to its caller. It simply
prints something on the screen.

¤ The three_x function does return its result to its caller so it can use the
value in another computation:
three_x(12) + three_x(16)

52
Function Outputs
¤ Suppose we write compute_area this way:

def compute_area(side):

square_area = side * side

triangle_area = 0.5 * side/2 * side/2

total_area = square_area – triangle_area

print(total_area)

¤ Now the following computation does not work. Why?


compute_area(109) + compute_area(78)

53
Built-in Functions (Methods)

54
Built-In Functions (Methods)

¤Lots of math stuff, e.g., sqrt, log, sin, cos

import math
r = 5 + math.sqrt(2)
alpha = math.sin(math.pi/3)

55
Using predefined modules
¤ math is a predefined module of functions (also called methods) that we can use
without writing their implementations.

math.sqrt(16)
math.pi
math.sin(math.pi / 2)

56
What Could Possibly Go Wrong?

alpha = 5
2 + alhpa

3 / 0

import math

math.sqrt(-1)
math.sqrt(2, 3)

57
Try

¤ Create a function that calculates 18% tip


¤ input(”Enter your check’s total: ”) would return a
user-entered variable. Write a short python script that would
advise users of an appropriate tip based on their input.

¤ Create a function that takes two parameters (mass and


radius) and calculates escape velocity. Note:
¤ G = 6.67e-011
¤ Our fine planet has mass of 5.9742e+024,
and a radius of 6378.1

58
Remember

¤ Next Lecture: Algorithms


¤ Note resources link and tutorials have extra info
on getting running with python

¤ Tonight:
¤ Lab 2
¤ OLI Iteration Module

¤ For tomorrow (Friday, 9:00AM)


¤ PS2

59
A SS
C L !
N O W !
R RO
M O
TO

60
Talking to the Shell (not Python!!)
Some useful Unix commands

61
Useful Unix Commands (Part 1)
All commands must be typed in lower case.

pwd --> print working directory, prints where you currently are

ls --> list, lists all the files and folders in the directory

cd stands for 'change directory':


cd lab1 --> change to the lab1 directory/folder
cd .. --> going up one directory/folder
cd ../.. --> going up two directories

62
Useful Unix Commands (Part 2)
mkdir lab1 --> make directory lab1 aka makes a folder called lab1

rm -r lab1 --> removes the directory lab1


(-r stands for recursive, which deletes any possible
folders in lab1 that might contain other files)

cp lab1/file1.txt lab2 --> copies a file called file1.txt, which is I


inside of the folder lab1, to the folder lab2

mv lab1/file1.txt lab2 --> moves a file called file1.txt, which is inside


of the folder lab1, to the folder lab2

zip zipfile.zip file1.txt file2.txt file3.txt -->


zips files 1 to 3 into zipfile.zip
zip -r zipfile.zip lab1/ --> zips up all files in the lab1 folder into
zipfile.zip
63
Useful Unix Commands (Part 3)

^c --> ctrl + c, interrupts running program

^d --> ctrl + d, gets you out of python3

"tab" - autocompletes what you're typing based on the files in the current folder

"up" - cycles through the commands you've typed. Similarly for the opposite effect,
press "down"

64
Useful Unix Commands (Part 4)
python3 -i test.py --> load test.py in python3, and
you can call the functions in test.py.

gedit lb1.txt & --> opens up lb1.txt on gedit and & allows you to
run your terminal at the same time
( else your terminal pauses until you close gedit)

And lastly, you can always do man <command> to find out more about a
particular command you're interested about (eg. man cp, man ls)

65

You might also like