Phyton 1
Phyton 1
Programming
with Python
2
Compiling and interpreting
Many languages require you to compile (translate) your program
into a form that the machine understands.
compile
source code byte code outpu
Hello.java execute
Hello.class t
interpret
source code outpu
Hello.py t
3
Best Python IDE
Best Python IDE
1. Full-featured IDEs: These are comprehensive environments with debugging, code
completion, project management, and testing tools.
Spyder
- Platforms: Cross-platform (bundled with Anaconda).
- Key Features:
- Built for data science (integrates with NumPy, Pandas, Matplotlib).
- Variable explorer, IPython console, and debugging tools.
- Best For: Data scientists, researchers.
5
Best Python IDE
Wing IDE
- Platforms: Windows, macOS, Linux
- Key Features:
- Advanced debugging (watch expressions, conditional breakpoints).
- Remote development and test-driven development (TDD) support.
- Editions: Free Personal Edition vs. Paid Pro.
- Best For: Debugging-heavy workflows.
Komodo IDE
- Platforms: Cross-platform
- Key Features
- Multi-language support (Python, PHP, Ruby, etc.).
- Docker integration and unit testing.
- Editions: Paid (with free Komodo Edit for basic use).
- Best For: Multi-language developers.
6
Best Python IDE
These are code editors enhanced with Python
2. Lightweight Editors with Python Support
extensions
Visual Studio Code (VS Code)
- Platforms: Cross-platform
-Key Features:
- Extensions for Python (IntelliSense, debugging, Jupyter notebooks).
- Git integration, terminal, and customizable workflows.
- **Best For**: General-purpose coding, flexibility.
Sublime Text
- Platforms: Cross-platform
- Key Features:
- Speed and simplicity with plugins (Anaconda, SublimeREPL).
- Multiple cursors, regex find/replace.
- Best For: Minimalists needing speed.
Atom (Discontinued)
- Platforms: Cross-platform (no longer maintained)
- Key Features:
- Hackable with packages (e.g., Hydrogen for Jupyter).
Best Python IDE
3. Online IDEs / Cloud-based Platforms
Replit
o ✔️Easy to use, great for beginners
o 💡 Real-time collaboration
8
Expressions
expression: is a combination of values, variables, and operators that result in a
value
Examples: 1 + 4 * 3
42
Arithmetic operators we will use:
+ - * / addition, subtraction/negation, multiplication, division
% modulus, a.k.a. remainder
** exponentiation
1
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
1
Real numbers
Python can also manipulate real numbers.
Examples: 6.022 -15.9997 42.0
2.143e17
1
Math commands
Python has useful commands (or called functions) for
performing calculations.
Constant Description
Command name Description
e 2.7182818...
abs(value) absolute value
pi 3.1415926...
ceil(value) rounds up
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
Code
import keyword
# Print all Python keywords
print("Python Keywords:")
print(keyword.kwlist)
Output:
Examples: x = 5
gpa = 3.14
x 5 gpa 3.14
A variable that has been given a value can be used in expressions.
x + 4 is 9
# Print variables
print("Name:", name)
print("Age:", age)
print("Height:", height)
print("Is Student?", is_student)
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 1
Example: print Statement
•
Elements separated by
commas print with a space
between them >>> print 'hello'
•
A comma at the end of the hello
statement (print ‘hello’,) >>> print
will not print a newline 'hello', 'there'
character hello there
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
1
Input: Example
print "What's your name?"
name = raw_input("> ")
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
23
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!
Exercise: How would we
print the "99 Bottles of Beer"
song? 24
Cumulative loops
Some loops incrementally compute a value that is initialized outside
the loop. This is sometimes called a cumulative sum.
sum = 0
for i in range(1, 11):
sum = sum + (i * i)
print "sum of first 10 squares is", sum
Output:
sum of first 10 squares is 385
25
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:
Example:
for x in range(1, 6): for i in range(5):
print x, "squared is", x * x print("Loop number:", i)
Output:
1 squared is 1
2 squared is 4
3 squared is 9
4 squared is 16
5 squared is 25
26
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."
27
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."
Multiple conditions 21
Example of If Statements
import math
x = 30
if x <= 15 : y >>> import ifstatement
= x + 15 y = 0.999911860107
>>>
elif x <= 30
In interpreter
:
y = x + 30
else :
y=x
print ‘y = ‘,
Inprint
file ifstatement.py
math.sin(y)
Example of If Statements
In interpreter
In file ifstatement.py
Example of If Statements
Output:
1 2 4 8 16 32 64 128
2
While Loops
>>> import whileloop
x=1 1
while x < 10 : 2
print x 3
x=x+1 4
5
6
In whileloop.py
7
8
9
>>>
In interpreter
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
%python forloop1.py
% python forloop2.py
1
0
7
1
13
2
2
3
4 [0,1, …, n-1]
range(N) generates a list of numbers
More Data Types
Everything is an object
Everything means
>>> x = 7
everything, >>> x
including 7
functions and >>>
classes (more on x=
'hello'
this later!) >>>
Data type is a x
property of the 'hello'
>>>
object and not
of the variable
Numbers: Integers
Integer – the
equivalent of a C long >>> 132224
Long Integer – an 132224
unbounded >>> 132323 **
2
integer value. 17509376329L
>>>
Numbers: Floating
Point
int(x) converts x to >>> 1.23232
1.2323200000000001
an integer
>>> print 1.23232
float(x) converts x
1.23232
to a floating >>> 1.3E7
point 13000000.0
The interpreter >>> int(2.0)
2
shows >>> float(2)
a lot of digits 2.0
Numbers: Complex
+ is overloaded to do
concatenation >>> x = 'hello'
>>> x = x + ' there'
>>> x
'hello there'
String Literals
Can use single or double quotes, and
three double quotes for a multi-line
string
insert>
Can usually just use %s for everything,
Ordered Pairs of values
Unordered list
Lists
Ordered collection of
data
>>> x = [1,'hello', (3 + 2j)]
Data can be of
>>> x
different [1, 'hello', (3+2j)]
types >>> x[2]
Lists are (3+2j)
>>>
mutable x[0:2]
Issues with shared [1,
'hello']
references and
mutability
Same subset
List Functions
list.append(x)
Add item at the end of the list.
list.insert(i,x)
Insert item at a given position.
Similar to a[i:i]=[x]
list.remove(x)
Removes first item from the list with value x
list.pop(i)
Remove item at position I and return it. If no index I is given then
list.count(x)
Return the number of time x appears in the list
list.sort()
Sorts items in the list in ascending order
list.reverse()
Reverses items in the list
List
List (Mutable):
fruits = ["apple", "banana", "cherry"]
fruits.append("orange")
colors = ("red",
"green", "blue")
print(colors[1])
# Second
item
Sets
A set is another python data structure that is an unordered
collection with no duplicates.
>>> setA=set(["a","b","c","d"])
>>> setB=set(["c","d","e","f"])
>>> "a" in setA
True
>>> "a" in setB
False
Sets
>>> setA - setB
numbers = {1, 2, 2, 3}
{'a', 'b'} print(numbers) # Output:
>>> setA | setB {1, 2, 3}
numbers.add(4)
{'a', 'c', 'b', 'e', 'd', 'f'}
>>> setA & setB
{'c', 'd'}
>>> setA ^ setB
{'a', 'b', 'e', 'f'}
>>>
Dictionaries
🔹 Dictionary (key-value pairs):
A set of key-value pairs
Dictionaries are mutable
print(person["name"])
person["age"] = 26
Dictionaries:
Add/Modify
Entries can be changed by assigning to
that entry
>>> d
{1: 'hello', 'two': 42, 'blah': [1, 2, 3]}
>>> d['two'] = 99
>>> d
{1: 'hello', 'two': 99, 'blah': [1, 2, 3]}
•
Assigning to a key that does not exist
adds an entry
>>> d[7] = 'new entry'
>>> d
{1: 'hello', 7: 'new entry', 'two': 99, 'blah': [1, 2, 3]}
Dictionaries: Deleting
Elements
The del method deletes an element from a
dictionary
>>> d
{1: 'hello', 2: 'there', 10: 'world'}
>>> del(d[2])
>>> d
{1: 'hello', 10: 'world'}
Iterating over a dictionary
>>>address={'Wayne': 'Young 678', 'John': 'Oakwood 345',
'Mary': 'Kingston 564'}
>>>for k in address.keys():
print(k,":", address[k])
Basic
○ Call Syntax
the functionRules (cont.)
by referring to its name
(function()) and by placing
any necessary arguments (1, 2) within
the parenthesis separated by
commas. myValue = function(1, 2)
○ If you wish, you can set your function call
equal to a variable (myValue). The value
returned by the function will be assigned
to your variable name.
myValue = function(1, 2)
Function Basics
funcasparam.py
Note that the function foo takes two
parameters and applies the first as a
function with the second as its
parameter
Higher-Order Functions
map(func,seq) – for all i, applies func(seq[i]) and returns the
corresponding sequence of the calculated results.
filter(boolfunc,seq) – returns a sequence containing all those
items in seq for which boolfunc is True.
reduce(func,seq) – applies func to the items of seq, from left
to right, two-at-time, to reduce the seq to a single value.
>>> from highorder import *
def plus(x,y):
>>> lst = [‘h’,’e’,’l’,’l’,’o’]
return (x + y)
>>> reduce(plus,lst)
‘hello’
highorder.py
Functions Inside Functions
funcinfunc.py
Functions Returning
Functions
def foo (x) :
def bar(y) :
return x + y % python funcreturnfunc.py
return bar <function bar at 0x612b0>
# main 5
f=
foo(3)
print f
print f(2)
funcreturnfunc.py
Parameters: Defaults
Parameters can be
assigned default
>>> def foo(x = 3) :
values
... print x
They are
...
>>> foo()
overridden if a 3
parameter is given
>>> foo(10)
for them
10
The type of the
>>> foo('hello')
hello
default doesn’t
limit the type of
a parameter
Parameters: Named
A lambda
expression >>> f = lambda x,y : x + y
returns a >>> f(2,3)
function 5
object >>> lst =
The body can ['one',
lambda x :
only be a simple x * x, 3]
expression, >>> lst[1](4)
not complex 16
statements
Modules
89
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
Output:
P. Diddy starts with P
90
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
91
raw_input
raw_input : Reads a string of text from user input.
Example:
name = raw_input("Howdy, pardner. What's yer name?
")
print name, "... what a silly name!"
Output:
Howdy, pardner. What's yer name? Paris Hilton
Paris Hilton ... what a silly name!
92
Text processing
text processing: Examining, editing, formatting text.
often uses loops that examine the characters of a string one by one
93
Strings and numbers
ord(text) - converts a string into a number.
Example: ord("a") is 97, ord("b") is 98, ...
Characters map to numbers using standardized mappings such as
ASCII and Unicode.
94
File processing
Many programs handle data, which often comes from files.
Example:
file_text = open("bankaccount.txt").read()
95
Line-by-line processing
Reading a file line-by-line:
for line in open("filename").readlines():
statements
Example:
count = 0
for line in open("bankaccount.txt").readlines():
count = count + 1
print "The file contains", count, "lines."
96
Objects, and Classes
● A class is a collection of
objects who share the same
Instance #1
set of variables/methods. Color: Pink
Name: Polo
○ The definition of the class Instance #2
provides a blueprint for all the Color: Red
Name: Mini
objects within it (instances).
Instance #3
Color: Blue
○ Instances may share the same Name: Beetle
variables (color, size, shape, etc.),
but they do NOT share the same
values for each variable
(blue/red/pink, small/large,
square/circular etc.)
Object
Defining a Class
Python program may own many objects
An object is an item with fields supported by a set of method functions.
An object can have several fields (or called attribute variables) describing
such an object
These fields can be accessed or modified by object methods
A class defines what objects look like and what functions can operate
on these object.
Declaring a class:
class name:
statements
Example:
class UCSBstudent:
age = 21
schoolname=‘UCSB’
Fields
name = value
Example:
class Point: point.py
x = 0
1 class Point:
y = 0 2 x = 0
3 y = 0
# main
p1 = Point()
p1.x = 2
p1.y = -5
can be declared directly inside class (as shown here)
or in constructors (more common)
Python does not really have encapsulation or private
fields
relies on caller to "be nice" and not mess with
objects' contents
Using a Class
import class
client programs must import the classes they use
point_main.py
1 from Point import *
2
3 # main
4 p1 = Point()
5 p1.x = 7
6 p1.y = -3
7
8 p2 = Point()
9 p2.x = 7
10 p2.y = 1
1) object.method(parameters)
or
2) Class.method(object,
parameters)
Example:
p = Point(3, -4)
p.move(1, 5)
Point.move(p, 1, 5)
Constructors
def init (self, parameter, ...,
parameter): statements
a constructor is a special method with the name init
Example:
class Point:
def init (self, x, y):
self.x = x
self.y = y
...
How would we make it possible to
construct a
Point() with no parameters to get (0,
0)?
toString and str
def str (self):
return string
equivalent to Java's
toString
(converts object to
a string)
invoked
automatically when
str or print is
called
Exercise: Write a str method for Point objects that returns strings
like "(3, -14)"
Example:
class BankAccount:
...
def deposit(self, amount):
if amount < 0:
raise ValueError("negative amount")
...
Inheritance
class name(superclass):
statements
Example:
class Point3D(Point): # Point3D extends Point
z = 0
...
(if > 1 superclass has the same field/method, conflicts are resolved
in left-to-right order)
Calling Superclass Methods
methods: class.method(object,
constructors: parameters) class. init
(parameters)
class Point3D(Point):
z = 0
def init (self, x, y, z):
Point. init (self, x, y)
self.z = z