Python Core

Help

In [ ]:
print(dir())
['In', 'Out', '_', '_10', '_11', '_12', '_18', '_19', '_20', '_21', '_22', '_23', '_24', '_25', '_26', '_30', '_35', '_36', '_37', '_38', '_39', '_40', '_41', '_45', '_46', '_47', '_48', '_49', '_5', '_6', '_7', '_8', '_9', '__', '___', '__builtin__', '__builtins__', '__doc__', '__loader__', '__name__', '__package__', '__spec__', '_dh', '_i', '_i1', '_i10', '_i11', '_i12', '_i13', '_i14', '_i15', '_i16', '_i17', '_i18', '_i19', '_i2', '_i20', '_i21', '_i22', '_i23', '_i24', '_i25', '_i26', '_i27', '_i28', '_i29', '_i3', '_i30', '_i31', '_i32', '_i33', '_i34', '_i35', '_i36', '_i37', '_i38', '_i39', '_i4', '_i40', '_i41', '_i42', '_i43', '_i44', '_i45', '_i46', '_i47', '_i48', '_i49', '_i5', '_i50', '_i51', '_i6', '_i7', '_i8', '_i9', '_ih', '_ii', '_iii', '_oh', '_sh', 'copied_list1', 'copy', 'exit', 'get_ipython', 'my_dict', 'my_dict0', 'my_dict1', 'my_dict2', 'my_dict3', 'my_dict4', 'my_frozenset1', 'my_list1', 'my_list2', 'my_list3', 'my_list4', 'my_list5', 'my_list6', 'my_list7', 'my_set1', 'my_set2', 'my_test2', 'my_text1', 'my_text2', 'my_text3', 'my_text4', 'my_text5', 'my_tuple1', 'my_tuple2', 'quit']
In [ ]:
print(help(print))
Help on built-in function print in module builtins:

print(...)
    print(value, ..., sep=' ', end='\n', file=sys.stdout, flush=False)
    
    Prints the values to a stream, or to sys.stdout by default.
    Optional keyword arguments:
    file:  a file-like object (stream); defaults to the current sys.stdout.
    sep:   string inserted between values, default a space.
    end:   string appended after the last value, default a newline.
    flush: whether to forcibly flush the stream.

None

Number

In [ ]:
# intergal 

num = 3
print(type(num)) 
<class 'int'>
In [ ]:
# Float with decimal

num = 3.14
print(type(num)) 
<class 'float'>
In [ ]:
# Calculation

print(3 + 2)     # Plus
print(3 - 2)     # Minus
print(3 * 2)     # Multiply
print(3 / 2)     # Division
print(3 // 2)    # Floor Division
print(3 ** 2)    # Exponents
print(3 % 2)     # Modulus
print(3 * (2 + 1))
5
1
6
1.5
1
9
1
9
In [ ]:
# Calculation

num = 1

num = num + 1
print(num)

num += 2
print(num)

print(abs(-3))
print(round(4.555))
print(round(4.555,1))
2
4
3
5
4.6
In [ ]:
# Operation 

a = 3
b = 2
print(a == b)
print(a != b)
print(a > b)
print(a < b)
print(a >= b)
print(a <= b)
False
True
True
False
True
False
In [ ]:
a = '100'
b = '200'
print(a+b)
type(a)
100200
Out[ ]:
str
In [ ]:
a = '100'
b = '200'
a = int(a)
b = int(b)
print(a+b)
type(a)
300
Out[ ]:
int
In [ ]:
 

String

In [ ]:
# Create String
# String are built  either single, double or triple quotes

my_text1 = 'This is a string'
my_text2 = "This is a string"
my_text3 = '''This is a multi-line strings.'''
my_text4 = r"This is a string \t test"        # string is interpreted as it is without interpreting the special character
my_text5 = "This is a string \t test"
In [ ]:
# Slice strings

my_text1 = 'This is a string'

print(my_text1[0])        # return scharacter from index
print(my_text1[-1])       # return last character
print(my_text1[2:4])      # return character from start to end index
T
g
is
In [ ]:
# Formatter

print("Value is %s" % "A")                       # % produce formated value
print("Value is %s %s" % ("A", "B"))             # % proudct two formated values
print("Value is {a} and {b}". format(a=1, b =2)) # {} a string with argument
Value is A
Value is A B
Value is 1 and 2
In [ ]:
# Operators

my_text1 = 'This is a string'

my_text1 + "1"       # cat1
print(my_text1)

my_test2 = my_text1 * 2         # catcat
print(my_test2)

print(my_text1.count('i'))  # countspecific charactor

len(my_text1)        # count all charactors
This is a string
This is a stringThis is a string
3
Out[ ]:
16
In [ ]:
# Check type

print("1".isdigit())        # Is the string made of digit only?
print("A".isalpha())        # Is the string made of alphabet only?
print("A".isupper())        # Is the string made of upper case only?
print("a".islower())        # Is the string made of lower case only?
print("Is".istitle())       # Is the string start with capital letter?
True
True
True
True
True
In [ ]:
# modifiy string

my_text1 = 'This is a TEST String'

print(my_text1.title())        # 'This Is A Test String'
print(my_text1.capitalize())   # 'This is a test string'
print(my_text1.upper())        # 'THIS IS A TEST STRING'
print(my_text1.lower())        # 'this is a test string'
print(my_text1.swapcase())     # 'tHIS IS A test sTRING'
print(my_text1.center(30))     # '    This is a TEST String     '
This Is A Test String
This is a test string
THIS IS A TEST STRING
this is a test string
tHIS IS A test sTRING
    This is a TEST String     
In [ ]:
# modifiy string

my_text1 = 'This is a TEST String'

print(my_text1.ljust(30))      # 'This is a TEST String         '
print(my_text1.rjust(30))      # '         This is a TEST String'
print(my_text1.rjust(30, '-')) # '---------This is a TEST String'
print(my_text1.zfill(30))      # '000000000This is a TEST String'
This is a TEST String         
         This is a TEST String
---------This is a TEST String
000000000This is a TEST String
In [ ]:
# modifiy string

my_text1 = "  This is a TEST String  "

print(my_text1.strip())        # 'This Is A Test String'
print(my_text1.rstrip())       # '  This Is A Test String'
print(my_text1.lstrip())       # 'This Is A Test String  '
print(my_text1.lstrip())       # 'This Is A Test String'
This is a TEST String
  This is a TEST String
This is a TEST String  
This is a TEST String  
In [ ]:
# replace()  'This is a my String'

my_text1 = "This is a TEST String"

my_text2 = my_text1.replace('TEST', 'my') 
my_text2
Out[ ]:
'This is a my String'
In [ ]:
# partion()  ('Th', 'is', ' is a TEST String')

my_text1 = "This is a TEST String"

my_text2 = my_text1.partition('is')
my_text2
Out[ ]:
('Th', 'is', ' is a TEST String')
In [ ]:
# rpartion() ('This ', 'is', ' a TEST String')

my_text1 = "This is a TEST String"

my_text2 = my_text1.rpartition('is')
my_text2
Out[ ]:
('This ', 'is', ' a TEST String')
In [ ]:
# split() ['This', 'is', 'a', 'TEST', 'String']

my_text1 = "This is a TEST String"

my_text2 = my_text1.split(' ') 
my_text2
Out[ ]:
['This', 'is', 'a', 'TEST', 'String']
In [ ]:
# Join()

' '.join(['Good', 'Night'])        # 'Good Night'
Out[ ]:
'Good Night'
In [ ]:
# endswith() may provide optional start and end indices

my_text1 = "This is a TEST String"

my_text1.endswith('ing')
Out[ ]:
True
In [ ]:
# startswith() may provide start and end indices

my_text1 = "This is a TEST String"

my_text1.startswith('This')
Out[ ]:
True
In [ ]:
# find() 

my_text1 = "This is a TEST String"

print(my_text1.find('is'))             # returns start index of 'is' first occurence
print(my_text1.find('is', 4))         # starting at index 4, returns start index of 'is' first occurence
print(my_text1.rfind('is'))           # returns start index of 'is' last occurence
print(my_text1.index('is'))           # like find but raises error when substring is not found
print(my_text1.rindex('is'))          # like rfind but raises error when substring is not found
2
5
5
2
5

Lists

  • Lists are enclosed in brackets.
  • Lists can contain any type of objects.
  • Lists are mutables (Can edit data)
In [ ]:
# Create list

my_list1 = [1, 2, 3, 4, 5]
my_list2 = ['one', 'two', 'three', 'two']
my_list3 = [1, 'two', 'three']
my_list4 = list(range(1,10))
my_list5 = [1, 3 ,2, 4]
my_list6 = [1, 2 ,3, 4]
my_list7 = [1, 2 ,[3, 4]]       # nested list
In [ ]:
# Copy
import copy

my_list1 = [1, 2, 3, 4, 5]

copied_list1 = copy.copy(my_list1)      # shallow copy - nested objects will not be copied
copied_list1 = copy.deepcopy(my_list1)  # deep copy - nested objects will be copied
In [ ]:
# Search element

my_list1 = ['one', 'two', 'three', 'two']

print(my_list1.index('two'))           # index() returns the index of the first occurence.
print(my_list1.index('two', 2))        # index() returns the index of the second occurence.
1
3
In [ ]:
# Slicing

my_list1 = [1, 2, 3, 4, 5]

print(my_list1[1])      # [] return an object from index
print(my_list1[:])      # return all objects in list
print(my_list1[1:])     # return index object to last object
print(my_list1[:1])     # return first object to index
print(my_list1[1:2])    # return index object to index
2
[1, 2, 3, 4, 5]
[2, 3, 4, 5]
[1]
[2]
In [ ]:
# edit:  append() appends object to the end of list

my_list1 = [1, 2, 3, 4, 5]

my_list1.append(6)
my_list1
Out[ ]:
[1, 2, 3, 4, 5, 6]
In [ ]:
# edit: extend() append list to the end of list

my_list1 = [1, 2, 3, 4, 5]
my_list2 = [5, 6]

my_list1.extend(my_list2)
my_list1
Out[ ]:
[1, 2, 3, 4, 5, 5, 6]
In [ ]:
# edit: insert() insert an object before the index provided

my_list1 = [1, 2, 3, 4, 5]

my_list1.insert(2, 'four')
my_list1
Out[ ]:
[1, 2, 'four', 3, 4, 5]
In [ ]:
# edit: remove() remove the first occurence of an element

my_list1 = [1, 2, 3, 4, 5]

my_list1.remove(3)
my_list1
Out[ ]:
[1, 2, 4, 5]
In [ ]:
# edit: pop() remove the last element of a list

my_list1 = [1, 2, 3, 4, 5]

my_list1.pop()
my_list1
Out[ ]:
[1, 2, 3, 4]
In [ ]:
# edit: sort() performs an in-place ascending sorting

my_list1 = [1, 3, 2, 2, 5]

my_list1.sort()
my_list1
Out[ ]:
[1, 2, 2, 3, 5]
In [ ]:
# edit: sort() performs an in-place descending sorting

my_list1 = [1, 3, 2, 2, 5]

my_list1.sort(reverse=True)
my_list1
Out[ ]:
[5, 3, 2, 2, 1]
In [ ]:
# edit: reverse() reverse the element in-place

my_list1 = [1, 3, 2, 2, 5]

my_list1.reverse()
my_list1
Out[ ]:
[5, 2, 2, 3, 1]
In [ ]:
# calculation

my_list1 = [1, 3, 2, 2, 5]

print(my_list1.count(2))                               # count() count the number of element

print(len(my_list1))                                   # len() count all elements in list

my_list1 += [1]                                        # append object to the end of list
print(my_list1)

my_list2 = my_list1 * 2                                # extend list 2 times
print(my_list2)

my_list2 = [x + 1 for x in my_list1]                   # add 1 in all elements in list
print(my_list2)
2
5
[1, 3, 2, 2, 5, 1]
[1, 3, 2, 2, 5, 1, 1, 3, 2, 2, 5, 1]
[2, 4, 3, 3, 6, 2]
In [ ]:
# Calculation

list1 = [1, 5, 6, 3, 2, 1]
print(min(list1))
print(max(list1))
print(sum(list1))
1
6
18
In [ ]:
# Filtering 

my_list1 = [1, 3, 2, 2, 5]

my_list2 = [i for i in my_list1 if i > 2]      # get element more than 2 
print(my_list2)

my_list2 = [i for i in my_list1 if i % 2 == 0] # get event number list
print(my_list2)
[3, 5]
[2, 2]
In [ ]:
# Condition

list1 = ['a', 'b', 'c','d']
print('b' in list1)
True
In [ ]:
# Condtion

list1 = ['a', 'b', 'c','d']
for item in list1:
    print(item)
a
b
c
d
In [ ]:
# Condition

list1 = ['a', 'b', 'c','d']
for index, item in enumerate(list1, start=1):
    print(index, item)
1 a
2 b
3 c
4 d
In [ ]:
 

Tuples

  • Tuples are enclosed in parentheses.
  • Tuples can contain any type of objects.
  • Tuples are immutables. (cannot add or remove elements)
  • Tuples are faster than lists.
In [ ]:
my_tuple1 = (1, 'two', 'three')
my_tuple2 = 1, 'two'
In [ ]:
# Change data type
list1 = ['a', 'b', 'c','d']
tuple1 = tuple(list1)

Dictionary

  • Dictionaries are built with curly brackets.
  • Each item is a pair made of a key and a value.
  • Dictionaries are not sorted.
  • You can access to the list of keys or values independently.
In [ ]:
# Create Dictionary
my_dict0 = {}                                         # create blank dictionary
my_dict1 = {'a':1, 'b':2, 'c': 'three', 'c': 'three'}
my_dict2 = {}.fromkeys(['a', 'b', 'c'])               # create dictionary key
my_dict3 = {'a':1, 'b':2}
my_dict4 = {('x1', 'y1'): 1,
            ('x1', 'y2'):2}
In [ ]:
# print

dic1 = {'name':'Tom','age':25, 'courses':['Match','CompSci']}

print(dic1)
print(dic1.keys())
print(dic1.values())
print(dic1.items())
{'name': 'Tom', 'age': 25, 'courses': ['Match', 'CompSci']}
dict_keys(['name', 'age', 'courses'])
dict_values(['Tom', 25, ['Match', 'CompSci']])
dict_items([('name', 'Tom'), ('age', 25), ('courses', ['Match', 'CompSci'])])
In [ ]:
# print

dic1 = {'name':'Tom','age':25, 'courses':['Match','CompSci']}
for key in dic1:
    print(key)
name
age
courses
In [ ]:
# print

dic1 = {'name':'Tom','age':25, 'courses':['Match','CompSci']}
for key, value in dic1.items():
    print(key, value)
name Tom
age 25
courses ['Match', 'CompSci']
In [ ]:
# access value

my_dict1 = {'a':1, 'b':2, 'c': 'three', 'c': 'three'}

print(my_dict1['a'])                         # [] returns value from key
print(my_dict1.get('d', 0))                  # get() returns value from key or get an optional value, if the key is not found
print(my_dict1.items())                      # items() returns a list of items of the form (key, value)
1
0
dict_items([('a', 1), ('b', 2), ('c', 'three')])
In [ ]:
# edit: pop() return value and removes the corresponding value

my_dict1 = {'a':1, 'b':2, 'c': 'three', 'c': 'three'}

my_dict1.pop('a')
my_dict1
Out[ ]:
{'b': 2, 'c': 'three'}
In [ ]:
# edit: popitem() return value and removes the corresponding pair 

my_dict1 = {'a':1, 'b':2, 'c': 'three', 'c': 'three'}

my_dict2 = my_dict1.popitem()
my_dict2
Out[ ]:
('c', 'three')
In [ ]:
# edit: copy() copy dictionary (shallow copy)

my_dict1 = {'a':1, 'b':2, 'c': 'three', 'c': 'three'}

my_dict2 = my_dict1.copy()
my_dict2
Out[ ]:
{'a': 1, 'b': 2, 'c': 'three'}
In [ ]:
# edit: clear() Remove all its items

my_dict1 = {'a':1, 'b':2, 'c': 'three', 'c': 'three'}

my_dict1.clear()
my_dict1
Out[ ]:
{}
In [ ]:
# edit:  clear() Remove all its items

my_dict1 = {'a':1, 'b':2, 'c': 'three', 'c': 'three'}

my_dict1.clear()                 
my_dict1
Out[ ]:
{}
In [ ]:
# edit:  del removes the corresponding item

my_dict1 = {'a':1, 'b':2, 'c': 'three', 'c': 'three'}

del my_dict1['b']
my_dict1
Out[ ]:
{'a': 1, 'c': 'three'}
In [ ]:
# edit: update() update value from another dictionary

my_dict1 = {'a':1, 'b':2, 'c': 'three', 'c': 'three'}
my_dict2 = {'a':7}

my_dict1.update(my_dict2)
my_dict1
Out[ ]:
{'a': 7, 'b': 2, 'c': 'three'}
In [ ]:
# edit: assign value by key

my_dict1 = {'a':1, 'b':2, 'c': 'three', 'c': 'three'}

my_dict1['c'] = 7                     
my_dict1
Out[ ]:
{'a': 1, 'b': 2, 'c': 7}
In [ ]:
# edit: assign value by list key 

my_dict1 = {('x1', 'y1'):1, ('x1', 'y2'):2}

my_dict1[('x1', 'y1')] = 7
my_dict1
Out[ ]:
{('x1', 'y1'): 7, ('x1', 'y2'): 2}

Sets

In [ ]:
# Create Sets
# Sets are mutable unordered sequence of unique elements.
my_set1 = set([1, 2, 3])
my_set2 = set([3, 4, 5])
In [ ]:
# Union

my_set1 = set([1, 2, 3])
my_set2 = set([3, 4, 5])

my_set1 | my_set2       
my_set1.union(my_set2)
Out[ ]:
{1, 2, 3, 4, 5}
In [ ]:
# Intersection

my_set1 = set([1, 2, 3])
my_set2 = set([3, 4, 5])

my_set1 & my_set2
my_set1.intersection(my_set2)
Out[ ]:
{3}
In [ ]:
# Subset

my_set1 = set([1, 2, 3])
my_set2 = set([3, 4, 5])

my_set1 < my_set2
my_set1.issubset(my_set2)
Out[ ]:
False
In [ ]:
# Difference

my_set1 = set([1, 2, 3])
my_set2 = set([3, 4, 5])

my_set1 - my_set2
my_set1.difference(my_set2)
Out[ ]:
{1, 2}
In [ ]:
# Symmetric Difference

my_set1 = set([1, 2, 3])
my_set2 = set([3, 4, 5])

my_set1 ^ my_set2 
my_set1.symmetric_difference(my_set2)
Out[ ]:
{1, 2, 4, 5}

frozensets

In [ ]:
# frozensets
# frozensets are immutable unordered sequence of unique elements.

my_frozenset1 = frozenset([1, 2, 3])
my_dict = {frozenset([1,2]): 1}       # use a set as a key dictionary

Conditions

In [ ]:
# if

language = 'Python'
if language == 'Python':
    print('Condition was True')
Condition was True
In [ ]:
# if else

language = 'Python'
if language == 'Python':
    print('Condition was True')
else:
    print('Not match')
Condition was True
In [ ]:
# if elif else

language = 'Java'
if language == 'Python':
    print('It is Python')
elif language == 'Java':
    print('It is Java')
else:
    print('Not match')
It is Java
In [ ]:
# if and

user ='Admin'
logged_in = True
if user == 'Admin' and logged_in:
    print('Admin page')
else:
    print('Bad creditial')
In [ ]:
# if or

user ='Admin'
logged_in = False
if user == 'Admin' or logged_in:
    print('Admin page')
else:
    print('Bad creditial')
Admin page
In [ ]:
# if not

user ='Admin'
logged_in = False
if not logged_in:
    print('Please log in')
else:
    print('Welcome')
Please log in
In [ ]:
# False

condition = False

if condition:
    print('Evaluated to True')
else: 
    print('Evaluated to False')
Evaluated to False
In [ ]:
# None = False

condition = None

if condition:
    print('Evaluated to True')
else: 
    print('Evaluated to False')
Evaluated to False
In [ ]:
# 0 = False

condition = 0

if condition:
    print('Evaluated to True')
else: 
    print('Evaluated to False')
Evaluated to False
In [ ]:
# Blank = False

condition = ''

if condition:
    print('Evaluated to True')
else: 
    print('Evaluated to False')
Evaluated to False

Loops and Iterations

In [ ]:
# for in

muns = [1, 2, 3, 4, 5]

for num in muns:
    print(num)
1
2
3
4
5
In [ ]:
# for in if

muns = [1, 2, 3, 4, 5]

for num in muns:
    if num == 3:
        print('Found!')
    print(num)
1
2
Found!
3
4
5
In [ ]:
# for in if break

muns = [1, 2, 3, 4, 5]

for num in muns:
    if num == 3:
        print('Found!')
        break
    print(num)
1
2
Found!
In [ ]:
# for in if continue

muns = [1, 2, 3, 4, 5]

for num in muns:
    if num == 3:
        print('Found!')
        continue
    print(num)
1
2
Found!
4
5
In [ ]:
# for in for in

muns = [1, 2, 3, 4]

for num in muns:
    for letter in 'abc':
        print(num, letter)
1 a
1 b
1 c
2 a
2 b
2 c
3 a
3 b
3 c
4 a
4 b
4 c
In [ ]:
# for in range

for i in range(5):
    print(i)
0
1
2
3
4
In [ ]:
# for in range

for i in range(1, 6):
    print(i)
1
2
3
4
5
In [ ]:
# while

x = 0
while x < 5:
    print(x)
    x +=1
0
1
2
3
4
In [ ]:
# while if

x = 0
while x < 5:
    if x == 3:
        break
    print(x)
    x +=1
0
1
2
In [ ]:
# while True

x = 0
while True:
    if x == 3:
        break
    print(x)
    x +=1
0
1
2

Functions

In [ ]:
# def fuction() pass

def hello_func():
    pass

hello_func()
In [ ]:
# print(function)

def hello_func():
    pass

print(hello_func)
print(hello_func())
<function hello_func at 0x7f0ccf9bb0d0>
None
In [ ]:
# print(function())

def hello_func():
  print('Hello Function!')

hello_func()
Hello Function!
In [ ]:
# def fuction() return

def hello_func():
    return 'Hello Function!'

hello_func()
Out[ ]:
'Hello Function!'
In [ ]:
# def fuction() return

def hello_func():
    return 'Hello Function!'

print(hello_func())
Hello Function!
In [ ]:
# def fuction() return 

def hello_func():
    return 'Hello Function!'

print(hello_func().upper())
HELLO FUNCTION!
In [ ]:
# def function(parameter)

def hello_func(greeting):
    return '{} Function.'.format(greeting)

hello_func('Hi')
Out[ ]:
'Hi Function.'
In [ ]:
# def function(arg)

def hello_func(greeting, name = 'John'):
    return '{},{} Function.'.format(greeting, name)

print(hello_func('Hi'))
Hi,John Function.
In [ ]:
def hello_func(greeting, name = 'You'):
    return '{}, {} '.format(greeting, name)

print(hello_func('Hi', 'Tom'))
In [ ]: