You are on page 1of 183

Introduction to Python programming

Installling Python
Data types and Variables
Python Input and Output
Making Decisions -If Statements
Repition-while loops
for loops
Iterators
List comprehensions
Functions
Scope-variable
Modules
Object-Oriented Programming
Inheritance
Exception Handling
Using Data structures
The Python programming language

high-level language; such as C, C++, Perl, and Java.

!#1 easier to program in a high-level language


less time to write, they are shorter and easier to read, and they
are more likely to be correct

high-level languages are portable, meaning that they can run


!#2 on different kinds of computers with few or no modifications

computers can only execute programs written in low-level languages So programs


written in a high-level language have to be processed before they can run.This extra
processing takes some time, which is a small disadvantage of high-level languages.

Two kinds of programs process high-level languages into low-level languages:


interpreters and compilers.

Interpreters
An interpreter reads a high-level program and executes it
meaning that it does what the program says
It processes the program a little at a time, alternately reading lines and performing
computations.
Python is considered an interpreted language because Python programs are executed
by an interpreter.
There are two ways to use the interpreter:
interactive mode and script mode.

In interactive mode
you type Python programs and the interpreter prints the result:
>>> 1 + 1
2
The chevron, >>>, is the prompt the interpreter uses to indicate that it is ready
If you type 1 + 1,
the interpreter replies 2.
Working in interactive mode is convenient for testing small pieces of code because
you can type and execute them immediately
*!imp But for anything more than a few lines, you should save your code as a
script so you can modify and execute it in the future.
You can run most of the examples in interactive mode, but if you put the code into a
script, it is easier to try out variations.
Alternatively, you can store code in a file and use the interpreter to execute the
contents of the file,which is called a script.
By convention, Python scripts have names that end with .py.
To execute the script, you have to tell the interpreter the name of the file

In other development environments, the details of executing scripts are different.


You can find instructions for your environment at the Python website
python.org.
low-level languages-machine languages-assembly languages

Low-level programs can run on only one kind of computer and have to be rewritten to run on another

Low-level languages
are used only for a few specialized applications.

Short Note on Compilers


A
Incompiler reads
this context, thethe programprogram
high-level and translates it completely
is called beforeand
the source code, thethe
program startsprogram
translated runningis called the
object
Once acode or theis executable.
program compiled, you can execute it repeatedly without
further translation
rewritten to run on another
programming as the process of breaking a large, complex task into smaller and smaller subtasks
until the subtasks are simple enough to be performed with one of these basic instructions
ler subtasks
ctions
What is a program?

A program is a sequence of instructions that specifies how to perform a computation


The computation might be something mathematical, such as solving a system of equations or finding the roots of a
polynomial, but it can also be a symbolic computation, such as searching and replacing text in a document or
(strangely enough) compiling a program.

input: Get data from the keyboard, a file, or some other device.
output: Display data on the screen or send data to a file or other device.
math: Perform basic mathematical operations like addition and multiplication
conditional execution: Check for certain conditions and execute the appropriate sequence of statements.
repetition: Perform some action repeatedly, usually with some variation
Programming languages are formal languages that
have been designed to express
computations.
output: Display data on the screen or send data to a file or other device
math: Perform
might be basic mathematical,
something mathematical operations like addition
such as solving a systemand multiplication.
of equations or finding the roots
of a polynomial
or finding the roots
symbolic computation, such as searching and replacing text in a document
a document
conditional execution: Check for certain conditions and execute the appropriate sequence of statements.

starting wth the key word if and than what you want to check : to emphasis that u r startin code block and

a=2
b=3

if a < b:
print "Success"

else
iate sequence of statements.

that u r startin code block and than indent write code and than exit out from code block

elseif in python is elif


give more conditional option and or

check many values


in
check something exist either in string
repetition: Perform some action repeatedly, usually with some variation.
for loop while loop
keep running each item in the list

deals with list deals with condition


a=a+1
a+=1

while loop

Loops
The two types of loops we're
discussing here are for loops and while
loops. for loops work using lists, and
while loops work using conditions.
while loops
1
2
3
4
5
a, b = 0, 5

while a < b:
print a
a += 1
for Loops
1
2
3
4
myList = [1, 2, 3, 4, 5]

for a in myList:
print a

deals with condition


skices of string and indexing of arrays
What is debugging?
Programming is error-prone. For whimsical reasons, programming errors are called
bugs and the process of tracking them down is called debugging.

Three kinds of errors can occur in a program:

Syntax errors

Python can only execute a program if the syntax is correct;otherwise, the interpreter
displays an
error message.

If there is a single syntax


error anywhere in your program, Python will display an error message and quit, and
you will not be
able to run your program.

Syntax refers to the structure of a program and the rules about that structure

For
example, parentheses have to come in matching pairs, so (1 + 2) is legal, but 8) is a
syntax error.

Runtime errors/ Exceptional Error

The second type of error is a runtime error, so called because the error does not
appear until after the
program has started running.

These errors are also called exceptions because they usually indicate
that something exceptional (and bad) has happened.

Semantic errors
The third type of error is the semantic error.

If there is a semantic error in your program, it will


run successfully in the sense that the computer will not generate any error messages,
but it will not
do the right thing. It will do something else. Specifically, it will do what you told it to
do.
The problem is that the program you wrote is not the program you wanted to write.
The meaning of
the program (its semantics) is wrong. Identifying semantic errors can be tricky
because it requires
you to work backward by looking at the output of the program and trying to figure
out what it is
doing.
What is debugging?
Programming
For whimsicalisreasons,
error-prone.
programming errors are called bugs and the process of tracking them down is call

Three kinds of errors can occur in a program: syntax errors, runtime errors, and semantic errors
It is useful to distinguish between them in order to track them down more quickly.
ss of tracking them down is called debugging.

, and semantic errors


Python can only execute a program if the syntax is correct; otherwise, the interpreter displays an
error message
Syntax refers to the structure of a program and the rules about that structure
For example,
error anywhereparentheses have toPython
in your program, come in matching
will pairs,
display an so message
error (1 + 2) is and
legal,quit,
but and
8) isyou
a syntax error.
will not be
able to run your program
e interpreter displays an

gal, but and


d quit, 8) isyou
a syntax error.
will not be
Runtime errors
The second type of error is a runtime error, so called because the error does not appear until a
program
These errorsstarted
has are alsorunning.
called exceptions because they usually indicate that something exception

Runtime errors are rare in the simple programs


he error does not appear until after the
ndicate that something exceptional (and bad) has happened.
Semantic errors
The third type ofinerror
run successfully is the semantic
the sense error.
that the computer will not generate any error messages, but it will not
do the right thing.
It will do something else. Specifically, it will do what you told it to do.

The problem is that the program you wrote is not the program you wanted to write.
Theto
you meaning of the program
work backward (its semantics)
by looking is wrong.
at the output of the program and trying to figure out what it is
doing.
or messages, but it will not

to figure out what it is


Linux is an operating system that contains thousands of lines of code, but it started
out as a simple program Linus Torvalds used to explore the Intel 80386 chip. According to Larry
Greenfield, “One of Linus’s earlier projects was a program that would switch between printing
AAAA and BBBB. This later evolved to Linux.” (The Linux Users’ Guide Beta Version 1).
Question:
Write a well-structured English sentence with invalid tokens in it. Then write another sentence with
all valid tokens but with invalid structure.
Answer:
Bad Token = 'The m@n jump3d over th3 m00n.'
Bad Syntax = 'Moon over jumped man the the
If you run a 10 kilometer race in 43 minutes 30 seconds, what is your average time per
mile? What
is your average speed in miles per hour? (Hint: there are 1.61 kilometers in a mile).
The volume of a sphere with radius r is 4/3 π r3.

What is the volume of a sphere with radius 5?

Hint: 392.6 is wrong!


ere with radius r is 4/3 π r3.

f a sphere with radius 5?


bookCost = 24.95
numBooks = 60.0

def cost(numBooks):
bulkBookCost = ((bookCost * 0.60) * numBooks)
shippingCost = (3.0 + (0.75 * (numBooks - 1)))
totalCost = bulkBookCost + shippingCost
print 'The total cost is: $', totalCost
Suppose the cover price of a book is $24.95, but bookstores get a 40% discount.
Shipping costs $3 for the first copy and 75 cents for each additional copy. What is the
total wholesale cost for 60 copies?
# Total wholesale book cost calculator
cover_price = 24.95

number_of_books = int(input("How many books do you want to order at wholesale?


"))

def ship_cost (number_of_books):


if number_of_books == 1:
return (number_of_books * 3) # Cost of shipping one book is $3
else:
return (3 + (number_of_books - 1) * 0.75) # Each additional copy of the book is
$0.75 to ship

def wholesale_cost(number_of_books):
return ((cover_price * 0.6 * number_of_books) + ship_cost(number_of_books)) #
There is a 40% discount on wholesale book sales

print("The cost of buying and shipping", number_of_books, "books is


$",round(wholesale_cost(number_of_books), 2))

code explination

input: Get data from the keyboard, a file, or some other device.

difference betwee return and print


$24.95 Cost
$9.98 Discount per book
$14.97 Cost per book after discount
60 Total number of books
$898.20 Total cost not inc delivery

$3.00 First book delivery


59 Remaining books
$0.75 Delivery cost for extra books
$44.25 Total cost for extra books
$47.25 Total Delivery cost

$945.45 Total Bill

This answer is wrong because 40.0/100.0 return wrong value 0.40000000000000002 for more
info see IEEE 754 (Standard for Floating-Point Arithmetic)
>>> (24.95-24.95*40.0/100.0)*60+3+0.75*(60-1)
945.44999999999993
>>> 24.95*0.6*60+0.75*(60-1)+3
945.45
resale_price = 24.95
wholesale_price = resale_price * 0.60
print wholesale_price
14.97
first_copy = wholesale_price + 3
print first_copy
17.97
additional_copies = wholesale_price + 0.75
print additional_copies
15.72
total_cost = first_copy + (additional_copies)*59
print total_cost
945.4
Suppose the cover price of a book is $24.95, but bookstores get a 40% discount. Shipping costs $3 for the first copy
and 75 cents for each additional copy. What is the total wholesale cost for 60 copies?

Hints:

What is the price of one book after the discount has been given?
What is the total cost of 60 books without shipping costs?
What is the total cost of 60 books including shipping costs?

Assuming you are a bookstore


each book costs x = 24.95*discount
From there you can find the total cost of all books
To that add the shipping costs.
If you are not a bookstore, just remove the discount.
price_per_book = 24.95
discount = .40
quantity = 60

Here:
discounted_price = (1-discount) * price_per_book

The discounted price should be price_per_book - discount

shipping = 3.0 + (60 - 1) * .75


shipping should be, I think, should be 3.0 + (quantity * .75)

total_price = 60 * discounted_price + shipping


replace 60 with quantity (quantity * discounted_price) + shipping

print total_price, 'Total price'

total_price gives:
945.45 Total price
and just 24.55(price per book - discount is ) * quantity is $1473 without the shipping, so the total is way off already:

I think the following is what you're looking for:

price_per_book = 24.95
discount = .40
quantity = 60
discounted_price = price_per_book-discount
shipping = 3.0 + (quantity*.75)
total_price = (quantity * discounted_price) + shipping
print 'Total price: $%d' % (total_price)
Total price: $1521
--
https://mail.python.org/mailman/listinfo/python-list
Web Programming With Python

Programming Review
Database Programming with Sqlite
FTP
Email
NewsGropup
Web client programming
webserver Programming
Web/Databse Programming
XMl Programming
Web framework Programming-Django
When you define a function, you specify the name and the sequence of statements

Later,you can “call” the function by name

>>> type(32)
<type 'int'>

The name of the function is type which is inbuilt function come from python and the other
function which we built it by ourselves

The expression in parentheses is called the argument of the function.


The result, for this function, is the type of the argument

It is common to say that a function “takes” an argument and “returns” a result.


The result is called the return value
print is a function requires open and
closed parenthesis with argument
Variation of printing function

using end ='' with print to print two stmt


in one line so what it does don’t end with
a new line end with a empty string

print("hello ")
print("hello world")
so if we want to print on the same line of
two print function
print("hello ", end =' ' )
print("hello world")

what we will do if we have large gap like a


tab

\t backslash t is a special character that


represent a tab
print("hello ,\tworld")

or
=+---conctenation combining multiple
string into one string
print("hello"+ "\t" + "tworld")

\n new line charactercauses line feed


print("hello,\ntworld!")

FOR LOOP
for i in range
StrongTyping
a=2
b='Tim'
type(a)
<class 'int'>
type(b)
<class 'str'>
c=3.14
type©
<class 'float'>

def adder(x,y):
print(x+y)
adder(2,2)
4

isinstance
int()
float()

help
Python has a math module that provides most of the familiar mathematical functions

Before we can use the module, we have to import it:

>>> import math


This
If youstatement
print the creates
moduleaobject,
module object
you named math
get some
information about it:
>>> print math

<module 'math' from '/usr/lib/python2.5/lib-dynload/math.so'>

The module object contains the functions and variables defined in the module.
To access one of the
functions, you have to specify the name of the module and the name of the function
separated by a dot (also known as a period).
This format is called dot notation.

>>> ratio = signal_power / noise_power


>>> decibels = 10 * math.log10(ratio) The first example uses log10 to compute a signal-to-noise ratio
signal_power and noise_power
The math module also provides are
log,defined)
which computes
logarithms base e.
>>> radians = 0.7
The second example finds the sine of radians
>>> height = math.sin(radians) The name of the variable is a hint that sin and the other trigon
To convert from degrees to radians, divide by 360 and multiply

>>> degrees = 45
>>> radians = degrees / 360.0 * 2 * math.pi
>>> math.sin(radians) The
The expression
value of thismath.pi
variablegets the variable pi from the
is an
0.707106781187 approximation of π, accurate to about 15 digits.

>>> math.sqrt(2) / 2.0 If you know your trigonometry, you can check the pr
0.707106781187 of two divided by two:
cal functions

he function

o compute a signal-to-noise ratio in decibels (assuming that


rs are
log,defined)
which computes

sine of radians
int that sin and the other trigonometric functions (cos, tan, etc.) take arguments in radians.
ians, divide by 360 and multiply by π:

h.pi
iablegets the variable pi from the math module
is an
accurate to about 15 digits.

gonometry, you can check the previous result by comparing it to the square root
wo:
Numeric DATA
Number expressions

Integers -0,1,2,+2,-2
Floating point number or fraction or Double-3.14,+3.14,-3.14
Hexa octal deci binary
Mathemtical operators-// integer division no remaainder
Modulus -retun the remaider
Exponent operator-**
precedence
built in mathematical function
pow
abs
round
sqrt
equal,==
isnotequalto !=

random
Character DATA
String expression

sequence of character inside single quote or double quotes but


dq are most standard most programming languages follow
str='Hello World';
str="Hello World";
str
Concatenation string with another string using plus sighn-
combined data
str=str + 'GoodBye,World!'
str

len()-tells how many characters


len(str)
array notation using squar brackets to disvoer postion of string
data character
str[0]
str[1]

slices in python
str[0, 4]
str[0, 4]
str[: 4]
str[4:]
str*2
split operator
takes a single argument a delimiter and splits up string into a list
based on that limiter
str. Split (' ')
split return the lists
\n is a new line character
print ('hello,world\n'goodbye world')
strip -cut down rogue spaces -cleaning data from irraneous
spaces
str ='Hello world!'
str.strip()
str ='Helloworld!'
str.rstrip()

PEMDAS-pleaseexcusemydearaunt sally-order of operatons


Boolean data type true or false true represent integer 1 false is
as a 0 and or

how to generate boolean data


assighment stmt

boo=l2==2
true
bool=2==3
false

python automatically assighn data type when using vaiable

Relational and logical operators

If stmt and decision making

tuple
Mutable data type
lists data structure

empty list represen by opening and closing brackets


[]
if item insert into the brackets seprated by comman if we like to
access we will do it b index notation

numbers=[1,2,3,4]

numbers
retrive each element losts indivually
numbers[0]+numbers[1]+numbers[2]+numbers[3]

numbers=[0:2]

len(numbers)

words =['now'; 'is']


words1= =['the','time']

words

words+words1

word=['hello']

word *5

nested sub lists

Dictionatry data structure lists


key and values pairs
Files

************************
Python input and output

Output------- how we print data to the screen


Input----------- how we received data from the keyboard

simple usage of print function

word ='hello' create variable


number=100 create variable

print(word) display the value of variable we simply put that


inside parenthesis and send that as an argument to the print
function and its print the value
print(number)

Lists data type


words = ['now', 'is', 'the','time']
print(words)

literals
print(100)
print('hello')

literal expression l such as concatenation


print('hello' + ''world')

Arithmethic exp
print(2*2)

tuple by using comma


print(word,number)

print(word+ ' '+number)to solve int with string expression


print(word+ ' '+str(number))
Format string
name ='Amry'
grade =81.7933

record ='%s: %2f' %(name,grade)


prit(record)

print redirection which mean print to the device other than the
screen

import sys
sys.stdout.write(hello\n)

sys.stdout=open('text.dat'.'a')
print('hello')
exit()

type text.dat-dos cmd type

import sys
sys.stdout=open('text.dat'.'a')
print('goodbye')
exit()

textfile=open('text.dat'.'a')
print >> textfile, 'hello'
print('goodbye')

Raw input
how to get data into the program from the keyborad

name =raw_input()
Mary Smith
print(name)

sentence=raw_input()
now is the time for all good people
print(sentence)

number=raw_input()
100
print (number*2)
number=(raw_input())
100
print(number*2)

number=float(raw_input())
2.22
print(number/1.4)
exit()

notepad add.py
print ("enter a number; ")
number1 = int(raw_input()
print ("enter a another number; ")
number2 = int(raw_input()
print ("The sum is: "+str (nuber1+number2))

Tasks small birthday gif enquires program-504

Conditional
If Stmt
Python program flow
when u define a function def key word is used

Use the keyword def to declare the function and follow this up with the function name.
Add parameters to the function: they should be within the parentheses of the function. End your line wit
Add statements that the functions should execute.
End your function with a return statement if the function should output something.
Without the return statement, your function will return an object None
unction name.
f the function. End your line with a colon.
function block begin with the key word def followed by the function name and parenthesis
inside the parenthesis parameters are given
The Code Block within every function start with a colon : and is indented

Calling a function
To call a function, use the function name followed by parenthesis:

Parameters
Information can be passed to functions as parameter.
Parameters are specified after the function name, inside the parenthese
You can add as many parameters as you want, just separate them with a comma
e and parenthesis
Built in python function

to print an object to the terminal

print statement: An instruction that causes the Python interpreter to display a value on the screen.
lay a value on the screen.
You (and the interpreter) can identify strings because they
are enclosed in quotation marks.

str in built python function can covert integers into srtring


str
>>>converts its argument to a string:
str(3.14159)
'3.14159'
value of len('allen') is 5.

Write
string awith
function named
enough right_justify
leading spaces that takes a string named as a parameter

so
>>>that the last letter of the string is in column 70 of the display.
right_justify('allen')

allen
ing named as a parameter

the display.
Python provides built-in functions that convert values from one type to another
The int function takes any value and converts it to an integer
>>> int('32')
32

if
>>>it can, or complains otherwise:
int('Hello')
ValueError: invalid literal for int(): Hello
int can convert floating-point values to integers, but it doesn’t round off; it chops off the fraction
part:
>>> int(-2.3)
-2
off the fraction
float converts integers and strings to floating-point numbers
>>> float('3.14159')
3.14159
if function is a group of code than module is group of funtion

import

math
random
urllib2
date and time
os module
A module is
a file that contains a collection of related functions.

Before we can use the module, we have to import it:


>>> import math
Functions are a construct to structure programs. They are known in most programming languages, someti
Functions are used to utilize code in more than one place in a program. The only way without functions to
programming languages, sometimes also called subroutines or procedures.
he only way without functions to reuse code consists in copying the code.
#!
= assignment stmt
Web Programming With Python

Programming Review
Database Programming with Sqlite
FTP
Email
NewsGropup
Web client programming
webserver Programming
Web/Databse Programming
XMl Programming
Web framework Programming-Django
print is a function requires open and closed parenthesis with
argument
Variation of printing function

using end ='' with print to print two stmt in one line so what it
does don’t end with a new line end with a empty string
print("hello ")
print("hello world")

so if we want to print on the same line of two print function


print("hello ", end =' ' )
print("hello world")

what we will do if we have large gap like a tab

\t backslash t is a special character that represent a tab


print("hello ,\tworld")

or
=+---conctenation combining multiple string into one string
print("hello"+ "\t" + "tworld")

\n new line charactercauses line feed


print("hello,\ntworld!")

FOR LOOP
for i in range
StrongTyping
a=2
b='Tim'
type(a)
<class 'int'>
type(b)
<class 'str'>
c=3.14
type©
<class 'float'>

def adder(x,y):
print(x+y)

adder(2,2)
4
isinstance
int()
float()

help
Numeric DATA
Number expressions

Integers -0,1,2,+2,-2
Floating point number or fraction or Double-3.14,+3.14,-3.14
Hexa octal deci binary
Mathemtical operators-// integer division no remaainder
Modulus -retun the remaider
Exponent operator-**
precedence
built in mathematical function
pow
abs
round
sqrt
equal,==
isnotequalto !=

random
Character DATA
String expression

sequence of character inside single quote or double quotes but


dq are most standard most programming languages follow
str='Hello World';
str="Hello World";
str
Concatenation string with another string using plus sighn-
combined data
str=str + 'GoodBye,World!'
str

len()-tells how many characters


len(str)
array notation using squar brackets to disvoer postion of string
data character
str[0]
str[1]

slices in python
str[0, 4]
str[0, 4]
str[: 4]
str[4:]
str*2
split operator
takes a single argument a delimiter and splits up string into a list
based on that limiter
str. Split (' ')
split return the lists
\n is a new line character
print ('hello,world\n'goodbye world')
strip -cut down rogue spaces -cleaning data from irraneous
spaces
str ='Hello world!'
str.strip()
str ='Helloworld!'
str.rstrip()

PEMDAS-pleaseexcusemydearaunt sally-order of operatons


Boolean data type true or false true represent integer 1 false is
as a 0 and or

how to generate boolean data


assighment stmt

boo=l2==2
true
bool=2==3
false

python automatically assighn data type when using vaiable

Relational and logical operators

If stmt and decision making

tuple
Mutable data type
lists data structure

empty list represen by opening and closing brackets


[]
if item insert into the brackets seprated by comman if we like to
access we will do it b index notation

numbers=[1,2,3,4]

numbers
retrive each element losts indivually
numbers[0]+numbers[1]+numbers[2]+numbers[3]

numbers=[0:2]

len(numbers)

words =['now'; 'is']


words1= =['the','time']

words

words+words1

word=['hello']

word *5

nested sub lists

Dictionatry data structure lists


key and values pairs
Files

************************
Python input and output

Output------- how we print data to the screen


Input----------- how we received data from the keyboard

simple usage of print function

word ='hello' create variable


number=100 create variable

print(word) display the value of variable we simply put that


inside parenthesis and send that as an argument to the print
function and its print the value
print(number)

Lists data type


words = ['now', 'is', 'the','time']
print(words)

literals
print(100)
print('hello')

literal expression l such as concatenation


print('hello' + ''world')

Arithmethic exp
print(2*2)

tuple by using comma


print(word,number)

print(word+ ' '+number)to solve int with string expression


print(word+ ' '+str(number))
Format string
name ='Amry'
grade =81.7933

record ='%s: %2f' %(name,grade)


prit(record)

print redirection which mean print to the device other than the
screen

import sys
sys.stdout.write(hello\n)

sys.stdout=open('text.dat'.'a')
print('hello')
exit()

type text.dat-dos cmd type

import sys
sys.stdout=open('text.dat'.'a')
print('goodbye')
exit()

textfile=open('text.dat'.'a')
print >> textfile, 'hello'
print('goodbye')

Raw input
how to get data into the program from the keyborad

name =raw_input()
Mary Smith
print(name)

sentence=raw_input()
now is the time for all good people
print(sentence)

number=raw_input()
100
print (number*2)
number=(raw_input())
100
print(number*2)

number=float(raw_input())
2.22
print(number/1.4)
exit()

notepad add.py
print ("enter a number; ")
number1 = int(raw_input()
print ("enter a another number; ")
number2 = int(raw_input()
print ("The sum is: "+str (nuber1+number2))

Tasks small birthday gif enquires program-504

Conditional
If Stmt
Python program flow
when u define a function def key word is used

Use the keyword def to declare the function and follow this up with the function name.
Add parameters to the function: they should be within the parentheses of the function. End your line wit
Add statements that the functions should execute.
End your function with a return statement if the function should output something.
Without the return statement, your function will return an object None
unction name.
f the function. End your line with a colon.
function block begin with the key word def followed by the function name and parenthesis
inside the parenthesis parameters are given
The Code Block within every function start with a colon : and is indented

Calling a function
To call a function, use the function name followed by parenthesis:

Parameters
Information can be passed to functions as parameter.
Parameters are specified after the function name, inside the parenthese
You can add as many parameters as you want, just separate them with a comma
e and parenthesis
Built in python function

to print an object to the terminal


Functions are a construct to structure programs. They are known in most programming languages, someti
Functions are used to utilize code in more than one place in a program. The only way without functions to
programming languages, sometimes also called subroutines or procedures.
he only way without functions to reuse code consists in copying the code.
#!
= assignment stmt
Web Programming With Python

Programming Review
Database Programming with Sqlite
FTP
Email
NewsGropup
Web client programming
webserver Programming
Web/Databse Programming
XMl Programming
Web framework Programming-Django
print is a function requires open and closed parenthesis with
argument
Variation of printing function

using end ='' with print to print two stmt in one line so what it
does don’t end with a new line end with a empty string
print("hello ")
print("hello world")

so if we want to print on the same line of two print function


print("hello ", end =' ' )
print("hello world")

what we will do if we have large gap like a tab

\t backslash t is a special character that represent a tab


print("hello ,\tworld")

or
=+---conctenation combining multiple string into one string
print("hello"+ "\t" + "tworld")

\n new line charactercauses line feed


print("hello,\ntworld!")

FOR LOOP
for i in range
StrongTyping
a=2
b='Tim'
type(a)
<class 'int'>
type(b)
<class 'str'>
c=3.14
type©
<class 'float'>

def adder(x,y):
print(x+y)

adder(2,2)
4
isinstance
int()
float()

help
Numeric DATA
Number expressions

Integers -0,1,2,+2,-2
Floating point number or fraction or Double-3.14,+3.14,-3.14
Hexa octal deci binary
Mathemtical operators-// integer division no remaainder
Modulus -retun the remaider
Exponent operator-**
precedence
built in mathematical function
pow
abs
round
sqrt
equal,==
isnotequalto !=

random
Character DATA
String expression

sequence of character inside single quote or double quotes but


dq are most standard most programming languages follow
str='Hello World';
str="Hello World";
str
Concatenation string with another string using plus sighn-
combined data
str=str + 'GoodBye,World!'
str

len()-tells how many characters


len(str)
array notation using squar brackets to disvoer postion of string
data character
str[0]
str[1]

slices in python
str[0, 4]
str[0, 4]
str[: 4]
str[4:]
str*2
split operator
takes a single argument a delimiter and splits up string into a list
based on that limiter
str. Split (' ')
split return the lists
\n is a new line character
print ('hello,world\n'goodbye world')
strip -cut down rogue spaces -cleaning data from irraneous
spaces
str ='Hello world!'
str.strip()
str ='Helloworld!'
str.rstrip()

PEMDAS-pleaseexcusemydearaunt sally-order of operatons


Boolean data type true or false true represent integer 1 false is
as a 0 and or

how to generate boolean data


assighment stmt

boo=l2==2
true
bool=2==3
false

python automatically assighn data type when using vaiable

Relational and logical operators

If stmt and decision making

tuple
Mutable data type
lists data structure

empty list represen by opening and closing brackets


[]
if item insert into the brackets seprated by comman if we like to
access we will do it b index notation

numbers=[1,2,3,4]

numbers
retrive each element losts indivually
numbers[0]+numbers[1]+numbers[2]+numbers[3]

numbers=[0:2]

len(numbers)

words =['now'; 'is']


words1= =['the','time']

words

words+words1

word=['hello']

word *5

nested sub lists

Dictionatry data structure lists


key and values pairs
Files

************************
Python input and output

Output------- how we print data to the screen


Input----------- how we received data from the keyboard

simple usage of print function

word ='hello' create variable


number=100 create variable

print(word) display the value of variable we simply put that


inside parenthesis and send that as an argument to the print
function and its print the value
print(number)

Lists data type


words = ['now', 'is', 'the','time']
print(words)

literals
print(100)
print('hello')

literal expression l such as concatenation


print('hello' + ''world')

Arithmethic exp
print(2*2)

tuple by using comma


print(word,number)

print(word+ ' '+number)to solve int with string expression


print(word+ ' '+str(number))
Format string
name ='Amry'
grade =81.7933

record ='%s: %2f' %(name,grade)


prit(record)

print redirection which mean print to the device other than the
screen

import sys
sys.stdout.write(hello\n)

sys.stdout=open('text.dat'.'a')
print('hello')
exit()

type text.dat-dos cmd type

import sys
sys.stdout=open('text.dat'.'a')
print('goodbye')
exit()

textfile=open('text.dat'.'a')
print >> textfile, 'hello'
print('goodbye')

Raw input
how to get data into the program from the keyborad

name =raw_input()
Mary Smith
print(name)

sentence=raw_input()
now is the time for all good people
print(sentence)

number=raw_input()
100
print (number*2)
number=(raw_input())
100
print(number*2)

number=float(raw_input())
2.22
print(number/1.4)
exit()

notepad add.py
print ("enter a number; ")
number1 = int(raw_input()
print ("enter a another number; ")
number2 = int(raw_input()
print ("The sum is: "+str (nuber1+number2))

Tasks small birthday gif enquires program-504

Conditional
If Stmt
Python program flow
when u define a function def key word is used

Use the keyword def to declare the function and follow this up with the function name.
Add parameters to the function: they should be within the parentheses of the function. End your line wit
Add statements that the functions should execute.
End your function with a return statement if the function should output something.
Without the return statement, your function will return an object None
unction name.
f the function. End your line with a colon.
function block begin with the key word def followed by the function name and parenthesis
inside the parenthesis parameters are given
The Code Block within every function start with a colon : and is indented

Calling a function
To call a function, use the function name followed by parenthesis:

Parameters
Information can be passed to functions as parameter.
Parameters are specified after the function name, inside the parenthese
You can add as many parameters as you want, just separate them with a comma
e and parenthesis
Built in python function

to print an object to the terminal


Functions are a construct to structure programs. They are known in most programming languages, someti
Functions are used to utilize code in more than one place in a program. The only way without functions to
programming languages, sometimes also called subroutines or procedures.
he only way without functions to reuse code consists in copying the code.
#!
= assignment stmt
Web Programming With Python

Programming Review
Database Programming with Sqlite
FTP
Email
NewsGropup
Web client programming
webserver Programming
Web/Databse Programming
XMl Programming
Web framework Programming-Django
print is a function requires open and closed parenthesis with
argument
Variation of printing function

using end ='' with print to print two stmt in one line so what it
does don’t end with a new line end with a empty string
print("hello ")
print("hello world")

so if we want to print on the same line of two print function


print("hello ", end =' ' )
print("hello world")

what we will do if we have large gap like a tab

\t backslash t is a special character that represent a tab


print("hello ,\tworld")

or
=+---conctenation combining multiple string into one string
print("hello"+ "\t" + "tworld")

\n new line charactercauses line feed


print("hello,\ntworld!")

FOR LOOP
for i in range
StrongTyping
a=2
b='Tim'
type(a)
<class 'int'>
type(b)
<class 'str'>
c=3.14
type©
<class 'float'>

def adder(x,y):
print(x+y)

adder(2,2)
4
isinstance
int()
float()

help
Numeric DATA
Number expressions

Integers -0,1,2,+2,-2
Floating point number or fraction or Double-3.14,+3.14,-3.14
Hexa octal deci binary
Mathemtical operators-// integer division no remaainder
Modulus -retun the remaider
Exponent operator-**
precedence
built in mathematical function
pow
abs
round
sqrt
equal,==
isnotequalto !=

random
Character DATA
String expression

sequence of character inside single quote or double quotes but


dq are most standard most programming languages follow
str='Hello World';
str="Hello World";
str
Concatenation string with another string using plus sighn-
combined data
str=str + 'GoodBye,World!'
str

len()-tells how many characters


len(str)
array notation using squar brackets to disvoer postion of string
data character
str[0]
str[1]

slices in python
str[0, 4]
str[0, 4]
str[: 4]
str[4:]
str*2
split operator
takes a single argument a delimiter and splits up string into a list
based on that limiter
str. Split (' ')
split return the lists
\n is a new line character
print ('hello,world\n'goodbye world')
strip -cut down rogue spaces -cleaning data from irraneous
spaces
str ='Hello world!'
str.strip()
str ='Helloworld!'
str.rstrip()

PEMDAS-pleaseexcusemydearaunt sally-order of operatons


Boolean data type true or false true represent integer 1 false is
as a 0 and or

how to generate boolean data


assighment stmt

boo=l2==2
true
bool=2==3
false

python automatically assighn data type when using vaiable

Relational and logical operators

If stmt and decision making

tuple
Mutable data type
lists data structure

empty list represen by opening and closing brackets


[]
if item insert into the brackets seprated by comman if we like to
access we will do it b index notation

numbers=[1,2,3,4]

numbers
retrive each element losts indivually
numbers[0]+numbers[1]+numbers[2]+numbers[3]

numbers=[0:2]

len(numbers)

words =['now'; 'is']


words1= =['the','time']

words

words+words1

word=['hello']

word *5

nested sub lists

Dictionatry data structure lists


key and values pairs
Files

************************
Python input and output

Output------- how we print data to the screen


Input----------- how we received data from the keyboard

simple usage of print function

word ='hello' create variable


number=100 create variable

print(word) display the value of variable we simply put that


inside parenthesis and send that as an argument to the print
function and its print the value
print(number)

Lists data type


words = ['now', 'is', 'the','time']
print(words)

literals
print(100)
print('hello')

literal expression l such as concatenation


print('hello' + ''world')

Arithmethic exp
print(2*2)

tuple by using comma


print(word,number)

print(word+ ' '+number)to solve int with string expression


print(word+ ' '+str(number))
Format string
name ='Amry'
grade =81.7933

record ='%s: %2f' %(name,grade)


prit(record)

print redirection which mean print to the device other than the
screen

import sys
sys.stdout.write(hello\n)

sys.stdout=open('text.dat'.'a')
print('hello')
exit()

type text.dat-dos cmd type

import sys
sys.stdout=open('text.dat'.'a')
print('goodbye')
exit()

textfile=open('text.dat'.'a')
print >> textfile, 'hello'
print('goodbye')

Raw input
how to get data into the program from the keyborad

name =raw_input()
Mary Smith
print(name)

sentence=raw_input()
now is the time for all good people
print(sentence)

number=raw_input()
100
print (number*2)
number=(raw_input())
100
print(number*2)

number=float(raw_input())
2.22
print(number/1.4)
exit()

notepad add.py
print ("enter a number; ")
number1 = int(raw_input()
print ("enter a another number; ")
number2 = int(raw_input()
print ("The sum is: "+str (nuber1+number2))

Tasks small birthday gif enquires program-504

Conditional
If Stmt
Python program flow
when u define a function def key word is used

Use the keyword def to declare the function and follow this up with the function name.
Add parameters to the function: they should be within the parentheses of the function. End your line wit
Add statements that the functions should execute.
End your function with a return statement if the function should output something.
Without the return statement, your function will return an object None
unction name.
f the function. End your line with a colon.
function block begin with the key word def followed by the function name and parenthesis
inside the parenthesis parameters are given
The Code Block within every function start with a colon : and is indented

Calling a function
To call a function, use the function name followed by parenthesis:

Parameters
Information can be passed to functions as parameter.
Parameters are specified after the function name, inside the parenthese
You can add as many parameters as you want, just separate them with a comma
e and parenthesis
Built in python function

to print an object to the terminal


Functions are a construct to structure programs. They are known in most programming languages, someti
Functions are used to utilize code in more than one place in a program. The only way without functions to
programming languages, sometimes also called subroutines or procedures.
he only way without functions to reuse code consists in copying the code.
#!
= assignment stmt
Web Programming With Python

Programming Review
Database Programming with Sqlite
FTP
Email
NewsGropup
Web client programming
webserver Programming
Web/Databse Programming
XMl Programming
Web framework Programming-Django
print is a function requires open and closed parenthesis with
argument
Variation of printing function

using end ='' with print to print two stmt in one line so what it
does don’t end with a new line end with a empty string
print("hello ")
print("hello world")

so if we want to print on the same line of two print function


print("hello ", end =' ' )
print("hello world")

what we will do if we have large gap like a tab

\t backslash t is a special character that represent a tab


print("hello ,\tworld")

or
=+---conctenation combining multiple string into one string
print("hello"+ "\t" + "tworld")

\n new line charactercauses line feed


print("hello,\ntworld!")

FOR LOOP
for i in range
StrongTyping
a=2
b='Tim'
type(a)
<class 'int'>
type(b)
<class 'str'>
c=3.14
type©
<class 'float'>

def adder(x,y):
print(x+y)

adder(2,2)
4
isinstance
int()
float()

help
Numeric DATA
Number expressions

Integers -0,1,2,+2,-2
Floating point number or fraction or Double-3.14,+3.14,-3.14
Hexa octal deci binary
Mathemtical operators-// integer division no remaainder
Modulus -retun the remaider
Exponent operator-**
precedence
built in mathematical function
pow
abs
round
sqrt
equal,==
isnotequalto !=

random
Character DATA
String expression

sequence of character inside single quote or double quotes but


dq are most standard most programming languages follow
str='Hello World';
str="Hello World";
str
Concatenation string with another string using plus sighn-
combined data
str=str + 'GoodBye,World!'
str

len()-tells how many characters


len(str)
array notation using squar brackets to disvoer postion of string
data character
str[0]
str[1]

slices in python
str[0, 4]
str[0, 4]
str[: 4]
str[4:]
str*2
split operator
takes a single argument a delimiter and splits up string into a list
based on that limiter
str. Split (' ')
split return the lists
\n is a new line character
print ('hello,world\n'goodbye world')
strip -cut down rogue spaces -cleaning data from irraneous
spaces
str ='Hello world!'
str.strip()
str ='Helloworld!'
str.rstrip()

PEMDAS-pleaseexcusemydearaunt sally-order of operatons


Boolean data type true or false true represent integer 1 false is
as a 0 and or

how to generate boolean data


assighment stmt

boo=l2==2
true
bool=2==3
false

python automatically assighn data type when using vaiable

Relational and logical operators

If stmt and decision making

tuple
Mutable data type
lists data structure

empty list represen by opening and closing brackets


[]
if item insert into the brackets seprated by comman if we like to
access we will do it b index notation

numbers=[1,2,3,4]

numbers
retrive each element losts indivually
numbers[0]+numbers[1]+numbers[2]+numbers[3]

numbers=[0:2]

len(numbers)

words =['now'; 'is']


words1= =['the','time']

words

words+words1

word=['hello']

word *5

nested sub lists

Dictionatry data structure lists


key and values pairs
Files

************************
Python input and output

Output------- how we print data to the screen


Input----------- how we received data from the keyboard

simple usage of print function

word ='hello' create variable


number=100 create variable

print(word) display the value of variable we simply put that


inside parenthesis and send that as an argument to the print
function and its print the value
print(number)

Lists data type


words = ['now', 'is', 'the','time']
print(words)

literals
print(100)
print('hello')

literal expression l such as concatenation


print('hello' + ''world')

Arithmethic exp
print(2*2)

tuple by using comma


print(word,number)

print(word+ ' '+number)to solve int with string expression


print(word+ ' '+str(number))
Format string
name ='Amry'
grade =81.7933

record ='%s: %2f' %(name,grade)


prit(record)

print redirection which mean print to the device other than the
screen

import sys
sys.stdout.write(hello\n)

sys.stdout=open('text.dat'.'a')
print('hello')
exit()

type text.dat-dos cmd type

import sys
sys.stdout=open('text.dat'.'a')
print('goodbye')
exit()

textfile=open('text.dat'.'a')
print >> textfile, 'hello'
print('goodbye')

Raw input
how to get data into the program from the keyborad

name =raw_input()
Mary Smith
print(name)

sentence=raw_input()
now is the time for all good people
print(sentence)

number=raw_input()
100
print (number*2)
number=(raw_input())
100
print(number*2)

number=float(raw_input())
2.22
print(number/1.4)
exit()

notepad add.py
print ("enter a number; ")
number1 = int(raw_input()
print ("enter a another number; ")
number2 = int(raw_input()
print ("The sum is: "+str (nuber1+number2))

Tasks small birthday gif enquires program-504

Conditional
If Stmt
Python program flow
when u define a function def key word is used

Use the keyword def to declare the function and follow this up with the function name.
Add parameters to the function: they should be within the parentheses of the function. End your line wit
Add statements that the functions should execute.
End your function with a return statement if the function should output something.
Without the return statement, your function will return an object None
unction name.
f the function. End your line with a colon.
function block begin with the key word def followed by the function name and parenthesis
inside the parenthesis parameters are given
The Code Block within every function start with a colon : and is indented

Calling a function
To call a function, use the function name followed by parenthesis:

Parameters
Information can be passed to functions as parameter.
Parameters are specified after the function name, inside the parenthese
You can add as many parameters as you want, just separate them with a comma
e and parenthesis
Built in python function

to print an object to the terminal


Functions are a construct to structure programs. They are known in most programming languages, someti
Functions are used to utilize code in more than one place in a program. The only way without functions to
programming languages, sometimes also called subroutines or procedures.
he only way without functions to reuse code consists in copying the code.
#!
= assignment stmt
Web Programming With Python

Programming Review
Database Programming with Sqlite
FTP
Email
NewsGropup
Web client programming
webserver Programming
Web/Databse Programming
XMl Programming
Web framework Programming-Django
print is a function requires open and closed parenthesis with
argument
Variation of printing function

using end ='' with print to print two stmt in one line so what it
does don’t end with a new line end with a empty string
print("hello ")
print("hello world")

so if we want to print on the same line of two print function


print("hello ", end =' ' )
print("hello world")

what we will do if we have large gap like a tab

\t backslash t is a special character that represent a tab


print("hello ,\tworld")

or
=+---conctenation combining multiple string into one string
print("hello"+ "\t" + "tworld")

\n new line charactercauses line feed


print("hello,\ntworld!")

FOR LOOP
for i in range
StrongTyping
a=2
b='Tim'
type(a)
<class 'int'>
type(b)
<class 'str'>
c=3.14
type©
<class 'float'>

def adder(x,y):
print(x+y)

adder(2,2)
4
isinstance
int()
float()

help
Numeric DATA
Number expressions

Integers -0,1,2,+2,-2
Floating point number or fraction or Double-3.14,+3.14,-3.14
Hexa octal deci binary
Mathemtical operators-// integer division no remaainder
Modulus -retun the remaider
Exponent operator-**
precedence
built in mathematical function
pow
abs
round
sqrt
equal,==
isnotequalto !=

random
Character DATA
String expression

sequence of character inside single quote or double quotes but


dq are most standard most programming languages follow
str='Hello World';
str="Hello World";
str
Concatenation string with another string using plus sighn-
combined data
str=str + 'GoodBye,World!'
str

len()-tells how many characters


len(str)
array notation using squar brackets to disvoer postion of string
data character
str[0]
str[1]

slices in python
str[0, 4]
str[0, 4]
str[: 4]
str[4:]
str*2
split operator
takes a single argument a delimiter and splits up string into a list
based on that limiter
str. Split (' ')
split return the lists
\n is a new line character
print ('hello,world\n'goodbye world')
strip -cut down rogue spaces -cleaning data from irraneous
spaces
str ='Hello world!'
str.strip()
str ='Helloworld!'
str.rstrip()

PEMDAS-pleaseexcusemydearaunt sally-order of operatons


Boolean data type true or false true represent integer 1 false is
as a 0 and or

how to generate boolean data


assighment stmt

boo=l2==2
true
bool=2==3
false

python automatically assighn data type when using vaiable

Relational and logical operators

If stmt and decision making

tuple
Mutable data type
lists data structure

empty list represen by opening and closing brackets


[]
if item insert into the brackets seprated by comman if we like to
access we will do it b index notation

numbers=[1,2,3,4]

numbers
retrive each element losts indivually
numbers[0]+numbers[1]+numbers[2]+numbers[3]

numbers=[0:2]

len(numbers)

words =['now'; 'is']


words1= =['the','time']

words

words+words1

word=['hello']

word *5

nested sub lists

Dictionatry data structure lists


key and values pairs
Files

************************
Python input and output

Output------- how we print data to the screen


Input----------- how we received data from the keyboard

simple usage of print function

word ='hello' create variable


number=100 create variable

print(word) display the value of variable we simply put that


inside parenthesis and send that as an argument to the print
function and its print the value
print(number)

Lists data type


words = ['now', 'is', 'the','time']
print(words)

literals
print(100)
print('hello')

literal expression l such as concatenation


print('hello' + ''world')

Arithmethic exp
print(2*2)

tuple by using comma


print(word,number)

print(word+ ' '+number)to solve int with string expression


print(word+ ' '+str(number))
Format string
name ='Amry'
grade =81.7933

record ='%s: %2f' %(name,grade)


prit(record)

print redirection which mean print to the device other than the
screen

import sys
sys.stdout.write(hello\n)

sys.stdout=open('text.dat'.'a')
print('hello')
exit()

type text.dat-dos cmd type

import sys
sys.stdout=open('text.dat'.'a')
print('goodbye')
exit()

textfile=open('text.dat'.'a')
print >> textfile, 'hello'
print('goodbye')

Raw input
how to get data into the program from the keyborad

name =raw_input()
Mary Smith
print(name)

sentence=raw_input()
now is the time for all good people
print(sentence)

number=raw_input()
100
print (number*2)
number=(raw_input())
100
print(number*2)

number=float(raw_input())
2.22
print(number/1.4)
exit()

notepad add.py
print ("enter a number; ")
number1 = int(raw_input()
print ("enter a another number; ")
number2 = int(raw_input()
print ("The sum is: "+str (nuber1+number2))

Tasks small birthday gif enquires program-504

Conditional
If Stmt
Python program flow
when u define a function def key word is used

Use the keyword def to declare the function and follow this up with the function name.
Add parameters to the function: they should be within the parentheses of the function. End your line wit
Add statements that the functions should execute.
End your function with a return statement if the function should output something.
Without the return statement, your function will return an object None
unction name.
f the function. End your line with a colon.
function block begin with the key word def followed by the function name and parenthesis
inside the parenthesis parameters are given
The Code Block within every function start with a colon : and is indented

Calling a function
To call a function, use the function name followed by parenthesis:

Parameters
Information can be passed to functions as parameter.
Parameters are specified after the function name, inside the parenthese
You can add as many parameters as you want, just separate them with a comma
e and parenthesis
Built in python function

to print an object to the terminal


Functions are a construct to structure programs. They are known in most programming languages, someti
Functions are used to utilize code in more than one place in a program. The only way without functions to
programming languages, sometimes also called subroutines or procedures.
he only way without functions to reuse code consists in copying the code.
#!
= assignment stmt
basics of classes and objects

define the object


the way we do this define the properties that it possesses
using a class

You can think of a class as a sort of template;


a guide for the way an object should be structured.

Each object belongs to a class


and inherits the properties of that class
but acts individually to the other objects of that class.

An object is sometimes referred to as an ‘instance’ of a class.

you might have a class named ‘person


with, say, an age and a name property,
and an instance of that class (an object) would be a single person
That person might have a name of “Andy” and an age of 23,
but you could simultaneously have another person belonging to the same class
with the name of “Lucy” and an age of 18.

Defining a class
To define a class, in typical simple Python fashion, Before writing your first class, you should k
we use the word ‘class,’ followed by the name of your new class
I’m going to make a new class here, called ‘pet’.
We use a colon after the name
and then anything contained within the class definition is indented

class pet:

So now we’ve got a class, but it’s rather useless without anything in it.
To start, let’s give it a couple of properties

To do this, you simply define some variables inside the class


I’m going to go with the number of legs to start with

As usual, you should always name your variables so that it’s easy to tell what they are
Let's be original and call it ‘number_of_legs’.
We need to define a value or we’ll get an error.

I’ll use 0 here (it doesn’t matter too much in this case
since the number of legs will be specific to each instance of the class

a fish doesn’t have the same amount of legs as a dog or a duck, etc. -
so we’ll have to change that value for each object anyway

Instances and member variables

A class on its own isn’t something you can directly manipulate;

first, we have to create an instance of the class to play with


We can store that instance in a variable

Outside of the class (without any indentation),

To make a new instance of a class, you simply type the name of the class,
and then a pair of parentheses

At this point, there’s no need to worry about the parentheses,


but later on you’ll see that they’re there
because, like a function, there’s a way of passing in a variable for use
by the class when you first create the instance.

Now that we have an instance of a class,

how do we access and manipulate its properties?


To reference a property of an object
first we have to tell Python which object (or which instance of a class) we’re talking about,

so we’re going to start with ‘doug

Then, we’re going to write a period


to indicate that we’re referencing something that’s contained within our doug instance

After the period, we add the name of our variable


If we’re accessing the number_of_legs variable, it’s going to look like this:

doug.number_of_legs

We can treat that now exactly as we would treat any other variable – here I’m going to assume

To access this variable, we’re going to use it again exactly as we would treat any other variable
, but using that doug.number_of_legs property instead of the normal variable name

Let’s put in a line to print out how many legs doug has so that we can show that it’s working as
class pet:
number_of_legs = 0

doug = pet()
doug.number_of_legs = 4
print "Doug has %s legs." %
doug.number_of_legs

If you run the code above, you'll see that it’s printed out for us
. It defined our ‘pet’ class,
created a new instance of that class
and stored it in the variable ‘doug’,
and then, inside that instance, it’s assigned the value of 4 to the number_of_legs variable that

classes as data structures - or, containers for variables

start performing more complex tasks with the data we’re manipulating

we need a way of introducing some logic into these objects

The way we do that is with methods.

Methods, essentially, are functions contained within a class

You define one in exactly the same way as you would a function,

but the difference is that you put it inside a class


and it belongs to that class
If you ever want to call that method,
you have to reference an object of that class
ust like the variables we were looking at previously.
Methods, essentially, are functions contained within a class.

We’ll see why that is later,


but for now you need to know that,
with a method, you always have to include an argument called ‘self
which is going to print out a message when it's first called.

Just like a function, I’m going to put ‘def’ for ‘define’,


and then I’m going to write the name of the method I want to create.
Then we’re going to put our parentheses and semicolon, and then start a new line
An ‘object’ can represent a person
(as defined by properties such as name, age, addre

or a company
(as defined by things like number of employees an

like a button in a computer interface

the same class

g your first class, you should know the syntax.


class nameoftheclass(parent_class):
class nameoftheclass(parent_class):
statement1
statement2
statement3

In the above example you can see first we are declaring a class called pet

, writing some random statements inside that class

to tell what they are

After the class definition, we are creating an object doug of the class pet
If you do a dir on that

>>> dir(doug)
['__doc__', '__module__', 'number of legs',
]
you can see the variables inside it.
class) we’re talking about,

thin our doug instance

ble – here I’m going to assume doug is a dog, and will give that variable the value of 4.

would treat any other variable


rmal variable name

e can show that it’s working as it should:


number_of_legs variable that it inherited from its class.
n start a new line
esent a person
erties such as name, age, address etc.),

gs like number of employees and so on),

mputer interface
I will add
you to
the
contribut
or list
(unless
you ask
to be
omitted).
problem solving solution
problem-solving skills