Python
Python
with Python
1
Languages
◼ Some influential ones:
◼ FORTRAN
◼ science / engineering
◼ COBOL
◼ business data
◼ LISP
◼ logic and AI
◼ BASIC
◼ a simple language
Python
2
Programming basics
◼ code or source code: The sequence of instructions in a program.
3
Compiling and interpreting
◼ Many languages require you to compile (translate) your program
into a form that the machine understands.
compile execute
source code byte code output
Hello.java Hello.class
interpret
source code output
Hello.py
4
Expressions
◼ expression: A data value or set of operations to compute a value.
Examples: 1 + 4 * 3
13
5
Integer division
◼ When we divide integers with / , the quotient is also an integer.
3 52
4 ) 14 27 ) 1425
12 135
2 75
54
21
◼ More examples:
◼ 35 / 5 is 7
◼ 84 / 10 is 8
◼ 156 / 100 is 1
6
Real numbers
◼ Python can also manipulate real numbers.
◼ Examples: 6.022 -15.9997 42.0 2.143e17
◼ When integers and reals are mixed, the result is a real number.
◼ Example: 1 / 2.0 is 0.5
7
Math commands
◼ Python has useful commands for performing calculations.
Command name Description Constant Description
abs(value) absolute value e 2.7182818...
ceil(value) rounds up pi 3.1415926...
cos(value) cosine, in radians
floor(value) rounds down
log(value) logarithm, base e
log10(value) logarithm, base 10
max(value1, value2) larger of two values
min(value1, value2) smaller of two values
round(value) nearest whole number
sin(value) sine, in radians
sqrt(value) square root
◼ Examples: x = 5
gpa = 3.14
x 5 gpa 3.14
9
print
◼ print : Produces text output on the console.
◼ Syntax:
print "Message"
print Expression
◼ Prints the given text message or expression value on the console, and
moves the cursor down to the next line.
print Item1, Item2, ..., ItemN
◼ Prints several messages and/or expressions on the same line.
◼ Examples:
print ("Hello, world!")
age = 22
print ("You have", 65 - age, "years until retirement")
Output:
Hello, world!
You have 20 years until retirement
10
input
◼ input : Reads a number from user input.
◼ You can assign (store) the result of input into a variable.
◼ Example:
age = input("How old are you? ")
print ("Your age is", age)
print ("You have", 65 - age, "years until retirement")
Output:
How old are you? 53
Your age is 53
You have 12 years until retirement
11
Repetition (loops)
and Selection (if/else)
12
The for loop
◼ for loop: Repeats a set of statements over a group of values.
◼ Syntax:
for variableName in groupOfValues:
statements
◼ We indent the statements to be repeated with tabs or spaces.
◼ variableName gives a name to each value, so you can refer to it in the statements.
◼ groupOfValues can be a range of integers, specified with the range function.
◼ Example:
for x in range(1, 6):
print (x, "squared is", x * x)
Output:
1 squared is 1
2 squared is 4
3 squared is 9
4 squared is 16
5 squared is 25
13
range
◼ The range function specifies a range of integers:
◼ range(start, stop) - the integers between start (inclusive)
and stop (exclusive)
◼ It can also accept a third value specifying the change between values.
◼ range(start, stop, step) - the integers between start (inclusive)
and stop (exclusive) by step
◼ Example:
for x in range(5, 0, -1):
print (x)
print ("Blastoff!")
Output:
5
4
3
2
1
Blastoff!
14
Cumulative loops
Output:
sum of first 10 squares is 385
15
if
◼ if statement: Executes a group of statements only if a certain
condition is true. Otherwise, the statements are skipped.
◼ Syntax:
if condition:
statements
◼ Example:
gpa = 3.4
if gpa > 2.0:
print ("Your application is accepted.")
16
if/else
◼ if/else statement: Executes one block of statements if a certain
condition is True, and a second block of statements if it is False.
◼ Syntax:
if condition:
statements
else:
statements
◼ Example:
gpa = 1.4
if gpa > 2.0:
print ("Welcome to Mars University!")
else:
print ("Your application is denied.")
◼ Syntax:
while condition:
statements
◼ Example:
number = 1
while number < 200:
print (number)
number = number * 2
◼ Output:
1 2 4 8 16 32 64 128
18
Logic
◼ Many logical expressions use relational operators:
Operator Meaning Example Result
== equals 1 + 1 == 2 True
!= does not equal 3.2 != 2.5 True
< less than 10 < 5 False
> greater than 10 > 5 True
<= less than or equal to 126 <= 100 False
>= greater than or equal to 5.0 >= 5.0 True
19
Text and File Processing
20
Strings
◼ string: A sequence of text characters in a program.
◼ Strings start and end with quotation mark " or apostrophe ' characters.
◼ Examples:
"hello"
"This is a string"
"This, too, is a string. It can be very long!"
◼ A string may not span across multiple lines or contain a " character.
"This is not
a legal String."
"This is not a "legal" String either."
21
Indexes
◼ Characters in a string are numbered with indexes starting at 0:
◼ Example:
name = "P. Diddy"
index 0 1 2 3 4 5 6 7
character P . D i d d y
◼ Example:
print name, "starts with", name[0]
Output:
P. Diddy starts with P
22
String properties
◼ len(string) - number of characters in a string
(including spaces)
◼ str.lower(string) - lowercase version of a string
◼ str.upper(string) - uppercase version of a string
◼ Example:
name = "Martin Douglas Stepp"
length = len(name)
big_name = str.upper(name)
print (big_name, "has", length, "characters")
Output:
MARTIN DOUGLAS STEPP has 20 characters
23
input
24
Text processing
25
Strings and numbers
26
File processing
◼ Many programs handle data, which often comes from files.
Example:
file_text = open("bankaccount.txt").read()
27
Line-by-line processing
Example:
count = 0
for line in open("bankaccount.txt").readlines():
count = count + 1
print ("The file contains", count, "lines.")
28
Python Keywords
29