0% found this document useful (0 votes)
19 views

Python

Uploaded by

vermaratan12911
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
19 views

Python

Uploaded by

vermaratan12911
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 106

Python Introduction

What is Python?

Python is a popular programming language. It was created by Guido van Rossum, and released in 1991.

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, me aning 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-oriented way or a functional way.

Python Variables

Variables:-

Variables are containers for storing data values.

Creating Variables

Python has no command for declaring a variable

example:

1)x = 5

y = "John"
print(x)

print(y)

output:-5

John

2)x = 4

x = "Sally"

print(x)

output:-Sally

3)c

4)a = 4

A = "Sally"

print(a)

print(A)

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)

A variable name cannot be any of the Python keywords.

example:

myvar = "John"

my_var = "John"

_my_var = "John"

myVar = "John"

MYVAR = "John"

myvar2 = "John"

print(myvar)
print(my_var)

print(_my_var)

print(myVar)

print(MYVAR)

print(myvar2)

output:-John

John

John

John

John

John

Assign Multiple Values:-

exampple:

1)x, y, z = "Orange", "Banana", "Cherry"

print(x)

print(y)

print(z)

output:-

Orange

Banana

Cherry

2)x = y = z = "Orange"

print(x)

print(y)

print(z)

output:-

Orange

Orange

Orange
3)

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

x, y, z = fruits

print(x)

print(y)

print(z)

output:-

apple

banana

cherry

Output Variables:-

The Python print() function is often used to output variables.

example:-

1)x = "Python is awesome"

print(x)

output:-Python is awesome

2)x = "Python"

y = "is"

z = "awesome"

print(x, y, z)

output:-

Python is awesome

Global Variables:-

Variables that are created outside of a function (as in all of the examples above) are known as global variables.

Global variables can be used by everyone, both inside of functions and outside.

example:-

1)x = "awesome"

def myfunc():
print("Python is " + x)

myfunc()

output:-

Python is awesome

2)x = "awesome"

def myfunc():

x = "fantastic"

print("Python is " + x)

myfunc()

print("Python is " + x)

output:

Python is fantastic

Python is awesome

3)x = "awesome"

def myfunc():

global x

x = "fantastic"

myfunc()

print("Python is " + x)

output:

Python is fantastic

Python Data Types:-

Variables can store data of different types, and different types can do different things.
Python has the following data types built-in by default, in these categories:

Text Type: str

Numeric Types: int, float, complex

Sequence Type:list, tuple, range

Mapping Type: dict

Set Types: set, frozenset

Boolean Type: bool

Binary Types: bytes, bytearray, memoryview

None Type: NoneType

1)str

x = "Hello World"

#display x:

print(x)

#display the data type of x:

print(type(x))

output:-

Hello World

<class 'str'>

2)int

x = 20

#display x:

print(x)

#display the data type of x:

print(type(x))

output:-

20

<class 'int'>
3)float

x = 20.5

#display x:

print(x)

#display the data type of x:

print(type(x))

output:-

20.5

<class 'float'>

4)complex

x = 1j

#display x:

print(x)

#display the data type of x:

print(type(x))

output:-

1j

<class 'complex'>

5)list

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

#display x:

print(x)

#display the data type of x:

print(type(x))

output:-

['apple', 'banana', 'cherry']


<class 'list'>

6)tuple

x = ("apple", "banana", "cherry")

#display x:

print(x)

#display the data type of x:

print(type(x))

output:-

('apple', 'banana', 'cherry')

<class 'tuple'>

7)range

x = range(6)

#display x:

print(x)

#display the data type of x:

print(type(x))

output:

range(2, 6)

<class 'range'>

8)dict

x = {"name" : "John", "age" : 36}

#display x:

print(x)

#display the data type of x:

print(type(x))

output:
{'name': 'John', 'age': 36}

<class 'dict'>

9)set

x = {"apple", "banana", "cherry"}

#display x:

print(x)

#display the data type of x:

print(type(x))

output:

{'apple', 'cherry', 'banana'}

<class 'set'>

10)frozenset

x = frozenset({"apple", "banana", "cherry"})

#display x:

print(x)

#display the data type of x:

print(type(x))

output:frozenset({'cherry', 'banana', 'apple'})

<class 'frozenset'>

11)bool

x = True

#display x:

print(x)

#display the data type of x:

print(type(x))

output:
True

<class 'bool'>

12)bytes

x = b"Hello"

#display x:

print(x)

#display the data type of x:

print(type(x))

output:

b'Hello'

<class 'bytes'>

13)bytearray

x = bytearray(5)

#display x:

print(x)

#display the data type of x:

print(type(x))

output:

bytearray(b'\x00\x00\x00\x00\x00')

<class 'bytearray'>

14)memoryview

x = memoryview(bytes(5))

#display x:

print(x)

#display the data type of x:

print(type(x))
output:

<memory at 0x006F8FA0>

<class 'memoryview'>

15)NoneType

x = None

#display x:

print(x)

#display the data type of x:

print(type(x))

output:

None

<class 'NoneType'>

Python Numbers

There are three numeric types in Python:

1)int

2)float

3)complex

example:

1)

x=1

y = 2.8

z = 1j

print(type(x))

print(type(y))

print(type(z))

output:

<class 'int'>
<class 'float'>

<class 'complex'>

Int:-

x=1

y = 35656222554887711

z = -3255522

print(type(x))

print(type(y))

print(type(z))

output:

<class 'int'>

<class 'int'>

<class 'int'>

Float:-

x = 1.10

y = 1.0

z = -35.59

print(type(x))

print(type(y))

print(type(z))

output:

<class 'float'>

<class 'float'>

<class 'float'>

Complex:-

x = 3+5j

y = 5j

z = -5j

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

print(type(z))

output:-

<class 'complex'>

<class 'complex'>

<class 'complex'>

Type Conversion:-

x = float(1)

#convert from float to int:

y = int(2.8)

#convert from int to complex:

z = complex(1)

print(x)

print(y)

print(z)

print(type(x))

print(type(y))

print(type(z))

output:

1.0

(1+0j)

<class 'float'>

<class 'int'>

<class 'complex'>

Random Number:

import random
print(random.randrange(1, 10))

Python Casting:-

Casting in python is therefore done using constructor functions:

1)int() - constructs an integer number from an integer literal, a float literal (by removing all decimals), or a string
literal (providing the string represents a whole number)

2)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)

3)str() - constructs a string from a wide variety of data types, including strings, integer literals and float literals

example:

1)x = int(1)

y = int(2.8)

z = int("3")

print(x)

print(y)

print(z)

output:

2)x = float(1)

y = float(2.8)

z = float("3")

w = float("4.2")

print(x)

print(y)

print(z)

print(w)

output:
1.0

2.8

3.0

4.2

3)x = str("s1")

y = str(2)

z = str(3.0)

print(x)

print(y)

print(z)

output:

s1

3.0

Python Strings:-

Strings:

Strings in python are surrounded by either single quotation marks, or double quotation marks.

'hello' is the same as "hello".

example:

print("Hello")

print('Hello')

output:

Hello

Hello

Assign String to a Variable:-

example:

a = "Hello"

print(a)

output:

Hello
Multiline Strings:-

example:

a = """Lorem ipsum dolor sit amet,

consectetur adipiscing elit,

sed do eiusmod tempor incididunt

ut labore et dolore magna aliqua."""

print(a)

output:

Lorem ipsum dolor sit amet,

consectetur adipiscing elit,

sed do eiusmod tempor incididunt

ut labore et dolore magna aliqua.

Strings are Arrays:-

example:

a = "Hello, World!"

print(a[1])

output:

Looping Through a String:-

example:

for x in "banana":

print(x)

output:

String Length:-

Example:

a = "Hello, World!"
print(len(a))

output:13

Check String:-

1)txt = "The best things in life are free!"

print("free" in txt)

output:True

2)txt = "The best things in life are free!"

if "free" in txt:

print("Yes, 'free' is present.")

output:

Yes, 'free' is present.

Check if NOT:-

1)txt = "The best things in life are free!"

print("expensive" not in txt)

output:True

2)txt = "The best things in life are free!"

if "expensive" not in txt:

print("No, 'expensive' is NOT present.")

output:No, 'expensive' is NOT present.

Python - Slicing Strings:-

example:

1)b = "Hello, World!"

print(b[2:5])

output:llo

2)b = "Hello, World!"

print(b[:5])

output:Hello

3)b = "Hello, World!"


print(b[2:])

output:llo, World!

4)b = "Hello, World!"

print(b[-5:-2])

output:orl

Python - Modify Strings:-

1)a = "Hello, World!"

print(a.upper())

output:HELLO, WORLD!

2)a = "Hello, World!"

print(a.lower())

output:hello, world!

3)a = " Hello, World! "

print(a.strip())

output:Hello, World!

4)a = "Hello, World!"

print(a.replace("H", "J"))

output:Jello, World!

5)a = "Hello, World!"

b = a.split(",")

print(b)

output:['Hello', ' World!']

Python - String Concatenation:-

1)a = "Hello"

b = "World"

c=a+b

print(c)

output:HelloWorld
2)a = "Hello"

b = "World"

c=a+""+b

print(c)

output:Hello World

Python - Format Strings:-

1)age = 36

txt = "My name is John, and I am {}"

print(txt.format(age))

output:My name is John, and I am 36

2)quantity = 3

itemno = 567

price = 49.95

myorder = "I want {} pieces of item {} for {} dollars."

print(myorder.format(quantity, itemno, price))

output:I want 3 pieces of item 567 for 49.95 dollars.

3)quantity = 3

itemno = 567

price = 49.95

myorder = "I want to pay {2} dollars for {0} pieces of item {1}."

print(myorder.format(quantity, itemno, price))

output:I want to pay 49.95 dollars for 3 pieces of item 567.

STRING METHOD:

Method Description

capitalize() Converts the first character to upper case

casefold() Converts string into lower case

center()Returns a centered string

count() Returns the number of times a specified value occurs in a string

encode() Returns an encoded version of the string

endswith() Returns true if the string ends with the specified value
expandtabs() Sets the tab size of the string

find() Searches the string for a specified value and returns the position of where it was found

format() Formats specified values in a string

format_map() Formats specified values in a string

index() Searches the string for a specified value and returns the position of where it was found

isalnum() Returns True if all characters in the string are alphanumeric

isalpha() Returns True if all characters in the string are in the alphabet

isascii() Returns True if all characters in the string are ascii characters

isdecimal() Returns True if all characters in the string are decimals

isdigit() Returns True if all characters in the string are digits

isidentifier() Returns True if the string is an identifier

islower() Returns True if all characters in the string are lower case

isnumeric() Returns True if all characters in the string are numeric

isprintable() Returns True if all characters in the string are printable

isspace() Returns True if all characters in the string are whitespaces

istitle() Returns True if the string follows the rules of a title

isupper() Returns True if all characters in the string are upper case

join() Joins the elements of an iterable to the end of the string

ljust() Returns a left justified version of the string

lower() Converts a string into lower case

lstrip() Returns a left trim version of the string

maketrans() Returns a translation table to be used in translations

partition() Returns a tuple where the string is parted into three parts

replace() Returns a string where a specified value is replaced with a specified value

rfind() Searches the string for a specified value and returns the last position of where it was found

rindex() Searches the string for a specified value and returns the last position of where it was found

rjust() Returns a right justified version of the string

rpartition() Returns a tuple where the string is parted into three parts

rsplit() Splits the string at the specified separator, and returns a list

rstrip() Returns a right trim version of the string

split() Splits the string at the specified separator, and returns a list

splitlines() Splits the string at line breaks and returns a list

startswith() Returns true if the string starts with the specified value

strip() Returns a trimmed version of the string

swapcase() Swaps cases, lower case becomes upper case and vice versa
title() Converts the first character of each word to upper case

translate() Returns a translated string

upper() Converts a string into upper case

zfill() Fills the string with a specified number of 0 values at the beginning

* Python Booleans:-Booleans represent one of two values: True or False.

example:-

1)print(10 > 9)

print(10 == 9)ss

print(10 < 9)

output:

True

False

False

2)print(bool("Hello"))

print(bool(15))

output:

True

True

* 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

Example:

1) x = 5

y=3

print(x + y)

2) x = 5

y=3

print(x - y)

3) x = 5

y=3

print(x *y)
4) x = 5

y=3

print(x / y)

5) x = 5

y=3

print(x % y)

6) x = 2

y=5

print(x ** y) #same as 2*2*2*2*2

7) x = 15

y=2

print(x // y)

#the floor division // rounds the result down to the nearest whole number

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

:= print(x := 3) x=3
print(x)

Example:

1) x = 5

print(x)

2) x = 5

x += 3

print(x)
3)x = 5

x -= 3

print(x)

4) x = 5

x *= 3

print(x)

5) x = 5

x /= 3

print(x)

6) x = 5

x %= 3

print(x)

7) x = 5

x //= 3

print(x)

8) x = 5

x **= 3

print(x)

9) x = 5

x &= 3

print(x)

10) x = 5

x |= 3

print(x)

11) x = 5

x ^= 3
print(x)

12) x = 5

x >>= 3

print(x)

13) x = 5

x <<= 3

print(x)

14) print(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 equal to x >= y

<= Less than or equal to x <= y

1)x = 5

y=3
print(x == y)

2) x = 5

y=3

print(x != y)

3) x = 5

y=3

print(x >y)

4) x = 5

y=3

print(x < y)

5) x = 5

y=3

print(x >=y)

6) x = 5

y=3

print(x <= y)

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

Not Reverse the result, returns False if the not(x < 5 and x < 10)
result is true

Example:

1) x = 5

print(x > 3 and x < 10)

2) x = 5

print(x > 3 or x < 10)

3) x = 5

print(not(x > 3 and x < 10))

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 x is y


object

is not Returns True if both variables are not the x is not y


same object

Example:

1) x = ["apple", "banana"]

y = ["apple", "banana"]

z=x

print(x is z)

# returns True because z is the same object as x

print(x is y)
# returns False because x is not the same object as y, even if they have the same content

print(x == y)

# to demonstrate the difference betweeen "is" and "==": this comparison returns True because x is equal to y

2) x = ["apple", "banana"]

y = ["apple", "banana"]

z=x

print(x is not z)

# returns False because z is the same object as x

print(x is not y)

# returns True because x is not the same object as y, even if they have the same content

print(x != y)

# to demonstrate the difference betweeen "is not" and "!=": this comparison returns False because x is equal
to y

Python Membership Operators


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

Operator Description Example

in Returns True if a sequence with the specified value x in y


is present in the object

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


is not present in the object

Example:

1) x = ["apple", "banana"]

print("banana" in x)

# returns True because a sequence with the value "banana" is in the list
2) x = ["apple", "banana"]

print("pineapple" not in x)

# returns True because a sequence with the value "pineapple" is not in the list

Python Bitwise Operators


Bitwise operators are used to compare (binary) numbers:

Operato Name Description Example


r

& AND Sets each bit to 1 if both bits are 1 x&y

| OR Sets each bit to 1 if one of two bits is 1 x|y

^ XOR Sets each bit to 1 if only one of two bits is 1 x^y

~ NOT Inverts all the bits ~x

<< Zero fill left Shift left by pushing zeros in from the right and let x << 2
shift the leftmost bits fall off

>> Signed Shift right by pushing copies of the leftmost bit in x >> 2
right shift from the left, and let the rightmost bits fall off

Example:

1) print(6 & 3)
2) print(6 | 3)
3) print(6 ^ 3)
4) print(~3)
5) print(3 << 2)
6) print(8 >> 2)
List
Lists are used to store multiple items in a single variable.

List items are ordered, changeable, and allow duplicate values.

List items are indexed, the first item has index [0], the second item has index [1] etc.

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, unchangeable*, and unindexed. No duplicate
members.
 Dictionary is a collection which is ordered** and changeable. No duplicate
members.

Example:
Example: 1) thislist = ["apple", "banana", "cherry"]
print(thislist)

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

print(len(thislist))

Data Types
list1 = ["apple", "banana", "cherry"]

list2 = [1, 5, 7, 9, 3]

list3 = [True, False, False]

print(list1)

print(list2)

print(list3)

type()
mylist = ["apple", "banana", "cherry"]

print(type(mylist))

list() Constructor
thislist = list(("apple", "banana", "cherry"))

print(thislist)
Access Items
thislist = ["apple", "banana", "cherry"]

print(thislist[1])

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

print(thislist[-1])

Range of Indexes
thislist = ["apple", "banana", "cherry", "orange", "kiwi", "melon", "mango"]

print(thislist[2:5])

Range of Negative Indexes


thislist = ["apple", "banana", "cherry", "orange", "kiwi", "melon", "mango"]

print(thislist[-4:-1])

Check if Item Exists


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

if "apple" in thislist:

print("Yes, 'apple' is in the fruits list")

Change Item Value


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

thislist[1] = "blackcurrant"

print(thislist)

Change a Range of Item Values


1)thislist = ["apple", "banana", "cherry", "orange", "kiwi", "mango"]

thislist[1:3] = ["blackcurrant", "watermelon"]

print(thislist)

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

thislist[1:3] = ["watermelon"]

print(thislist)

Insert Items
thislist = ["apple", "banana", "cherry"]
thislist.insert(2, "watermelon")

print(thislist)

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

thislist.append("orange")

print(thislist)

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

tropical = ["mango", "pineapple", "papaya"]

thislist.extend(tropical)

print(thislist)

Add Any Iterable


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

thistuple = ("kiwi", "orange")

thislist.extend(thistuple)

print(thislist)

Remove Specified Item


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

thislist.remove("banana")

print(thislist)

Remove Specified Index


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

thislist.pop(1)

print(thislist)

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

del thislist[0]

print(thislist)
Clear the List
thislist = ["apple", "banana", "cherry"]

thislist.clear()

print(thislist)

Loop Through a List


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

for x in thislist:

print(x)

Loop Through the Index Numbers


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

for i in range(len(thislist)):

print(thislist[i])

Using a While Loop


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

i=0

while i < len(thislist):

print(thislist[i])

i=i+1

Looping Using List Comprehension


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

[print(x) for x in thislist]

List Comprehension
1)fruits = ["apple", "banana", "cherry", "kiwi", "mango"]

newlist = []

for x in fruits:
if "a" in x:

newlist.append(x)

print(newlist)

2) fruits = ["apple", "banana", "cherry", "kiwi", "mango"]

newlist = [x for x in fruits if "a" in x]

print(newlist)

3) fruits = ["apple", "banana", "cherry", "kiwi", "mango"]

newlist = [x for x in fruits if x != "apple"]

print(newlist)

4) fruits = ["apple", "banana", "cherry", "kiwi", "mango"]

newlist = [x for x in fruits]

print(newlist)

Iterable
1)newlist = [x for x in range(10)]

print(newlist)

2)newlist = [x for x in range(10) if x < 5]

print(newlist)

Expression
1) fruits = ["apple", "banana", "cherry", "kiwi", "mango"]

newlist = [x.upper() for x in fruits]

print(newlist)

2) fruits = ["apple", "banana", "cherry", "kiwi", "mango"]

newlist = ['hello' for x in fruits]

print(newlist)

3) fruits = ["apple", "banana", "cherry", "kiwi", "mango"]

newlist = [x if x != "banana" else "orange" for x in fruits]

print(newlist)
Sort List Alphanumerically
1)thislist = ["orange", "mango", "kiwi", "pineapple", "banana"]

thislist.sort()

print(thislist)

2) thislist = [100, 50, 65, 82, 23]

thislist.sort()

print(thislist)

Sort Descending
1)thislist = ["orange", "mango", "kiwi", "pineapple", "banana"]

thislist.sort(reverse = True)

print(thislist)

2) thislist = [100, 50, 65, 82, 23]

thislist.sort(reverse = True)

print(thislist)

Reverse Order
thislist = ["banana", "Orange", "Kiwi", "cherry"]

thislist.reverse()

print(thislist)

Case Insensitive Sort


1)thislist = ["banana", "Orange", "Kiwi", "cherry"]

thislist.sort()

print(thislist)

2) thislist = ["banana", "Orange", "Kiwi", "cherry"]

thislist.sort(key = str.lower)

print(thislist)
Copy a List
1)thislist = ["apple", "banana", "cherry"]

mylist = thislist.copy()

print(mylist)

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

mylist = list(thislist)

print(mylist)

Join Two Lists


1)list1 = ["a", "b", "c"]

list2 = [1, 2, 3]

list3 = list1 + list2

print(list3)

2) list1 = ["a", "b" , "c"]

list2 = [1, 2, 3]

for x in list2:

list1.append(x)

print(list1)

3) list1 = ["a", "b" , "c"]

list2 = [1, 2, 3]

list1.extend(list2)

print(list1)

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

Tuple
Tuples are used to store multiple items in a single variable.

A tuple is a collection which is ordered and unchangeable.

Tuple items are ordered, unchangeable, and allow duplicate values.

Tuple items are indexed, the first item has index [0], the second item has index [1] etc.
Example:
1)thistuple = ("apple", "banana", "cherry")

print(thistuple)

2) thistuple = ("apple", "banana", "cherry", "apple", "cherry")

print(thistuple)

Length
thistuple = tuple(("apple", "banana", "cherry"))

print(len(thistuple))

Create Tuple With One Item


thistuple = ("apple",)

print(type(thistuple))

#NOT a tuple

thistuple = ("apple")

print(type(thistuple))

Data Types
tuple1 = ("apple", "banana", "cherry")

tuple2 = (1, 5, 7, 9, 3)

tuple3 = (True, False, False)

print(tuple1)

print(tuple2)

print(tuple3)

type()
mytuple = ("apple", "banana", "cherry")

print(type(mytuple))

tuple() Constructor
thistuple = tuple(("apple", "banana", "cherry"))

print(thistuple)

Access Tuple Items


thistuple = ("apple", "banana", "cherry")

print(thistuple[1])
Negative Indexing
thistuple = ("apple", "banana", "cherry")

print(thistuple[-1])

Range of Indexes
thistuple = ("apple", "banana", "cherry", "orange", "kiwi", "melon", "mango")

print(thistuple[2:5])

Range of Negative Indexes


thistuple = ("apple", "banana", "cherry", "orange", "kiwi", "melon", "mango")

print(thistuple[-4:-1])

Check if Item Exists


thistuple = ("apple", "banana", "cherry")

if "apple" in thistuple:

print("Yes, 'apple' is in the fruits tuple")

Change Tuple Values


x = ("apple", "banana", "cherry")

y = list(x)

y[1] = "kiwi"

x = tuple(y)

print(x)

Add Items
1)thistuple = ("apple", "banana", "cherry")

y = list(thistuple)

y.append("orange")

thistuple = tuple(y)

print(thistuple)

2) thistuple = ("apple", "banana", "cherry")

y = ("orange",)

thistuple += y

print(thistuple)
Remove Items
thistuple = ("apple", "banana", "cherry")

y = list(thistuple)

y.remove("apple")

thistuple = tuple(y)

print(thistuple)

Unpacking a Tuple
1)fruits = ("apple", "banana", "cherry")

print(fruits)

2) fruits = ("apple", "banana", "cherry")

(green, yellow, red) = fruits

print(green)

print(yellow)

print(red)

Using Asterisk*
1)fruits = ("apple", "banana", "cherry", "strawberry", "raspberry")

(green, yellow, *red) = fruits

print(green)

print(yellow)

print(red)

2) fruits = ("apple", "mango", "papaya", "pineapple", "cherry")

(green, *tropic, red) = fruits

print(green)

print(tropic)

print(red)
Loop Through a Tuple
thistuple = ("apple", "banana", "cherry")

for x in thistuple:

print(x)

Loop Through the Index Numbers


thistuple = ("apple", "banana", "cherry")

for i in range(len(thistuple)):

print(thistuple[i])

Using a While Loop


thistuple = ("apple", "banana", "cherry")

i=0

while i < len(thistuple):

print(thistuple[i])

i=i+1

Join Two Tuples


tuple1 = ("a", "b", "c")

tuple2 = (1, 2, 3)

tuple3 = tuple1 + tuple2

print(tuple3)

Multiply Tuples
fruits = ("apple", "banana", "cherry")

mytuple = fruits * 2

print(mytuple)
Tuple Methods
Method Description

count() Returns the number of times a specified value occurs in a tuple

index() Searches the tuple for a specified value and returns the

position of where it was found

Set
Sets are used to store multiple items in a single variable.

A set is a collection which is unordered, unchangeable*, and unindexed.

Example:
ple: thisset = {"apple", "banana", "cherry"}

print(thisset)

Duplicates Not Allowed


1)thisset = {"apple", "banana", "cherry", "apple"}

print(thisset)

2) thisset = {"apple", "banana", "cherry", True, 1, 2}

print(thisset)

3) thisset = {"apple", "banana", "cherry", False, True, 0}

print(thisset)

Length
thisset = {"apple", "banana", "cherry"}

print(len(thisset))
Data Types
1) set1 = {"apple", "banana", "cherry"}

set2 = {1, 5, 7, 9, 3}

set3 = {True, False, False}

print(set1)

print(set2)

print(set3)

2) set1 = {"abc", 34, True, 40, "male"}

print(set1)

type()
myset = {"apple", "banana", "cherry"}

print(type(myset))

set() Constructor
thisset = set(("apple", "banana", "cherry"))

print(thisset)

Access Items
1)thisset = {"apple", "banana", "cherry"}

for x in thisset:

print(x)

2) thisset = {"apple", "banana", "cherry"}

print("banana" in thisset)

3) thisset = {"apple", "banana", "cherry"}

print("banana" not in thisset)


Add Items
thisset = {"apple", "banana", "cherry"}

thisset.add("orange")

print(thisset)

Add Sets
thisset = {"apple", "banana", "cherry"}

tropical = {"pineapple", "mango", "papaya"}

thisset.update(tropical)

print(thisset)

Iterable
thisset = {"apple", "banana", "cherry"}

mylist = ["kiwi", "orange"]

thisset.update(mylist)

print(thisset)

Remove Item
1)thisset = {"apple", "banana", "cherry"}

thisset.remove("banana")

print(thisset)

2) thisset = {"apple", "banana", "cherry"}

thisset.discard("banana")

print(thisset)

3) thisset = {"apple", "banana", "cherry"}

x = thisset.pop()

print(x) #removed item

print(thisset) #the set after removal


4) thisset = {"apple", "banana", "cherry"}

thisset.clear()

print(thisset)

Loop Items
thisset = {"apple", "banana", "cherry"}

for x in thisset:

print(x)

Join Sets
I) set1 = {"a", "b", "c"}

set2 = {1, 2, 3}

set3 = set1.union(set2)

print(set3)

II) set1 = {"a", "b", "c"}

set2 = {1, 2, 3}

set3 = set1 | set2

print(set3)

Join Multiple Sets


1)set1 = {"a", "b", "c"}

set2 = {1, 2, 3}

set3 = {"John", "Elena"}

set4 = {"apple", "bananas", "cherry"}

myset = set1.union(set2, set3, set4)

print(myset)

2) set1 = {"a", "b", "c"}

set2 = {1, 2, 3}
set3 = {"John", "Elena"}

set4 = {"apple", "bananas", "cherry"}

myset = set1 | set2 | set3 |set4

print(myset)

Join a Set and a Tuple


x = {"a", "b", "c"}

y = (1, 2, 3)

z = x.union(y)

print(z)

Update
set1 = {"a", "b", "c"}

set2 = {1, 2, 3}

set1.update(set2)

print(set1)

Intersection
1) set1 = {"apple", "banana", "cherry"}

set2 = {"google", "microsoft", "apple"}

set3 = set1.intersection(set2)

print(set3)

2) set1 = {"apple", "banana" , "cherry"}

set2 = {"google", "microsoft", "apple"}

set3 = set1 & set2

print(set3)

3) set1 = {"apple", "banana", "cherry"}

set2 = {"google", "microsoft", "apple"}


set1.intersection_update(set2)

print(set1)

4) set1 = {"apple", 1, "banana", 0, "cherry"}

set2 = {False, "google", "microsoft", "apple", True}

set3 = set1.intersection(set2)

print(set3)

Difference
1) set1 = {"apple", "banana" , "cherry"}

set2 = {"google", "microsoft", "apple"}

set3 = set1.difference(set2)

print(set3)

2) set1 = {"apple", "banana" , "cherry"}

set2 = {"google", "microsoft", "apple"}

set3 = set1 - set2

print(set3)

3) set1 = {"apple", "banana" , "cherry"}

set2 = {"google", "microsoft", "apple"}

set1.difference_update(set2)

print(set1)

Symmetric Differences
1) set1 = {"apple", "banana" , "cherry"}

set2 = {"google", "microsoft", "apple"}

set3 = set1.symmetric_difference(set2)

print(set3)

2) set1 = {"apple", "banana", "cherry"}

set2 = {"google", "microsoft", "apple"}


set3 = set1 ^ set2

print(set3)

3) set1 = {"apple", "banana" , "cherry"}

set2 = {"google", "microsoft", "apple"}

set1.symmetric_difference_update(set2)

print(set1)

Method Shortcut Description

add() Adds an element to the set

clear() Removes all the elements from the set

copy() Returns a copy of the set

difference() - Returns a set containing the difference

between two or more sets

difference_update() -= Removes the items in this set that are also

included in another, specified set

discard() Remove the specified item

intersection() & Returns a set, that is the intersection of two

other sets

intersection_update() &= Removes the items in this set that are not
present in other, specified set(s)

isdisjoint() Returns whether two sets have a intersectio

not

issubset() <= Returns whether another set contains this s

not

< Returns whether all items in this set is

present in other, specified set(s)

issuperset() >= Returns whether this set contains another s

not

> Returns whether all items in other, specifie

(s) is present in this set

pop() Removes an element from the set

remove() Removes the specified element

symmetric_difference() ^ Returns a set with the symmetric difference

two sets

symmetric_difference_update() ^= Inserts the symmetric differences from this

and another
union() | Return a set containing the union of sets

update() |= Update the set with the union of this set an

others

Dictionary
Dictionaries are used to store data values in key:value pairs.

A dictionary is a collection which is ordered*, changeable and do not allow duplicates.

Example:
thisdict = {

"brand": "Ford",

"model": "Mustang",

"year": 1964

print(thisdict)

Dictionary Items
thisdict = {

"brand": "Ford",

"model": "Mustang",

"year": 1964

print(thisdict["brand"])

Duplicates Not Allowed


thisdict = {
"brand": "Ford",

"model": "Mustang",

"year": 1964,

"year": 2020

print(thisdict)

Length
thisdict = {

"brand": "Ford",

"model": "Mustang",

"year": 1964,

"year": 2020

print(len(thisdict))

Data Types
thisdict = {

"brand": "Ford",

"electric": False,

"year": 1964,

"colors": ["red", "white", "blue"]

print(thisdict)

type()
thisdict = {
"brand": "Ford",

"model": "Mustang",

"year": 1964

print(type(thisdict))

dict() Constructor
thisdict = dict(name = "John", age = 36, country = "Norway")

print(thisdict)

Accessing Items
1)thisdict = {

"brand": "Ford",

"model": "Mustang",

"year": 1964

x = thisdict["model"]

print(x)

2) thisdict = {

"brand": "Ford",

"model": "Mustang",

"year": 1964

x = thisdict.get("model")

print(x)

Get Keys
1)thisdict = {
"brand": "Ford",

"model": "Mustang",

"year": 1964

x = thisdict.keys()

print(x)

2) car = {

"brand": "Ford",

"model": "Mustang",

"year": 1964

x = car.keys()

print(x) #before the change

car["color"] = "white"

print(x) #after the change

Values
1) thisdict = {

"brand": "Ford",

"model": "Mustang",

"year": 1964

x = thisdict.values()

print(x)

2) car = {

"brand": "Ford",

"model": "Mustang",
"year": 1964

x = car.values()

print(x) #before the change

car["year"] = 2020

print(x) #after the change

3) car = {

"brand": "Ford",

"model": "Mustang",

"year": 1964

x = car.values()

print(x) #before the change

car["color"] = "red"

print(x) #after the change

Items
1) thisdict = {

"brand": "Ford",

"model": "Mustang",

"year": 1964

x = thisdict.items()

print(x)

2) car = {

"brand": "Ford",

"model": "Mustang",
"year": 1964

x = car.items()

print(x) #before the change

car["year"] = 2020

print(x) #after the change

3) car = {

"brand": "Ford",

"model": "Mustang",

"year": 1964

x = car.items()

print(x) #before the change

car["color"] = "red"

print(x) #after the change

Check if Key Exists


thisdict = {

"brand": "Ford",

"model": "Mustang",

"year": 1964

if "model" in thisdict:

print("Yes, 'model' is one of the keys in the thisdict dictionary")

Change Values
thisdict = {

"brand": "Ford",
"model": "Mustang",

"year": 1964

thisdict["year"] = 2018

print(thisdict)

Update
thisdict = {

"brand": "Ford",

"model": "Mustang",

"year": 1964

thisdict.update({"year": 2020})

print(thisdict)

Adding Items
thisdict = {

"brand": "Ford",

"model": "Mustang",

"year": 1964

thisdict["color"] = "red"

print(thisdict)

Update
thisdict = {

"brand": "Ford",

"model": "Mustang",
"year": 1964

thisdict.update({"color": "red"})

print(thisdict)

Removing Items
1)thisdict = {

"brand": "Ford",

"model": "Mustang",

"year": 1964

thisdict.pop("model")

print(thisdict)

2) thisdict = {

"brand": "Ford",

"model": "Mustang",

"year": 1964

thisdict.popitem()

print(thisdict)

3) thisdict = {

"brand": "Ford",

"model": "Mustang",

"year": 1964

del thisdict["model"]

print(thisdict)
4) thisdict = {

"brand": "Ford",

"model": "Mustang",

"year": 1964

thisdict.clear()

print(thisdict)

Loop Through a Dictionary


1) thisdict = {

"brand": "Ford",

"model": "Mustang",

"year": 1964

for x in thisdict:

print(x)

2) thisdict = {

"brand": "Ford",

"model": "Mustang",

"year": 1964

for x in thisdict:

print(thisdict[x])

3) thisdict = {

"brand": "Ford",

"model": "Mustang",

"year": 1964
}

for x in thisdict.values():

print(x)

4) thisdict = {

"brand": "Ford",

"model": "Mustang",

"year": 1964

for x in thisdict.keys():

print(x)

5) thisdict = {

"brand": "Ford",

"model": "Mustang",

"year": 1964

for x, y in thisdict.items():

print(x, y)

Copy a Dictionary
1)thisdict = {

"brand": "Ford",

"model": "Mustang",

"year": 1964

mydict = thisdict.copy()

print(mydict)

2) thisdict = {
"brand": "Ford",

"model": "Mustang",

"year": 1964

mydict = dict(thisdict)

print(mydict)

Nested Dictionaries
1)myfamily = {

"child1" : {

"name" : "Emil",

"year" : 2004

},

"child2" : {

"name" : "Tobias",

"year" : 2007

},

"child3" : {

"name" : "Linus",

"year" : 2011

print(myfamily)

2) myfamily = {

"child1" : {

"name" : "Emil",

"year" : 2004
},

"child2" : {

"name" : "Tobias",

"year" : 2007

},

"child3" : {

"name" : "Linus",

"year" : 2011

print(myfamily["child2"]["name"])

3) myfamily = {

"child1" : {

"name" : "Emil",

"year" : 2004

},

"child2" : {

"name" : "Tobias",

"year" : 2007

},

"child3" : {

"name" : "Linus",

"year" : 2011

for x, obj in myfamily.items():

print(x)
for y in obj:

print(y + ':', obj[y])

Method Description

clear() Removes all the elements from the dictionary

copy() Returns a copy of the dictionary

fromkeys() Returns a dictionary with the specified keys and value

get() Returns the value of the specified key

items() Returns a list containing a tuple for each key value pair

keys() Returns a list containing the dictionary's keys

pop() Removes the element with the specified key

popitem() Removes the last inserted key-value pair

setdefault() Returns the value of the specified key. If the key does not exist: insert the

key, with the specified value

update() Updates the dictionary with the specified key-value pairs

values() Returns a list of all the values in the dictionary


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

Example
if :
a = 33

b = 200

if b > a:

print("b is greater than a")

Elif:
a = 33

b = 33

if b > a:

print("b is greater than a")

elif a == b:

print("a and b are equal")

Else
1)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")

2) a = 200
b = 33

if b > a:

print("b is greater than a")

else:

print("b is not greater than a")

Short Hand If
a = 200

b = 33

if a > b: print("a is greater than b")

Short Hand If ... Else


a=2

b = 330

print("A") if a > b else print("B")

And
a = 200

b = 33

c = 500

if a > b and c > a:

print("Both conditions are True")

Or
a = 200

b = 33

c = 500

if a > b or a > c:

print("At least one of the conditions is True")

Not
a = 33

b = 200

if not a > b:
print("a is NOT greater than b")

Nested If
x = 41

if x > 10:

print("Above ten,")

if x > 20:

print("and also above 20!")

else:

print("but not above 20.")

The pass Statement


if statements cannot be empty, but if you for some reason have an if statement with no
content, put in the pass statement to avoid getting an error.

a = 33

b = 200

if b > a:

pass

# having an empty if statement like this, would raise an error without the pass statement

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.

i=1

while i < 6:

print(i)

i += 1

The break Statement


i=1
while i < 6:

print(i)

if (i == 3):

break

i += 1

The continue Statement


i=0

while i < 6:

i += 1

if i == 3:

continue

print(i)

# Note that number 3 is missing in the result

The else Statement


i=1

while i < 6:

print(i)

i += 1

else:

print("i is no longer less than 6")

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 languages, and works more like an
iterator method as found in other object-orientated programming languages.

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

for x in fruits:

print(x)

Looping Through a String


for x in "banana":

print(x)
The break Statement
1)fruits = ["apple", "banana", "cherry"]

for x in fruits:

print(x)

if x == "banana":

break

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

for x in fruits:

if x == "banana":

break

print(x)

The continue Statement


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

for x in fruits:

if x == "banana":

continue

print(x)

The range() Function


1)for x in range(6):

print(x)

2) for x in range(2, 6):

print(x)

3) for x in range(2, 30, 3):

print(x)

Else in For Loop


1)for x in range(6):

print(x)

else:

print("Finally finished!")

2)for x in range(6):

if x == 3: break

print(x)
else:

print("Finally finished!")

#If the loop breaks, the else block is not executed.

Nested Loops
adj = ["red", "big", "tasty"]

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

for x in adj:

for y in fruits:

print(x, y)

The pass Statement


for x in [0, 1, 2]:

pass

PYTHON FUNCTIONS
A function is a block of code which only runs when it is called.

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

my_function()

2) Arguments
def my_function(fname):
print(fname + " Refsnes")

my_function("Emil")
my_function("Tobias")
my_function("Linus")

3) Number of Arguments
def my_function(fname, lname):
print(fname + " " + lname)
my_function("Emil", "Refsnes")

4) Arbitrary Arguments, *args


def my_function(*kids):
print("The youngest child is " + kids[2])

my_function("Emil", "Tobias", "Linus")

5) Keyword Arguments
def my_function(child3, child2, child1):
print("The youngest child is " + child3)

my_function(child1 = "Emil", child2 = "Tobias", child3 = "Linus")

6) Arbitrary Keyword Arguments, **kwargs


def my_function(**kid):
print("His last name is " + kid["lname"])

my_function(fname = "Tobias", lname = "Refsnes")

7) Default Parameter Value


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

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

8) Passing a List as an Argument


def my_function(food):
for x in food:
print(x)

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

my_function(fruits)
9) Return Values
def my_function(x):
return 5 * x

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

10) The pass Statement


def myfunction():

pass

11) Positional-Only Arguments


def my_function(x, /):

print(x)

my_function(3)

12) Keyword-Only Arguments


def my_function(*, x):

print(x)

my_function(x = 3)

13) Combine Positional-Only and Keyword-Only


def my_function(a, b, /, *, c, d):

print(a + b + c + d)

my_function(5, 6, c = 7, d = 8)

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.

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 LAMBDA
A lambda function is a small anonymous function.

A lambda function can take any number of arguments, but can only have one
expression.

Example:
1) x = lambda a: a + 10
print(x(5))
2) x = lambda a, b: a * b
print(x(5, 6))
3) x = lambda a, b, c: a + b + c
print(x(5, 6, 2))

Why Use Lambda Functions?


The power of lambda is better shown when you use them as an anonymous function
inside another function.

Example:
1) def myfunc(n):
return lambda a : a * n

mydoubler = myfunc(2)

print(mydoubler(11))
2) def myfunc(n):
return lambda a : a * n

mytripler = myfunc(3)
print(mytripler(11))
3) def myfunc(n):
return lambda a : a * n

mydoubler = myfunc(2)
mytripler = myfunc(3)

print(mydoubler(11))
print(mytripler(11))

PYTHON ARRAYS
What is an Array?
An array is a special variable, which can hold more than one value at a time.

If you have a list of items (a list of car names, for example), storing the cars in single
variables could look like this:

car1 = "Ford
car2="Volvo"
car3 = "BMW"
Example:
1) cars = ["Ford", "Volvo", "BMW"]

x = cars[0]

print(x)
2) cars = ["Ford", "Volvo", "BMW"]

cars[0] = "Toyota"

print(cars)

3) The Length of an Array


cars = ["Ford", "Volvo", "BMW"]

x = len(cars)
print(x)

4) Looping Array Elements


cars = ["Ford", "Volvo", "BMW"]

for x in cars:

print(x)

5) Adding Array Elements


cars = ["Ford", "Volvo", "BMW"]

cars.append("Honda")

print(cars)

6)Removing Array Elements


i)cars = ["Ford", "Volvo", "BMW"]

cars.pop(1)

print(cars)

ii)cars = ["Ford", "Volvo", "BMW"]

cars.remove("Volvo")

print(cars)

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

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 first item with the specified value

reverse() Reverses the order of the list

sort() Sorts the list

Python Classes/Objects
Python is an object oriented programming language.

Example:

1)Create a Class
class MyClass:

x=5

print(MyClass)
2) Create Object
class MyClass:

x=5

p1 = MyClass()

print(p1.x)

3) The __init__() Function


class Person:

def __init__(self, name, age):

self.name = name

self.age = age

p1 = Person("John", 36)

print(p1.name)

print(p1.age)

4) The __str__() Function


class Person:

def __init__(self, name, age):

self.name = name

self.age = age

p1 = Person("John", 36)

print(p1)

5) Object Methods
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()

6) The self Parameter


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()

7) Delete Object Properties


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)

del p1.age

print(p1.age)

8) The pass Statement


class Person:

pass
Python Inheritance
Inheritance allows us to define a class that inherits all the methods and properties from
another class.

Parent class is the class being inherited from, also called base class.

Child class is the class that inherits from another class, also called derived class.

Example:

1) Create a Parent Class


class Person:

def __init__(self, fname, lname):

self.firstname = fname

self.lastname = lname

def printname(self):

print(self.firstname, self.lastname)

#Use the Person class to create an object, and then execute the printname method:

x = Person("John", "Doe")

x.printname()

2) Create a Child Class


class Person:

def __init__(self, fname, lname):

self.firstname = fname

self.lastname = lname

def printname(self):

print(self.firstname, self.lastname)

class Student(Person):

pass

x = Student("Mike", "Olsen")
x.printname()

3) Add the __init__() Function


class Person:

def __init__(self, fname, lname):

self.firstname = fname

self.lastname = lname

def printname(self):

print(self.firstname, self.lastname)

class Student(Person):

def __init__(self, fname, lname):

Person.__init__(self, fname, lname)

x = Student("Mike", "Olsen")

x.printname()

4) Use the super() Function


class Person:

def __init__(self, fname, lname):

self.firstname = fname

self.lastname = lname

def printname(self):

print(self.firstname, self.lastname)

class Student(Person):

def __init__(self, fname, lname):

super().__init__(fname, lname)

x = Student("Mike", "Olsen")

x.printname()

5) Add Properties
class Person:
def __init__(self, fname, lname):

self.firstname = fname

self.lastname = lname

def printname(self):

print(self.firstname, self.lastname)

class Student(Person):

def __init__(self, fname, lname):

super().__init__(fname, lname)

self.graduationyear = 2019

x = Student("Mike", "Olsen")

print(x.graduationyear)

6) Add Methods
class Person:

def __init__(self, fname, lname):

self.firstname = fname

self.lastname = lname

def printname(self):

print(self.firstname, self.lastname)

class Student(Person):

def __init__(self, fname, lname, year):

super().__init__(fname, lname)

self.graduationyear = year

def welcome(self):

print("Welcome", self.firstname, self.lastname, "to the class of", self.graduationyear)

x = Student("Mike", "Olsen", 2019)

x.welcome()
Python Iterators
An iterator is an object that contains a countable number of values.

An iterator is an object that can be iterated upon, meaning that you can traverse through
all the values.

Example:

1) mytuple = ("apple", "banana", "cherry")

myit = iter(mytuple)

print(next(myit))

print(next(myit))

print(next(myit))

2) mystr = "banana"

myit = iter(mystr)

print(next(myit))

print(next(myit))

print(next(myit))

print(next(myit))

print(next(myit))

print(next(myit))

3) Looping Through an Iterator


mytuple = ("apple", "banana", "cherry")

for x in mytuple:

print(x)

4) Create an Iterator
class MyNumbers:

def __iter__(self):

self.a = 1

return self
def __next__(self):

x = self.a

self.a += 1

return x

myclass = MyNumbers()

myiter = iter(myclass)

print(next(myiter))

print(next(myiter))

print(next(myiter))

print(next(myiter))

print(next(myiter))

5) StopIteration
class MyNumbers:

def __iter__(self):

self.a = 1

return self

def __next__(self):

if self.a <= 20:

x = self.a

self.a += 1

return x

else:

raise StopIteration

myclass = MyNumbers()

myiter = iter(myclass)

for x in myiter:

print(x)
PYTHON POLYMORPHISM
The word "polymorphism" means "many forms", and in programming it refers to
methods/functions/operators with the same name that can be executed on many
objects or classes.

Example:

1) String
x = "Hello World!"

print(len(x))

2) Tuple
mytuple = ("apple", "banana", "cherry")

print(len(mytuple))

3) Dictionary
thisdict = {

"brand": "Ford",

"model": "Mustang",

"year": 1964

print(len(thisdict))

4) Class Polymorphism
class Car:

def __init__(self, brand, model):

self.brand = brand

self.model = model

def move(self):

print("Drive!")

class Boat:

def __init__(self, brand, model):


self.brand = brand

self.model = model

def move(self):

print("Sail!")

class Plane:

def __init__(self, brand, model):

self.brand = brand

self.model = model

def move(self):

print("Fly!")

car1 = Car("Ford", "Mustang") #Create a Car class

boat1 = Boat("Ibiza", "Touring 20") #Create a Boat class

plane1 = Plane("Boeing", "747") #Create a Plane class

for x in (car1, boat1, plane1):

x.move()

5) Inheritance Class Polymorphism


class Vehicle:

def __init__(self, brand, model):

self.brand = brand

self.model = model

def move(self):

print("Move!")

class Car(Vehicle):

pass

class Boat(Vehicle):

def move(self):
print("Sail!")

class Plane(Vehicle):

def move(self):

print("Fly!")

car1 = Car("Ford", "Mustang") #Create a Car object

boat1 = Boat("Ibiza", "Touring 20") #Create a Boat object

plane1 = Plane("Boeing", "747") #Create a Plane object

for x in (car1, boat1, plane1):

print(x.brand)

print(x.model)

x.move()

PYTHON SCOPE
A variable is only available from inside the region it is created. This is called scope.

Local Scope
A variable created inside a function belongs to the local scope of that function, and can
only be used inside that function.

Example:
1)def myfunc():
x = 300
print(x)

myfunc()

2) Function Inside Function


def myfunc():
x = 300
def myinnerfunc():
print(x)
myinnerfunc()

myfunc()
3) Global Scope
A variable created in the main body of the Python code is a global variable and belongs to
the global scope.

x = 300

def myfunc():
print(x)

myfunc()

print(x)

4) Naming Variables
x = 300

def myfunc():
x = 200
print(x)

myfunc()

print(x)

5) Global Keyword
def myfunc():
global x
x = 300

myfunc()

print(x)

6) Nonlocal Keyword
The nonlocal keyword is used to work with variables inside nested functions.

def myfunc1():
x = "Jane"
def myfunc2():
nonlocal x
x = "hello"
myfunc2()
return x

print(myfunc1())

PYTHON MODULES
What is a Module?
Consider a module to be the same as a code library.

A file containing a set of functions you want to include in your application.

Create a Module
To create a module just save the code you want in a file with the file extension .py:

1)Save this code in a file named mymodule.py

def greeting(name):
print("Hello, " + name)

Use a Module
import mymodule

mymodule.greeting("Jonathan")

2)Variables in Module
Save this code in the file mymodule.py

person1 = {
"name": "John",
"age": 36,
"country": "Norway"
}

Import the module named mymodule, and access the person1 dictionary:
import mymodule

a = mymodule.person1["age"]
print(a)

Re-naming a Module
import mymodule as mx

a = mx.person1["age"]

print(a)

Python Dates
A date in Python is not a data type of its own, but we can import a module
named datetime to work with dates as date objects.

Example:

1) import datetime

x = datetime.datetime.now()

print(x)

2) import datetime

x = datetime.datetime.now()

print(x.year)

print(x.strftime("%A"))

3) import datetime

x = datetime.datetime(2020, 5, 17)

print(x)

4) import datetime

x = datetime.datetime(2018, 6, 1)

print(x.strftime("%B"))
Directive Description Example

%a Weekday, short version Wed

%A Weekday, full version Wednesday

%w Weekday as a number 0-6, 0 is Sunday 3

%d Day of month 01-31 31

%b Month name, short version Dec

%B Month name, full version December

%m Month as a number 01-12 12

%y Year, short version, without century 18

%Y Year, full version 2018

%H Hour 00-23 17

%I Hour 00-12 05

%p AM/PM PM
%M Minute 00-59 41

%S Second 00-59 08

%f Microsecond 000000-999999 548513

%z UTC offset +0100

%Z Timezone CST

%j Day number of year 001-366 365

%U Week number of year, Sunday as the first day 52


of week, 00-53

%W Week number of year, Monday as the first day 52


of week, 00-53

%c Local version of date and time Mon Dec 31

17:41:00 2018

%C Century 20

%x Local version of date 12/31/18

%X Local version of time 17:41:00


%% A % character %

%G ISO 8601 year 2018

%u ISO 8601 weekday (1-7) 1

%V ISO 8601 weeknumber (01-53) 01

PYTHON MATH
Python has a set of built-in math functions, including an extensive math module, that allows
you to perform mathematical tasks on numbers.
Example:
1) x = min(5, 10, 25)
y = max(5, 10, 25)

print(x)
print(y)
2) x = abs(-7.25)

print(x)
3) x = pow(4, 3)

print(x)
4) import math

x = math.sqrt(64)

print(x)
5) #Import math library
import math

#Round a number upward to its nearest integer


x = math.ceil(1.4)

#Round a number downward to its nearest integer


y = math.floor(1.4)

print(x)
print(y)
6) import math

x = math.pi

print(x)

PYTHON JSON
JSON is a syntax for storing and exchanging data.

JSON is text, written with JavaScript object notation.

Example:
1) import json

# some JSON:
x = '{ "name":"John", "age":30, "city":"New York"}'

# parse x:
y = json.loads(x)

# the result is a Python dictionary:


print(y["age"])
2) import json

# a Python object (dict):


x={
"name": "John",
"age": 30,
"city": "New York"
}

# convert into JSON:


y = json.dumps(x)

# the result is a JSON string:


print(y)
3) import json

print(json.dumps({"name": "John", "age": 30}))


print(json.dumps(["apple", "bananas"]))
print(json.dumps(("apple", "bananas")))
print(json.dumps("hello"))
print(json.dumps(42))
print(json.dumps(31.76))
print(json.dumps(True))
print(json.dumps(False))
print(json.dumps(None))
4) import json

x={
"name": "John",
"age": 30,
"married": True,
"divorced": False,
"children": ("Ann","Billy"),
"pets": None,
"cars": [
{"model": "BMW 230", "mpg": 27.5},
{"model": "Ford Edge", "mpg": 24.1}
]
}

# convert into JSON:


y = json.dumps(x)
# the result is a JSON string:
print(y)
5) import json

x={
"name": "John",
"age": 30,
"married": True,
"divorced": False,
"children": ("Ann","Billy"),
"pets": None,
"cars": [
{"model": "BMW 230", "mpg": 27.5},
{"model": "Ford Edge", "mpg": 24.1}
]
}

# use four indents to make it easier to read the result:


print(json.dumps(x, indent=4))
6) import json

x={
"name": "John",
"age": 30,
"married": True,
"divorced": False,
"children": ("Ann","Billy"),
"pets": None,
"cars": [
{"model": "BMW 230", "mpg": 27.5},
{"model": "Ford Edge", "mpg": 24.1}
]
}
# use . and a space to separate objects, and a space, a = and a space to separate keys
from their values:
print(json.dumps(x, indent=4, separators=(". ", " = ")))
7) import json

x={
"name": "John",
"age": 30,
"married": True,
"divorced": False,
"children": ("Ann","Billy"),
"pets": None,
"cars": [
{"model": "BMW 230", "mpg": 27.5},
{"model": "Ford Edge", "mpg": 24.1}
]
}

# sort the result alphabetically by keys:


print(json.dumps(x, indent=4, sort_keys=True))

PYTHON REGEX
A RegEx, or Regular Expression, is a sequence of characters that forms a search
pattern.

RegEx can be used to check if a string contains the specified search pattern.

RegEx Functions
Function Description

findall Returns a list containing all matches

search Returns a Match object if there is a match anywhere in the string


split Returns a list where the string has been split at each match

sub Replaces one or many matches with a string

Metacharacters
Metacharacters are characters with a special meaning:

Character Description Example

[] A set of characters "[a-m]"

\ Signals a special sequence (can also be used to escape "\d"

special characters)

. Any character (except newline character) "he..o"

^ Starts with "^hello"

$ Ends with "planet$"

* Zero or more occurrences "he.*o"

+ One or more occurrences "he.+o"

? Zero or one occurrences "he.?o"


{} Exactly the specified number of occurrences "he.{2}o"

| Either or "falls|stays

() Capture and group

Special Sequences
A special sequence is a \ followed by one of the characters in the list below, and has a
special meaning:

Character Description Example

\A Returns a match if the specified characters are at the beginning "\AThe"

of the string

\b Returns a match where the specified characters are at the r"\bain"


beginning or at the end of a word
(the "r" in the beginning is making sure that the string is being r"ain\b"
treated as a "raw string")

\B Returns a match where the specified characters are present,but r"\Bain"


NOT at the beginning (or at the end) of a word
(the "r" in the beginning is making sure that the string is being r"ain\B"
treated as a "raw string")

\d Returns a match where the string contains digits (numbers from 0- "\d"
9)

\D Returns a match where the string DOES NOT contain digits "\D"
\s Returns a match where the string contains a white space character "\s"

\S Returns a match where the string DOES NOT contain a white space "\S"
character

\w Returns a match where the string contains any word characters "\w"
(characters from a to Z, digits from 0-9, and the underscore _
character)

\W Returns a match where the string DOES NOT contain any word "\W"
characters

\Z Returns a match if the specified characters are at the end of the "Spain\Z"
string

Sets
A set is a set of characters inside a pair of square brackets [] with a special meaning:

Set Description

[arn] Returns a match where one of the specified characters ( a, r, or n) is present

[a-n] Returns a match for any lower case character, alphabetically between a and n

[^arn] Returns a match for any character EXCEPT a, r, and n

[0123] Returns a match where any of the specified digits ( 0, 1, 2, or 3) are present
[0-9] Returns a match for any digit between 0 and 9

[0-5][0-9] Returns a match for any two-digit numbers from 00 and 59

[a-zA-Z] Returns a match for any character alphabetically between a and z, lower case O
upper case

[+] In sets, +, *, ., |, (), $,{} has no special meaning, so [+] means: return a

match for any + character in the string

Example:

1) import re

#Return a list containing every occurrence of "ai":

txt = "The rain in Spain"

x = re.findall("ai", txt)

print(x)

2) import re

txt = "The rain in Spain"

#Check if "Portugal" is in the string:

x = re.findall("Portugal", txt)

print(x)

if (x):

print("Yes, there is at least one match!")

else:

print("No match")
3) import re

txt = "The rain in Spain"

x = re.search("\s", txt)

print("The first white-space character is located in position:", x.start())

4) import re

txt = "The rain in Spain"

x = re.search("Portugal", txt)

print(x)

5) import re

#Split the string at every white-space character:

txt = "The rain in Spain"

x = re.split("\s", txt)

print(x)

6) import re

#Split the string at the first white-space character:

txt = "The rain in Spain"

x = re.split("\s", txt, 1)

print(x)

7) import re

#Replace all white-space characters with the digit "9":

txt = "The rain in Spain"

x = re.sub("\s", "9", txt)

print(x)

8) import re

#Replace the first two occurrences of a white-space character with the digit 9:
txt = "The rain in Spain"

x = re.sub("\s", "9", txt, 2)

print(x)

9) import re

#The search() function returns a Match object:

txt = "The rain in Spain"

x = re.search("ai", txt)

print(x)

10) import re

#Search for an upper case "S" character in the beginning of a word, and print its position:

txt = "The rain in Spain"

x = re.search(r"\bS\w+", txt)

print(x.span())

11) import re

#The string property returns the search string:

txt = "The rain in Spain"

x = re.search(r"\bS\w+", txt)

print(x.string)

12) import re

#Search for an upper case "S" character in the beginning of a word, and print the word:

txt = "The rain in Spain"

x = re.search(r"\bS\w+", txt)

print(x.group())
PYTHON PIP
PIP is a package manager for Python packages, or modules if you like.

What is a Package?
A package contains all the files you need for a module.

Modules are Python code libraries you can include in your project.

Check PIP version:

C:\Users\Your Name\AppData\Local\Programs\Python\Python36-32\Scripts>pip --
version

Install PIP
If you do not have PIP installed, you can download and install it from this
page: https://pypi.org/project/pip/

Download a package named "camelcase":

C:\Users\Your Name\AppData\Local\Programs\Python\Python36-32\Scripts>pip
install camelcase

Uninstall the package named "camelcase":

C:\Users\Your Name\AppData\Local\Programs\Python\Python36-32\Scripts>pip
uninstall camelcase

List installed packages:

C:\Users\Your Name\AppData\Local\Programs\Python\Python36-32\Scripts>pip
list

Result:

Package Version
-----------------------
camelcase 0.2
mysql-connector 2.1.6
pip 18.1
pymongo 3.6.1
setuptools 39.0.1

Example:

import camelcase

c = camelcase.CamelCase()
txt = "lorem ipsum dolor sit amet"

print(c.hump(txt))

#This method capitalizes the first letter of each word.

PYTHON TRY EXCEPT


The try block lets you test a block of code for errors.

The except block lets you handle the error.

The else block lets you execute code when there is no error.

The finally block lets you execute code, regardless of the result of the try- and
except blocks.

Example:
1) #The try block will generate an error, because x is not defined:

try:
print(x)
except:
print("An exception occurred")
2) #The try block will generate a NameError, because x is not defined:

try:
print(x)
except NameError:
print("Variable x is not defined")
except:
print("Something else went wrong")
3) #The try block does not raise any errors, so the else block is executed:

try:
print("Hello")
except:
print("Something went wrong")
else:
print("Nothing went wrong")
4) #The finally block gets executed no matter if the try block raises any errors or not:

try:
print(x)
except:
print("Something went wrong")
finally:
print("The 'try except' is finished")
5) #The try block will raise an error when trying to write to a read-only file:

try:
f = open("demofile.txt")
try:
f.write("Lorum Ipsum")
except:
print("Something went wrong when writing to the file")
finally:
f.close()
except:
print("Something went wrong when opening the file")

User Input
Python allows for user input.

That means we are able to ask the user for input.

The method is a bit different in Python 3.6 than Python 2.7.

Python 3.6 uses the input() method.

Python 2.7 uses the raw_input() method.

Example:
1) username = input("Enter username:")
print("Username is: " + username)
PYTHON FILE OPEN
File handling is an important part of any web application.

Python has several functions for creating, reading, updating, and deleting files.

File Handling
The key function for working with files in Python is the open() function.

"r" - Read - Default value. Opens a file for reading, error if the file does not exist

"a" - Append - Opens a file for appending, creates the file if it does not exist

"w" - Write - Opens a file for writing, creates the file if it does not exist

"x" - Create - Creates the specified file, returns an error if the file exists

"t" - Text - Default value. Text mode

"b" - Binary - Binary mode (e.g. images)

Write to an Existing File


To write to an existing file, you must add a parameter to the open() function:

"a" - Append - will append to the end of the file

"w" - Write - will overwrite any existing content

Create a File Example:


1) f = open("demofile2.txt", "a")
f.write("Now the file has more content!")
f.close()

#open and read the file after the appending:


f = open("demofile2.txt", "r")
print(f.read())

Read a File Example:


1) f = open("demofile2.txt", "r")
print(f.read())
2) f = open("demofile2.txt", "r")

print(f.readline())

Delete a File
1)import os

os.remove("demofile2.txt")

You might also like