Python
Python
What is Python?
Python is a popular programming language. It was created by Guido van Rossum, and released in 1991.
It is used for:
software development,
mathematics,
system scripting.
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 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 Variables
Variables:-
Creating Variables
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 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)
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
exampple:
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)
x, y, z = fruits
print(x)
print(y)
print(z)
output:-
apple
banana
cherry
Output Variables:-
example:-
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
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:
1)str
x = "Hello World"
#display x:
print(x)
print(type(x))
output:-
Hello World
<class 'str'>
2)int
x = 20
#display x:
print(x)
print(type(x))
output:-
20
<class 'int'>
3)float
x = 20.5
#display x:
print(x)
print(type(x))
output:-
20.5
<class 'float'>
4)complex
x = 1j
#display x:
print(x)
print(type(x))
output:-
1j
<class 'complex'>
5)list
#display x:
print(x)
print(type(x))
output:-
6)tuple
#display x:
print(x)
print(type(x))
output:-
<class 'tuple'>
7)range
x = range(6)
#display x:
print(x)
print(type(x))
output:
range(2, 6)
<class 'range'>
8)dict
#display x:
print(x)
print(type(x))
output:
{'name': 'John', 'age': 36}
<class 'dict'>
9)set
#display x:
print(x)
print(type(x))
output:
<class 'set'>
10)frozenset
#display x:
print(x)
print(type(x))
<class 'frozenset'>
11)bool
x = True
#display x:
print(x)
print(type(x))
output:
True
<class 'bool'>
12)bytes
x = b"Hello"
#display x:
print(x)
print(type(x))
output:
b'Hello'
<class 'bytes'>
13)bytearray
x = bytearray(5)
#display x:
print(x)
print(type(x))
output:
bytearray(b'\x00\x00\x00\x00\x00')
<class 'bytearray'>
14)memoryview
x = memoryview(bytes(5))
#display x:
print(x)
print(type(x))
output:
<memory at 0x006F8FA0>
<class 'memoryview'>
15)NoneType
x = None
#display x:
print(x)
print(type(x))
output:
None
<class 'NoneType'>
Python Numbers
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)
y = int(2.8)
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:-
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.
example:
print("Hello")
print('Hello')
output:
Hello
Hello
example:
a = "Hello"
print(a)
output:
Hello
Multiline Strings:-
example:
print(a)
output:
example:
a = "Hello, World!"
print(a[1])
output:
example:
for x in "banana":
print(x)
output:
String Length:-
Example:
a = "Hello, World!"
print(len(a))
output:13
Check String:-
print("free" in txt)
output:True
if "free" in txt:
output:
Check if NOT:-
output:True
example:
print(b[2:5])
output:llo
print(b[:5])
output:Hello
output:llo, World!
print(b[-5:-2])
output:orl
print(a.upper())
output:HELLO, WORLD!
print(a.lower())
output:hello, world!
print(a.strip())
output:Hello, World!
print(a.replace("H", "J"))
output:Jello, World!
b = a.split(",")
print(b)
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
1)age = 36
print(txt.format(age))
2)quantity = 3
itemno = 567
price = 49.95
3)quantity = 3
itemno = 567
price = 49.95
myorder = "I want to pay {2} dollars for {0} pieces of item {1}."
STRING METHOD:
Method Description
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
index() Searches the string for a specified value and returns the position of where it was found
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
islower() Returns True if all characters in the string are lower case
isupper() Returns True if all characters in the string are upper case
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
rpartition() Returns a tuple where the string is parted into three parts
rsplit() Splits the string at the specified separator, and returns a list
split() Splits the string at the specified separator, and returns a list
startswith() Returns true if the string starts with the specified value
swapcase() Swaps cases, lower case becomes upper case and vice versa
title() Converts the first character of each word to upper case
zfill() Fills the string with a specified number of 0 values at the beginning
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:-
Arithmetic operators
Assignment operators
Comparison operators
Logical operators
Identity operators
Membership operators
Bitwise 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
7) x = 15
y=2
print(x // y)
#the floor division // rounds the result down to the nearest whole number
= 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
:= 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)
== Equal x == y
!= Not equal 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)
and Returns True if both statements are true x < 5 and x < 10
Not Reverse the result, returns False if the not(x < 5 and x < 10)
result is true
Example:
1) x = 5
2) x = 5
3) x = 5
Example:
1) x = ["apple", "banana"]
y = ["apple", "banana"]
z=x
print(x is z)
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)
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
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
<< 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 indexed, the first item has index [0], the second item has index [1] etc.
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]
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])
print(thislist[-4:-1])
if "apple" in thislist:
thislist[1] = "blackcurrant"
print(thislist)
print(thislist)
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"]
thislist.extend(tropical)
print(thislist)
thislist.extend(thistuple)
print(thislist)
thislist.remove("banana")
print(thislist)
thislist.pop(1)
print(thislist)
del thislist[0]
print(thislist)
Clear the List
thislist = ["apple", "banana", "cherry"]
thislist.clear()
print(thislist)
for x in thislist:
print(x)
for i in range(len(thislist)):
print(thislist[i])
i=0
print(thislist[i])
i=i+1
List Comprehension
1)fruits = ["apple", "banana", "cherry", "kiwi", "mango"]
newlist = []
for x in fruits:
if "a" in x:
newlist.append(x)
print(newlist)
print(newlist)
print(newlist)
print(newlist)
Iterable
1)newlist = [x for x in range(10)]
print(newlist)
print(newlist)
Expression
1) fruits = ["apple", "banana", "cherry", "kiwi", "mango"]
print(newlist)
print(newlist)
print(newlist)
Sort List Alphanumerically
1)thislist = ["orange", "mango", "kiwi", "pineapple", "banana"]
thislist.sort()
print(thislist)
thislist.sort()
print(thislist)
Sort Descending
1)thislist = ["orange", "mango", "kiwi", "pineapple", "banana"]
thislist.sort(reverse = True)
print(thislist)
thislist.sort(reverse = True)
print(thislist)
Reverse Order
thislist = ["banana", "Orange", "Kiwi", "cherry"]
thislist.reverse()
print(thislist)
thislist.sort()
print(thislist)
thislist.sort(key = str.lower)
print(thislist)
Copy a List
1)thislist = ["apple", "banana", "cherry"]
mylist = thislist.copy()
print(mylist)
mylist = list(thislist)
print(mylist)
list2 = [1, 2, 3]
print(list3)
list2 = [1, 2, 3]
for x in list2:
list1.append(x)
print(list1)
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
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
Tuple
Tuples are used to store multiple items in a single variable.
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)
print(thistuple)
Length
thistuple = tuple(("apple", "banana", "cherry"))
print(len(thistuple))
print(type(thistuple))
#NOT a tuple
thistuple = ("apple")
print(type(thistuple))
Data Types
tuple1 = ("apple", "banana", "cherry")
tuple2 = (1, 5, 7, 9, 3)
print(tuple1)
print(tuple2)
print(tuple3)
type()
mytuple = ("apple", "banana", "cherry")
print(type(mytuple))
tuple() Constructor
thistuple = tuple(("apple", "banana", "cherry"))
print(thistuple)
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])
print(thistuple[-4:-1])
if "apple" in thistuple:
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)
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)
print(green)
print(yellow)
print(red)
Using Asterisk*
1)fruits = ("apple", "banana", "cherry", "strawberry", "raspberry")
print(green)
print(yellow)
print(red)
print(green)
print(tropic)
print(red)
Loop Through a Tuple
thistuple = ("apple", "banana", "cherry")
for x in thistuple:
print(x)
for i in range(len(thistuple)):
print(thistuple[i])
i=0
print(thistuple[i])
i=i+1
tuple2 = (1, 2, 3)
print(tuple3)
Multiply Tuples
fruits = ("apple", "banana", "cherry")
mytuple = fruits * 2
print(mytuple)
Tuple Methods
Method Description
index() Searches the tuple for a specified value and returns the
Set
Sets are used to store multiple items in a single variable.
Example:
ple: thisset = {"apple", "banana", "cherry"}
print(thisset)
print(thisset)
print(thisset)
print(thisset)
Length
thisset = {"apple", "banana", "cherry"}
print(len(thisset))
Data Types
1) set1 = {"apple", "banana", "cherry"}
set2 = {1, 5, 7, 9, 3}
print(set1)
print(set2)
print(set3)
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)
print("banana" in thisset)
thisset.add("orange")
print(thisset)
Add Sets
thisset = {"apple", "banana", "cherry"}
thisset.update(tropical)
print(thisset)
Iterable
thisset = {"apple", "banana", "cherry"}
thisset.update(mylist)
print(thisset)
Remove Item
1)thisset = {"apple", "banana", "cherry"}
thisset.remove("banana")
print(thisset)
thisset.discard("banana")
print(thisset)
x = thisset.pop()
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)
set2 = {1, 2, 3}
print(set3)
set2 = {1, 2, 3}
print(myset)
set2 = {1, 2, 3}
set3 = {"John", "Elena"}
print(myset)
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"}
set3 = set1.intersection(set2)
print(set3)
print(set3)
print(set1)
set3 = set1.intersection(set2)
print(set3)
Difference
1) set1 = {"apple", "banana" , "cherry"}
set3 = set1.difference(set2)
print(set3)
print(set3)
set1.difference_update(set2)
print(set1)
Symmetric Differences
1) set1 = {"apple", "banana" , "cherry"}
set3 = set1.symmetric_difference(set2)
print(set3)
print(set3)
set1.symmetric_difference_update(set2)
print(set1)
other sets
intersection_update() &= Removes the items in this set that are not
present in other, specified set(s)
not
not
not
two sets
and another
union() | Return a set containing the union of sets
others
Dictionary
Dictionaries are used to store data values in key:value pairs.
Example:
thisdict = {
"brand": "Ford",
"model": "Mustang",
"year": 1964
print(thisdict)
Dictionary Items
thisdict = {
"brand": "Ford",
"model": "Mustang",
"year": 1964
print(thisdict["brand"])
"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,
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()
car["color"] = "white"
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()
car["year"] = 2020
3) car = {
"brand": "Ford",
"model": "Mustang",
"year": 1964
x = car.values()
car["color"] = "red"
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()
car["year"] = 2020
3) car = {
"brand": "Ford",
"model": "Mustang",
"year": 1964
x = car.items()
car["color"] = "red"
"brand": "Ford",
"model": "Mustang",
"year": 1964
if "model" in thisdict:
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)
"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
print(x)
for y in obj:
Method Description
items() Returns a list containing a tuple for each key value pair
setdefault() Returns the value of the specified key. If the key does not exist: insert the
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:
Elif:
a = 33
b = 33
if b > a:
elif a == b:
Else
1)a = 200
b = 33
if b > a:
elif a == b:
else:
2) a = 200
b = 33
if b > a:
else:
Short Hand If
a = 200
b = 33
b = 330
And
a = 200
b = 33
c = 500
Or
a = 200
b = 33
c = 500
if a > b or a > c:
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:
else:
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
i=1
while i < 6:
print(i)
i += 1
print(i)
if (i == 3):
break
i += 1
while i < 6:
i += 1
if i == 3:
continue
print(i)
while i < 6:
print(i)
i += 1
else:
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.
for x in fruits:
print(x)
print(x)
The break Statement
1)fruits = ["apple", "banana", "cherry"]
for x in fruits:
print(x)
if x == "banana":
break
for x in fruits:
if x == "banana":
break
print(x)
for x in fruits:
if x == "banana":
continue
print(x)
print(x)
print(x)
print(x)
print(x)
else:
print("Finally finished!")
2)for x in range(6):
if x == 3: break
print(x)
else:
print("Finally finished!")
Nested Loops
adj = ["red", "big", "tasty"]
for x in adj:
for y in fruits:
print(x, y)
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")
5) Keyword Arguments
def my_function(child3, child2, child1):
print("The youngest child is " + child3)
my_function("Sweden")
my_function("India")
my_function()
my_function("Brazil")
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))
pass
print(x)
my_function(3)
print(x)
my_function(x = 3)
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.
Example:
def tri_recursion(k):
result = k + tri_recursion(k - 1)
print(result)
else:
result = 0
return result
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))
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)
x = len(cars)
print(x)
for x in cars:
print(x)
cars.append("Honda")
print(cars)
cars.pop(1)
print(cars)
cars.remove("Volvo")
print(cars)
Array Methods
Python has a set of built-in methods that you can use on lists/arrays.
Method Description
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
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)
self.name = name
self.age = age
p1 = Person("John", 36)
print(p1.name)
print(p1.age)
self.name = name
self.age = age
p1 = Person("John", 36)
print(p1)
5) Object Methods
class Person:
self.name = name
self.age = age
def myfunc(self):
p1.myfunc()
mysillyobject.name = name
mysillyobject.age = age
def myfunc(abc):
p1 = Person("John", 36)
p1.myfunc()
self.name = name
self.age = age
def myfunc(self):
p1 = Person("John", 36)
del p1.age
print(p1.age)
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:
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()
self.firstname = fname
self.lastname = lname
def printname(self):
print(self.firstname, self.lastname)
class Student(Person):
pass
x = Student("Mike", "Olsen")
x.printname()
self.firstname = fname
self.lastname = lname
def printname(self):
print(self.firstname, self.lastname)
class Student(Person):
x = Student("Mike", "Olsen")
x.printname()
self.firstname = fname
self.lastname = lname
def printname(self):
print(self.firstname, self.lastname)
class Student(Person):
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):
super().__init__(fname, lname)
self.graduationyear = 2019
x = Student("Mike", "Olsen")
print(x.graduationyear)
6) Add Methods
class Person:
self.firstname = fname
self.lastname = lname
def printname(self):
print(self.firstname, self.lastname)
class Student(Person):
super().__init__(fname, lname)
self.graduationyear = year
def welcome(self):
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:
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))
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):
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:
self.brand = brand
self.model = model
def move(self):
print("Drive!")
class Boat:
self.model = model
def move(self):
print("Sail!")
class Plane:
self.brand = brand
self.model = model
def move(self):
print("Fly!")
x.move()
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!")
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()
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.
Create a Module
To create a module just save the code you want in a file with the file extension .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
%H Hour 00-23 17
%I Hour 00-12 05
%p AM/PM PM
%M Minute 00-59 41
%S Second 00-59 08
%Z Timezone CST
17:41:00 2018
%C Century 20
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
print(x)
print(y)
6) import math
x = math.pi
print(x)
PYTHON JSON
JSON is a syntax for storing and exchanging data.
Example:
1) import json
# some JSON:
x = '{ "name":"John", "age":30, "city":"New York"}'
# parse x:
y = json.loads(x)
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}
]
}
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}
]
}
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}
]
}
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
Metacharacters
Metacharacters are characters with a special meaning:
special characters)
| Either or "falls|stays
Special Sequences
A special sequence is a \ followed by one of the characters in the list below, and has a
special meaning:
of the 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
[a-n] Returns a match for any lower case character, alphabetically between a 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
[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
Example:
1) import re
x = re.findall("ai", txt)
print(x)
2) import re
x = re.findall("Portugal", txt)
print(x)
if (x):
else:
print("No match")
3) import re
x = re.search("\s", txt)
4) import re
x = re.search("Portugal", txt)
print(x)
5) import re
x = re.split("\s", txt)
print(x)
6) import re
x = re.split("\s", txt, 1)
print(x)
7) import re
print(x)
8) import re
#Replace the first two occurrences of a white-space character with the digit 9:
txt = "The rain in Spain"
print(x)
9) import re
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:
x = re.search(r"\bS\w+", txt)
print(x.span())
11) import re
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:
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.
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/
C:\Users\Your Name\AppData\Local\Programs\Python\Python36-32\Scripts>pip
install camelcase
C:\Users\Your Name\AppData\Local\Programs\Python\Python36-32\Scripts>pip
uninstall camelcase
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))
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.
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
print(f.readline())
Delete a File
1)import os
os.remove("demofile2.txt")