Professional Documents
Culture Documents
Introduction to Programming
Home Page
www.python.org
Documentation Home
www.python.org/doc/
Getting Started Page
http://www.python.org/about/gettingstarted/
2
CS2020
Installing Python
Go to www.python.org/download
Select the version for your platform
3
CS2020
Interactive vs. Batch Execution
Interactive (command line) mode
Enter program statements one at a time at a command
prompt
Each statement is processed after it is typed
This mode is appropriate for exploring or studying the
Python language and its features
Batch (script) mode
Enter the entire program into a text file, using a text editor
Invoke the interpreter to process statements in the text file
This is the standard mode for writing Python programs
We will use the Interactive mode in class for introducing
the basics of Python
4
CS2020
Interactive Mode Example
Initial startup
message
Prompt Statement
>>> 23 + 45
Response 68
5
CS2020
Batch Mode Example
Use a text editor (Notepad, TextEdit, …) to create
a Python program containing the following code:
print("Welcome to Python")
Save the file as welcome.py and run it from the
command prompt (not from the Python interpreter)
c:\>python welcome.py
Welcome to Python
Note that the file path must be set appropriately for
your system. If not, specify the full path in the
command, e.g., c:\python32\python. Here we
assume the command is executed from the current
directory, which includes welcome.py.
6
CS2020
Python Programming Basics: Data
Computer programs manipulate different
types of data
We start by looking at simple data types
Numbers (numeric values)
Strings (textual values)
7
CS2020
Numbers
Integers
Whole numbers
Floating-Point Numbers
Real numbers
Stored in computer memory using a
representation called floating-point
Complex Numbers
8
CS2020
Integers
Standard Integers (int)
-20, 0, 23, 4, …
Represented (stored) in the computer using the number
of bits needed, i.e., there is no size limit
9
CS2020
Floating-Point Numbers
Double-precision 64-bit IEEE 754
representation is used for real numbers
Both decimal and scientific notations can be
used
All of the following are valid Python float data
2.9, .998, -2345.0909
32.54e5, 0.12e-4
345.0E-20, 54.0E2
10
CS2020
Complex Numbers
Complex numbers have a real and an
imaginary part, represented by the syntax:
<real> + <imaginary>j|J
11
CS2020
Strings
A string is a sequence of characters
surrounded by single or double matched
quotes
Examples:
"This is a string"
"John's Mac"
'Jane"s PC'
"I like 'double quotes' better."
We will use double quotes by convention in
this class (except for internal quoting, where
single quotes must be used)
12
CS2020
Variables
A variable is a memory location where we store
data values during program execution
We can store exactly one value in a variable at
any given instance
It’s called a variable because the value stored within
it may vary
We can store different values in the same variable at
different times during program execution
A variable can be assigned a literal (fixed) value,
or a value from another variable
A variable must have a name in order to be
referenced or accessed
We call this name an identifier
13
CS2020
Identifiers
An identifier is a sequence of characters we
use to name a variable, and other program
elements (such as functions or constants)
A valid Python identifier must:
consist only of letters, numbers, and the
underscore symbol, and
begin with a letter or underscore
Example identifiers:
total _isThis_OKAY camelCaseIsBest
sum string CONSTANT2
1badExample
14
CS2020
Reserved Words
An identifier that is used for a specific purpose by a
language is called a reserved word, or keyword
Python reserved words:
and assert break class
continue def del elif
else except finally for
from global if import
in is lambda not
or pass raise return
try while yield
Added/removed in Python 3
15
CS2020
Choosing Variable Names
Any valid identifier that is not a reserved
word can be used as a variable name
But good programmers must...
choose a descriptive name
avoid non-reserved system or language names,
e.g., sum, print
use camelCase notation (easier to read)
Starts with a lowercase letter
Successive words are capitalized
Examples:
monthlyRent
discountAmtForSeniors
16
CS2020
Assignment Statement
A statement that assigns a value to a variable
Basic Syntax:
<variable> = <expression>
Examples:
x = 3
name = "John"
daysPerWeek = 7
r = x Notice that this is addition
followed by assignment, not
x = x + 2 a mathematical equality
17
CS2020
Multiple-Equal Assignments
We can assign a value to multiple variables
using a single statement
Basic Syntax:
( <variable> = )+ <expression>
The notation ( A )+ means 1 or more of A
Examples:
x = y = 3
sum1 = sum2 = sum3 = 0
msg1 = msg2 = "hello"
18
CS2020
Multiple-Target, Multiple-Source Assignments
We can also assign multiple values to multiple
variables using a single statement
Basic Syntax:
<variable> ( , <variable> )* =
<expression> ( , <expression> )*
The notation ( A )* means 0 or more of A
The number of target variables and RHS
expressions must match
Examples:
x, y = 3, "hello"
x, y, z = 1, 2, 3
x, y = 4, x
19
CS2020
Multiple-Equal, Multiple-Target, Multiple-Source
Assignments
Finally, we can combine the two previous
types of multiple assignment statements
Basic Syntax:
(<variable> ( , <variable> )* = )+
<expression> ( , <expression> )*
Again, number of target variables and expressions
must match
Examples:
x, y = a, b = 3, 4
a, b, c = w, x, z = 1, 2, 3
20
CS2020
Shortcut (Augmented) Assignments
It is very common in programming to modify the
current value of an integer variable, e.g.:
x = x + 10
For this type of update assignment, Python
provides a shortcut assignment operator
Instead of x = x + 10, we can write x += 10
Python shortcut assignment operators:
x += y x /= y x *= y x -= y
x %= y x //= y x **= y x <<= y
x ^= y x &= y x |= y x >>= y
21
CS2020
Python is a Type-less Language
This means it is perfectly legal to assign
different types of data to the same variable,
e.g., the following is valid:
x = 20
x = "I love Python"
The interpreter keeps track of the type of data
currently stored in a variable at any given time
The type() command is used to reveal the
type of data currently stored in a variable
x = "This is a string."
type(x) Returns <class 'str'> since x
was assigned a string value
22
CS2020
Expressions
An expression is a programming construct
that yields a value when evaluated
Anything that equates to a value is a valid
expression
Example expressions (notice no '='):
1 + 2
3 * 4 / 9
7.2
x + 2
"Just a string"
x == y
23
CS2020
Types of Expressions
Arithmetic Expressions
Yield a numeric value
String Expressions
Yield a string value
Boolean Expressions
Yield a boolean value, i.e., True or False
Others
We’ll learn about other expressions later
24
CS2020
Operators
Operators are the fundamental building
blocks of expressions
Mathematical symbols such as '+' and '*'
are well known, common operators
25
CS2020
Arithmetic Operators
Addition/Subtraction operators: +
-
4 + 2
Multiplication/Division operators: *
/ //
20 // 3
Exponentiation operator: **
2 ** 3
26
CS2020
Integer Division
In Python 3, the division operator always
yields a float
Try these: >>> 18 / 5
>>> 18.0 / 5
>>> 18 / 5.0
History lesson: Python 2 performed integer
division with two integer operands
In Python 3, the // operator provides
truncated division
Quotient is truncated, not rounded
Try the operations above, but with //
27
CS2020
Operator Precedence
For this statement, will the value of x be
22 or 30?
x = 2 + 4 * 5
Operator Precedence (partial list):
Operator Group Operators Example High
Exponentiation ** x ** y
Unary + - -x
Multiplicative * / // % x * y
Additive + - x + y Low
28
CS2020
Sample Arithmetic Expression
The expression below is evaluated in the
order shown:
2 - 4 * -3 // 2 + 2
-12
-6
8
10
Repetition: *
"hello " * 3 >>> "hello hello hello "
3 * "hello " >>> "hello hello hello "
Length: len( )
len("hey hey hey") >>> 11
x = "hello " * 3
len(x) >>> 18
31
CS2020
Boolean/Comparison Operators
Class of operators that equate to True or False
value
Boolean operators: and or not
Examples: x or y
not x
Note that not has a lower priority than non-boolean
operators, so not a == b is interpreted as
not (a == b), while a == not b gives an error
[ instead, use a == (not b)]
Comparison operators:
Less/Greater than: < <= > >=
Equality/Inequality: == !=
Object Identity/Negation: is is not
34
CS2020