0% found this document useful (0 votes)
389 views32 pages

Python Fundmentals Idrees 1

Python is a popular programming language created in 1991 by Guido van Rossum. It is used for web development, software development, mathematics, and system scripting. Python can be used to create web applications, work with databases, perform complex mathematics, and more. It runs on many platforms and has a simple, easy to read syntax. To use Python, you first need to install it on your computer and then you can write and execute Python code by saving Python files with a .py extension or by using the Python interactive shell.

Uploaded by

ammar amir
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
Download as pdf or txt
0% found this document useful (0 votes)
389 views32 pages

Python Fundmentals Idrees 1

Python is a popular programming language created in 1991 by Guido van Rossum. It is used for web development, software development, mathematics, and system scripting. Python can be used to create web applications, work with databases, perform complex mathematics, and more. It runs on many platforms and has a simple, easy to read syntax. To use Python, you first need to install it on your computer and then you can write and execute Python code by saving Python files with a .py extension or by using the Python interactive shell.

Uploaded by

ammar amir
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
Download as pdf or txt
Download as pdf or txt
You are on page 1/ 32

What is Python?

Python is a popular programming language. It was created in 1991 by Guido van Rossum.
It is used for:
• web development (server-side),
• software development,
• mathematics,
• system scripting.

What can Python do?


• Python can be used on a server to create web applications.
• Python can be used alongside software to create workflows.
• Python can connect to database systems. It can also read and modify files.
• Python can be used to handle big data and perform complex mathematics.
• Python can be used for rapid prototyping, or for production-ready software development.

Why Python?
• Python works on different platforms (Windows, Mac, Linux, Raspberry Pi, etc).
• Python has a simple syntax similar to the English language.
• Python has syntax that allows developers to write programs with fewer lines than some other
programming languages.
• Python runs on an interpreter system, meaning that code can be executed as soon as it is
written. This means that prototyping can be very quick.
• Python can be treated in a procedural way, an object-orientated way or a functional way.

Good to know
• The most recent major version of Python is Python 3, which we shall be using in this
tutorial. However, Python 2, although not being updated with anything other than security
updates, is still quite popular.
• In this tutorial Python will be written in a text editor. It is possible to write Python in an
Integrated Development Environment, such as Thonny, Pycharm, Netbeans or Eclipse which
are particularly useful when managing larger collections of Python files.

Python Syntax compared to other programming languages


• Python was designed to for readability, and has some similarities to the English language
with influence from mathematics.
• Python uses new lines to complete a command, as opposed to other programming languages
which often use semicolons or parentheses.
• Python relies on indentation, using whitespace, to define scope; such as the scope of loops,
functions and classes. Other programming languages often use curly-brackets for this
purpose.
Python Install
Many PCs and Macs will have python already installed.
To check if you have python installed on a Windows PC, search in the start bar for Python or run
the following on the Command Line (cmd.exe):
C:\Users\Your Name>python --version
To check if you have python installed on a Linux or Mac, then on linux open the command line or
on Mac open the Terminal and type:
python --version
If you find that you do not have python installed on your computer, then you can download it for
free from the following website: https://www.python.org/

Python Quickstart
Python is an interpreted programming language, this means that as a developer you write Python
(.py) files in a text editor and then put those files into the python interpreter to be executed.
The way to run a python file is like this on the command line:
C:\Users\Your Name>python helloworld.py
Where "helloworld.py" is the name of your python file.
Let's write our first Python file, called helloworld.py, which can be done in any text editor.
helloworld.py
print("Hello, World!")
Simple as that. Save your file. Open your command line, navigate to the directory where you saved
your file, and run:
C:\Users\Your Name>python helloworld.py
The output should read:
Hello, World!
Congratulations, you have written and executed your first Python program.
Python Syntax

Execute Python Syntax


As we learned in the previous page, Python syntax can be executed by writing directly in the
Command Line:
>>> print("Hello, World!")
Hello, World!
Or by creating a python file on the server, using the .py file extension, and running it in the
Command Line:
C:\Users\Your Name>python myfile.py

Python Indentations
Where in other programming languages the indentation in code is for readability only, in Python the
indentation is very important.
Python uses indentation to indicate a block of code.

Example
if 5 > 2:
print("Five is greater than two!")
Python will give you an error if you skip the indentation:

Example
if 5 > 2:
print("Five is greater than two!")

Comments
Python has commenting capability for the purpose of in-code documentation.
Comments start with a #, and Python will render the rest of the line as a comment:

Example
Comments in Python:
#This is a comment.
print("Hello, World!")
Docstrings
Python also has extended documentation capability, called docstrings.
Docstrings can be one line, or multiline.
Python uses triple quotes at the beginning and end of the docstring:

Example
Docstrings are also comments:
"""This is a
multiline docstring."""
print("Hello, World!")
Python Variables

Creating Variables
Unlike other programming languages, Python has no command for declaring a variable.
A variable is created the moment you first assign a value to it.

Example
x=5
y = "John"
print(x)
print(y)
Variables do not need to be declared with any particular type and can even change type after they
have been set.

Example
x = 4 # x is of type int
x = "Sally" # x is now of type str
print(x)

Variable Names
A variable can have a short name (like x and y) or a more descriptive name (age, carname,
total_volume). Rules for Python variables:
• A variable name must start with a letter or the underscore character
• A variable name cannot start with a number
• A variable name can only contain alpha-numeric characters and underscores (A-z, 0-9, and _
)
• Variable names are case-sensitive (age, Age and AGE are three different variables)
Remember that variables are case-sensitive

Output Variables
The Python print statement is often used to output variables.

To combine both text and a variable, Python uses the + character:

Example
x = "awesome"
print("Python is " + x)
You can also use the + character to add a variable to another variable:
Example
x = "Python is "
y = "awesome"
z= x+y
print(z)
For numbers, the + character works as a mathematical operator:

Example
x=5
y = 10
print(x + y)
If you try to combine a string and a number, Python will give you an error:

Example
x=5
y = "John"
print(x + y)

Python Numbers

Python Numbers
There are three numeric types in Python:
• int
• float
• complex
Variables of numeric types are created when you assign a value to them:

Example
x = 1 # int
y = 2.8 # float
z = 1j # complex
To verify the type of any object in Python, use the type() function:

Example
print(type(x))
print(type(y))
print(type(z))
Int
Int, or integer, is a whole number, positive or negative, without decimals, of unlimited length.

Example
Integers:
x=1
y = 35656222554887711
z = -3255522

print(type(x))
print(type(y))
print(type(z))

Float
Float, or "floating point number" is a number, positive or negative, containing one or more
decimals.

Example
Floats:
x = 1.10
y = 1.0
z = -35.59

print(type(x))
print(type(y))
print(type(z))
Float can also be scientific numbers with an "e" to indicate the power of 10.

Example
Floats:
x = 35e3
y = 12E4
z = -87.7e100

print(type(x))
print(type(y))
print(type(z))
Complex
Complex numbers are written with a "j" as the imaginary part:

Example
Complex:
x = 3+5j
y = 5j
z = -5j

print(type(x))
print(type(y))
print(type(z))
Python Casting

Specify a Variable Type


There may be times when you want to specify a type on to a variable. This can be done with
casting. Python is an object-orientated language, and as such it uses classes to define data types,
including its primitive types.
Casting in python is therefore done using constructor functions:
• int() - constructs an integer number from an integer literal, a float literal (by rounding down
to the previous whole number), or a string literal (providing the string represents a whole
number)
• float() - constructs a float number from an integer literal, a float literal or a string literal
(providing the string represents a float or an integer)
• str() - constructs a string from a wide variety of data types, including strings, integer literals
and float literals

Example
Integers:
x = int(1) # x will be 1
y = int(2.8) # y will be 2
z = int("3") # z will be 3

Example
Floats:
x = float(1) # x will be 1.0
y = float(2.8) # y will be 2.8
z = float("3") # z will be 3.0
w = float("4.2") # w will be 4.2

Example
Strings:
x = str("s1") # x will be 's1'
y = str(2) # y will be '2'
z = str(3.0) # z will be '3.0'
Python Strings

String Literals
String literals in python are surrounded by either single quotation marks, or double quotation marks.
'hello' is the same as "hello".
Strings can be output to screen using the print function. For example: print("hello").
Like many other popular programming languages, strings in Python are arrays of bytes representing
unicode characters. However, Python does not have a character data type, a single character is
simply a string with a length of 1. Square brackets can be used to access elements of the string.

Example
Get the character at position 1 (remember that the first character has the position 0):
a = "Hello, World!"
print(a[1])

Example
Substring. Get the characters from position 2 to position 5 (not included):
b = "Hello, World!"
print(b[2:5])

Example
The strip() method removes any whitespace from the beginning or the end:
a = " Hello, World! "
print(a.strip()) # returns "Hello, World!"

Example
The len() method returns the length of a string:
a = "Hello, World!"
print(len(a))

Example
The lower() method returns the string in lower case:
a = "Hello, World!"
print(a.lower())

Example
The upper() method returns the string in upper case:
a = "Hello, World!"
print(a.upper())

Example
The replace() method replaces a string with another string:
a = "Hello, World!"
print(a.replace("H", "J"))

Example
The split() method splits the string into substrings if it finds instances of the separator:
a = "Hello, World!"
print(a.split(",")) # returns ['Hello', ' World!']

Command-line String Input


Python allows for command line input.
That means we are able to ask the user for input.
The following example asks for the user's name, then, by using the input() method, the program
prints the name to the screen:

Example
demo_string_input.py
print("Enter your name:")
x = input()
print("Hello, ", x)
Save this file as demo_string_input.py, and load it through the command line:
C:\Users\Your Name>python demo_string_input.py
Our program will prompt the user for a string:
Enter your name:
The user now enters a name:
Linus
Then, the program prints it to screen with a little message:
Hello, Linus
Python Operators

Python Operators
Operators are used to perform operations on variables and values.
Python divides the operators in the following groups:
• Arithmetic operators
• Assignment operators
• Comparison operators
• Logical operators
• Identity operators
• Membership operators
• Bitwise operators

Python Arithmetic Operators


Arithmetic operators are used with numeric values to perform common mathematical operations:

Operator Name Example


+ Addition x + y
- Subtraction x-y
* Multiplication x*y
/ Division x/y
% Modulus x%y
** Exponentiation x ** y
// Floor division x // y
Python Assignment Operators
Assignment operators are used to assign values to variables:

Operator Example Same As


= x=5 x=5
+= x += 3 x=x+3
-= x -= 3 x=x-3
*= x *= 3 x=x*3
/= x /= 3 x=x/3
%= x %= 3 x=x%3
//= x //= 3 x = x // 3
**= x **= 3 x = x ** 3
&= x &= 3 x=x&3
|= x |= 3 x=x|3
^= x ^= 3 x=x^3
>>= x >>= 3 x = x >> 3
<<= x <<= 3 x = x << 3

Python Comparison Operators


Comparison operators are used to compare two values:

Operator Name Example


== Equal x == y
!= Not equal x != y
> Greater than x>y
< Less than x<y
Greater than or
>= x >= y
equal to
Less than or
<= x <= y
equal to

Python Logical Operators


Logical operators are used to combine conditional statements:

Operator Description Example


and Returns True if both statements are true x < 5 and x < 10
or Returns True if one of the statements is true x < 5 or x < 4
Reverse the result, returns False if the result
not not(x < 5 and x < 10)
is true
Python Identity Operators
Identity operators are used to compare the objects, not if they are equal, but if they are actually the
same object, with the same memory location:

Operator Description Example


is Returns true if both variables are the same object x is y
Returns true if both variables are not the same
is not x is not y
object

Python Membership Operators


Membership operators are used to test if a sequence is presented in an object:

Operator Description Example


Returns True if a sequence with the specified value is present in the
in x in y
object
not in Returns True if a sequence with the specified value is not present in the object x not in y

Python Bitwise Operators


Bitwise operators are used to compare (binary) numbers:

Operator Name Description


& AND Sets each bit to 1 if both bits are 1
| OR Sets each bit to 1 if one of two bits is 1
^ XOR Sets each bit to 1 if only one of two bits is 1
~ NOT Inverts all the bits
Zero fill left Shift left by pushing zeros in from the right and let the leftmost bits fall
<<
shift off
Signed right Shift right by pushing copies of the leftmost bit in from the left, and let
>>
shift the rightmost bits fall off
Python Lists

Python Collections (Arrays)


There are four collection data types in the Python programming language:
• List is a collection which is ordered and changeable. Allows duplicate members.
• Tuple is a collection which is ordered and unchangeable. Allows duplicate members.
• Set is a collection which is unordered and unindexed. No duplicate members.
• Dictionary is a collection which is unordered, changeable and indexed. No duplicate
members.
When choosing a collection type, it is useful to understand the properties of that type. Choosing the
right type for a particular data set could mean retention of meaning, and, it could mean an increase
in efficiency or security.

List
A list is a collection which is ordered and changeable. In Python lists are written with square
brackets.

Example
Create a List:
thislist = ["apple", "banana", "cherry"]
print(thislist)

Access Items
You access the list items by referring to the index number:

Example
Print the second item of the list:
thislist = ["apple", "banana", "cherry"]
print(thislist[1])

Change Item Value


To change the value of a specific item, refer to the index number:

Example
Change the second item:
thislist = ["apple", "banana", "cherry"]
thislist[1] = "blackcurrant"
print(thislist)

Loop Through a List


You can loop through the list items by using a for loop:

Example
Print all items in the list, one by one:
thislist = ["apple", "banana", "cherry"]
for x in thislist:
print(x)
You will learn more about for loops in out Python For Loops Chapter.

Check if Item Exists


To determine if a specified item is present in a list use the in keyword:

Example
Check if "apple" is present in the list:
thislist = ["apple", "banana", "cherry"]
if "apple" in thislist:
print("Yes, 'apple' is in the fruits list")

List Length
To determine how many items a list has, use the len() method:

Example
Print the number of items in the list:
thislist = ["apple", "banana", "cherry"]
print(len(thislist))

Add Items
To add an item to the end of the list, use the append() method:

Example
Using the append() method to append an item:
thislist = ["apple", "banana", "cherry"]
thislist.append("orange")
print(thislist)
To add an item at the specified index, use the insert() method:

Example
Insert an item as the second position:
thislist = ["apple", "banana", "cherry"]
thislist.insert(1, "orange")
print(thislist)

Remove Item
There are several methods to remove items from a list:

Example
The remove() method removes the specified item:

thislist = ["apple", "banana", "cherry"]


thislist.remove("banana")
print(thislist)

Example
The pop() method removes the specified index, (or the last item if index is not specified):

thislist = ["apple", "banana", "cherry"]


thislist.pop()
print(thislist)

Example
The del keyword removes the specified index:

thislist = ["apple", "banana", "cherry"]


del thislist[0]
print(thislist)

Example
The del keyword can also delete the list completely:

thislist = ["apple", "banana", "cherry"]


del thislist

Example
The clear() method empties the list:
thislist = ["apple", "banana", "cherry"]
thislist.clear()
print(thislist)

The list() Constructor


It is also possible to use the list() constructor to make a list.

Example
Using the list() constructor to make a List:
thislist = list(("apple", "banana", "cherry")) # note the double round-brackets
print(thislist)

List Methods
Python has a set of built-in methods that you can use on lists.

Method Description
append() Adds an element at the end of the list
clear() Removes all the elements from the list
copy() Returns a copy of the list
count() Returns the number of elements with the specified value
extend() Add the elements of a list (or any iterable), to the end of the current list
index() Returns the index of the first element with the specified value
insert() Adds an element at the specified position
pop() Removes the element at the specified position
remove() Removes the item with the specified value
reverse() Reverses the order of the list
sort() Sorts the list
Python If ... Else

Python Conditions and If statements


Python supports the usual logical conditions from mathematics:
• Equals: a == b
• Not Equals: a != b
• Less than: a < b
• Less than or equal to: a <= b
• Greater than: a > b
• Greater than or equal to: a >= b
These conditions can be used in several ways, most commonly in "if statements" and loops.
An "if statement" is written by using the if keyword.

Example
If statement:
a = 33
b = 200
if b > a:
print("b is greater than a")
In this example we use two variables, a and b, which are used as part of the if statement to test
whether b is greater than a. As a is 33, and b is 200, we know that 200 is greater than 33, and so we
print to screen that "b is greater than a".

Indentation
Python relies on indentation, using whitespace, to define scope in the code. Other programming
languages often use curly-brackets for this purpose.

Example
If statement, without indentation (will raise an error):
a = 33
b = 200
if b > a:
print("b is greater than a") # you will get an error
Elif
The elif keyword is pythons way of saying "if the previous conditions were not true, then try this
condition".

Example
a = 33
b = 33
if b > a:
print("b is greater than a")
elif a == b:
print("a and b are equal")
In this example a is equal to b, so the first condition is not true, but the elif condition is true, so we
print to screen that "a and b are equal".

Else
The else keyword catches anything which isn't caught by the preceding conditions.

Example
a = 200
b = 33
if b > a:
print("b is greater than a")
elif a == b:
print("a and b are equal")
else:
print("a is greater than b")
In this example a is greater to b, so the first condition is not true, also the elif condition is not true,
so we go to the else condition and print to screen that "a is greater than b".
You can also have an else without the elif:

Example
a = 200
b = 33
if b > a:
print("b is greater than a")
else:
print("b is not greater than a")
Short Hand If
If you have only one statement to execute, you can put it on the same line as the if statement.

Example
One line if statement:
if a > b: print("a is greater than b")

Short Hand If ... Else


If you have only one statement to execute, one for if, and one for else, you can put it all on the same
line:

Example
One line if else statement:
print("A") if a > b else print("B")
You can also have multiple else statements on the same line:

Example
One line if else statement, with 3 conditions:
print("A") if a > b else print("=") if a == b else print("B")

And
The and keyword is a logical operator, and is used to combine conditional statements:

Example
Test if a is greater than b, AND if c is greater than a:

if a > b and c > a:


print("Both conditions are True")

Or
The or keyword is a logical operator, and is used to combine conditional statements:

Example
Test if a is greater than b, OR if a is greater than c:

if a > b or a > c:
print("At least one of the conditions is True")
Python While Loops

Python Loops
Python has two primitive loop commands:
• while loops
• for loops

The while Loop


With the while loop we can execute a set of statements as long as a condition is true.

Example
Print i as long as i is less than 6:
i=1
while i < 6:
print(i)
i += 1
Note: remember to increment i, or else the loop will continue forever.
The while loop requires relevant variables to be ready, in this example we need to define an
indexing variable, i, which we set to 1.

The break Statement


With the break statement we can stop the loop even if the while condition is true:

Example
Exit the loop when i is 3:
i=1
while i < 6:
print(i)
if i == 3:
break
i += 1
The continue Statement
With the continue statement we can stop the current iteration, and continue with the next:
Example
Continue to the next iteration if i is 3:
i=0
while i < 6:
i += 1
if i == 3:
continue
print(i)
Python For Loops

Python For Loops


A for loop is used for iterating over a sequence (that is either a list, a tuple, a dictionary, a set, or a
string).
This is less like the for keyword in other programming language, and works more like an iterator
method as found in other object-orientated programming languages.
With the for loop we can execute a set of statements, once for each item in a list, tuple, set etc.

Example
Print each fruit in a fruit list:
fruits = ["apple", "banana", "cherry"]
for x in fruits:
print(x)
The for loop does not require an indexing variable to set beforehand.

Looping Through a String


Even strings are iterable objects, they contain a sequence of characters:

Example
Loop through the letters in the word "banana":
for x in "banana":
print(x)

The break Statement


With the break statement we can stop the loop before it has looped through all the items:

Example
Exit the loop when x is "banana":

fruits = ["apple", "banana", "cherry"]


for x in fruits:
print(x)
if x == "banana":
break
Example
Exit the loop when x is "banana", but this time the break comes before the print:

fruits = ["apple", "banana", "cherry"]


for x in fruits:
if x == "banana":
break
print(x) The continue Statement
With the continue statement we can stop the current iteration of the loop, and continue with the
next:

Example
Do not print banana:
fruits = ["apple", "banana", "cherry"]
for x in fruits:
if x == "banana":
continue
print(x)

The range() Function


To loop through a set of code a specified number of times, we can use the range() function,
The range() function returns a sequence of numbers, starting from 0 by default, and increments by 1
(by default), and ends at a specified number.

Example
Using the range() function:
for x in range(6):
print(x)
Note that range(6) is not the values of 0 to 6, but the values 0 to 5.
The range() function defaults to 0 as a starting value, however it is possible to specify the starting
value by adding a parameter: range(2, 6), which means values from 2 to 6 (but not including 6):

Example
Using the start parameter:
for x in range(2, 6):
print(x)
The range() function defaults to increment the sequence by 1, however it is possible to specify the
increment value by adding a third parameter: range(2, 30, 3):
Example
Increment the sequence with 3 (default is 1):
for x in range(2, 30, 3):
print(x)

Else in For Loop


The else keyword in a for loop specifies a block of code to be executed when the loop is
finished:

Example
Print all numbers from 0 to 5, and print a message when the loop has ended:
for x in range(6):
print(x)
else:
print("Finally finished!")

Nested Loops
A nested loop is a loop inside a loop.
The "inner loop" will be executed one time for each iteration of the "outer loop":

Example
Print each adjective for every fruit:
adj = ["red", "big", "tasty"]
fruits = ["apple", "banana", "cherry"]

for x in adj:
for y in fruits:
print(x, y)
Python Functions
A function is a block of code which only runs when it is called.
You can pass data, known as parameters, into a function.
A function can return data as a result.

Creating a Function
In Python a function is defined using the def keyword:

Example
def my_function():
print("Hello from a function")

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

Example
def my_function():
print("Hello from a function")

my_function()

Parameters
Information can be passed to functions as parameter.
Parameters are specified after the function name, inside the parentheses. You can add as many
parameters as you want, just separate them with a comma.
The following example has a function with one parameter (fname). When the function is called, we
pass along a first name, which is used inside the function to print the full name:

Example
def my_function(fname):
print(fname + " Refsnes")

my_function("Emil")
my_function("Tobias")
my_function("Linus")
Default Parameter Value
The following example shows how to use a default parameter value.
If we call the function without parameter, it uses the default value:

Example
def my_function(country = "Norway"):
print("I am from " + country)

my_function("Sweden")
my_function("India")
my_function()
my_function("Brazil")

Return Values
To let a function return a value, use the return statement:

Example
def my_function(x):
return 5 * x

print(my_function(3))
print(my_function(5))
print(my_function(9))

Recursion
Python also accepts function recursion, which means a defined function can call itself.
Recursion is a common mathematical and programming concept. It means that a function calls
itself. This has the benefit of meaning that you can loop through data to reach a result.
The developer should be very careful with recursion as it can be quite easy to slip into writing a
function which never terminates, or one that uses excess amounts of memory or processor power.
However, when written correctly recursion can be a very efficient and mathematically-elegant
approach to programming.
In this example, tri_recursion() is a function that we have defined to call itself ("recurse"). We use
the k variable as the data, which decrements (-1) every time we recurse. The recursion ends when
the condition is not greater than 0 (i.e. when it is 0).
To a new developer it can take some time to work out how exactly this works, best way to find out
is by testing and modifying it.
Example
Recursion Example
def tri_recursion(k):
if(k>0):
result = k+tri_recursion(k-1)
print(result)
else:
result = 0
return result

print("\n\nRecursion Example Results")


tri_recursion(6)
Python Classes and Objects

Python Classes/Objects
Python is an object oriented programming language.
Almost everything in Python is an object, with its properties and methods.
A Class is like an object constructor, or a "blueprint" for creating objects.

Create a Class
To create a class, use the keyword class:

Example
Create a class named MyClass, with a property named x:
class MyClass:
x=5

Create Object
Now we can use the class named myClass to create objects:

Example
Create an object named p1, and print the value of x:
p1 = MyClass()
print(p1.x)

The __init__() Function


The examples above are classes and objects in their simplest form, and are not really useful in real
life applications.
To understand the meaning of classes we have to understand the built-in __init__() function.
All classes have a function called __init__(), which is always executed when the class is being
initiated.
Use the __init__() function to assign values to object properties, or other operations that are
necessary to do when the object is being created:
Example
Create a class named Person, use the __init__() function to assign values for name and age:
class Person:
def __init__(self, name, age):
self.name = name
self.age = age

p1 = Person("John", 36)

print(p1.name)
print(p1.age)
Note: The __init__() function is called automatically every time the class is being used to
create a new object.

Object Methods
Objects can also contain methods. Methods in objects are functions that belongs to the object.
Let us create a method in the Person class:

Example
Insert a function that prints a greeting, and execute it on the p1 object:
class Person:
def __init__(self, name, age):
self.name = name
self.age = age

def myfunc(self):
print("Hello my name is " + self.name)

p1 = Person("John", 36)
p1.myfunc()
Note: The self parameter is a reference to the class instance itself, and is used to access variables
that belongs to the class.

The self Parameter


The self parameter is a reference to the class itself, and is used to access variables that belongs to
the class.
It does not have to be named self , you can call it whatever you like, but it has to be the first
parameter of any function in the class:
Example
Use the words mysillyobject and abc instead of self:
class Person:
def __init__(mysillyobject, name, age):
mysillyobject.name = name
mysillyobject.age = age

def myfunc(abc):
print("Hello my name is " + abc.name)

p1 = Person("John", 36)
p1.myfunc()

Modify Object Properties


You can modify properties on objects like this:

Example
Set the age of p1 to 40:
p1.age = 40

Delete Object Properties


You can delete properties on objects by using the del keyword:

Example
Delete the age property from the p1 object:
del p1.age

Delete Objects
You can delete objects by using the del keyword:

Example
Delete the p1 object:
del p1

You might also like