X Programming Language in One
What is a programming language?
- Programming languages are tools used to solve problems.
- They are tools used to communicate to computers and machines on how to solve problems and perform tasks
Most Programming Languages
- Mostly have an English syntax
- Unlike human natural languages it can be created or designed by only one person or a few people
- C (Dennis Ritchie)
- C++ (Bjarne Stroustrup)
- Python (Guido van Rossum)
- JavaScript (Brendan Eich)
- Ruby (Yukihiro Matsumoto)
- HTML ( Sir Tim Lee)
- Perl (Larry Wall)
- Java (James Gosling)
- Julia (Jeff Bezanson, Stefan Karpinski, Viral B. Shah, and Alan Edelman)
- Golang (Robert Griesemer, Rob Pike, and Ken Thompson.)
Classification of Programming Languages
- By Paradigms
- By closeness in relation to the machine/computer
- By Type checking
- By Type freedom
7 Domains of Programming
The various domains of expertise you can work as a programmer and can choose to specialize in. All these areas are opportunities you can make impact,income and influence when you learn and apply any programming language.
- Design
- Development
- Databases
- DevOps
- Data Science
- Defence(Cyber)
- Digital Marketing
Installing Python
Python has support for almost all the major platform such as Windows,Linux,MacOs,FreeBSD as well as iOs and android. So you can install it on all of these platform with ease.
You can download python from here.
What is Python?
Python is an interpreted, high-level, general-purpose programming language. Created by Guido van Rossum and first released in 1991. Python’s design philosophy emphasizes code readability with its notable use of significant whitespace. Its language constructs and object-oriented approach aim to help programmers write clear, logical code for small and large-scale projects.
Basics of Python(Level 01)
- DataTypes
- Variables
- Numbers
- Strings
- Arrays
- Functions
- Modules
- Dictionaries
- Tuples
- Sets
- Conditionals
- If elif else
- Loops
- For loop
- While loop
- FileIO
Advanced Python (Level 02-03)
- Data Structures & Collections
- Object Oriented Programming
- Decorators
- Generators
- Web Programming
- MultiThreading and Async
- Modules and Package Building
- Statistics
- Data Analysis
- Command Line Interface Development
- API Development
- Machine Learning and AI
- Quantum Programming
- Domain Specifics
- Etc
Level 01 :Python
Variables
- They are used to store values or data
- Reserved memory locations to store values
- The interpreter or compiler reserves or allocates memory and decide what to store there
- Act as containers that can store any type of data (datatype)
- We use
=
to assign a value to a variable
DataTypes
- They refer to the type of value a variable has
- These are the common datatypes in python
- List
- Dictionary
- Strings
- Tuples
- Numbers
- Sets
- To check for the datatype we use
type()
- Sequence is a collection eg. list,tuple,dictionary,set,string
Usefulness of Variables
- Used to store values
# A Variable thats stores the word hello
a = "hello"
# To Show or Output the variable
print(a)
hello
# Check for the datatype
type(a)
str
# Variables can store different datype
num = 2
type(num)
int
# it can be a boolean
t = True
type(t)
bool
# Behind the scene using disassembly
import dis
dis.dis(a)
1 0 LOAD_NAME 0 (hello) 2 RETURN_VALUE
# Disassembles a code object indicating last instruction
dis.disco(a)
--------------------------------------------------------------------------- AttributeError Traceback (most recent call last) <ipython-input-9-b0b3f7f563f7> in <module> ----> 1 dis.disco(a) /usr/lib/python3.7/dis.py in disassemble(co, lasti, file) 352 def disassemble(co, lasti=-1, *, file=None): 353 """Disassemble a code object.""" --> 354 cell_names = co.co_cellvars + co.co_freevars 355 linestarts = dict(findlinestarts(co)) 356 _disassemble_bytes(co.co_code, lasti, co.co_varnames, co.co_names, AttributeError: 'str' object has no attribute 'co_cellvars'
Numbers
- They python interpreter can act as calculator
- Operators : they are constructs that manipulate the values of operands
x + y
- x and y are operands
+
is an operator
Extra Packages(For Arithmetics and Maths)
- math
- statistics
- numpy
# Numbers
print("Addition: 2 + 4 = ",2 + 4)
print("Subtraction: 4 - 2 = ",4 - 2)
print("Division: 9 / 2 =",9 / 2)
print("Multiplication: 2 * 4 = ",2 * 4)
print("Modulus: 20%3 =",20%3)
print("Exponent: 4 **2 = ",4 **2)
print("Floor Division(remove digits after dec.pts): 9 // 2 = ",9 // 2)
Addition: 2 + 4 = 6 Subtraction: 4 - 2 = 2 Division: 9 / 2 = 4.5 Multiplication: 2 * 4 = 8 Modulus: 20%3 = 2 Exponent: 4 **2 = 16 Floor Division(remove digits after dec.pts): 9 // 2 = 4
Assignment Operators
- ==,!=,<>,<,>,>=,<=
Logical Operators
=
assignment+=
add AND(x += 1 == x = x + 1)
-=
subtract AND(x -= 1 == x = x - 1)
*=
multiply AND(x *= 1 == x = x * 1)
/=
divide AND(x /= 1 == x = x / 1)
**=
exponent AND(x **= 1 == x = x ** 1)
- and
- or
- not
Membership Operators
- in
- not in
Identity Operators
- It compares the memory locations of two objects
- is
- is not
x = 10
print("+ `+=` add AND ,x += 1 == x = x + 1",x += 2)
print("+ `-=` subtract AND,(x -= 1 == x = x - 1)",x -= 2)
print("+ `*=` multiply AND,(x *= 1 == x = x * 1)",x *= 2)
print("+ `/=` divide AND,(x /= 1 == x = x / 1)",x /= 2)
print("+ `**=` exponent AND,(x **= 1 == x = x ** 1),",x **= 2)
File "<ipython-input-25-146d1485e325>", line 2 print("+ `+=` add AND ,x += 1 == x = x + 1",x += 2) ^ SyntaxError: invalid syntax
Strings
- They are a set of characters represented in quotation marks
- In single quote(‘ ‘) or double quote(” “) or triple quote(“”” “””)
Extra Packages
- strings
- unicode
- ftfy
name = "hello python"
type(name)
str
String Manipulation
- dir()
# List All Attributes and Methods
dir(name)
['__add__', '__class__', '__contains__', '__delattr__', '__dir__', '__doc__', '__eq__', '__format__', '__ge__', '__getattribute__', '__getitem__', '__getnewargs__', '__gt__', '__hash__', '__init__', '__init_subclass__', '__iter__', '__le__', '__len__', '__lt__', '__mod__', '__mul__', '__ne__', '__new__', '__reduce__', '__reduce_ex__', '__repr__', '__rmod__', '__rmul__', '__setattr__', '__sizeof__', '__str__', '__subclasshook__', 'capitalize', 'casefold', 'center', 'count', 'encode', 'endswith', 'expandtabs', 'find', 'format', 'format_map', 'index', 'isalnum', 'isalpha', 'isascii', 'isdecimal', 'isdigit', 'isidentifier', 'islower', 'isnumeric', 'isprintable', 'isspace', 'istitle', 'isupper', 'join', 'ljust', 'lower', 'lstrip', 'maketrans', 'partition', 'replace', 'rfind', 'rindex', 'rjust', 'rpartition', 'rsplit', 'rstrip', 'split', 'splitlines', 'startswith', 'strip', 'swapcase', 'title', 'translate', 'upper', 'zfill']
# Convert
print("Uppercase:",name.upper())
print("Lowercase:",name.lower())
print("Titlecase:",name.title())
print("Capitalize:",name.capitalize())
print("Swapcase:",name.swapcase())
Uppercase: HELLO PYTHON Lowercase: hello python Titlecase: Hello Python Capitalize: Hello python Swapcase: HELLO PYTHON
# Find the length of string
len(name)
12
# String Indexing or Splicing
# Starts from 0 not 1
name[0]
'h'
name[0:5]
'hello'
# From begining to end
name[0:]
'hello python'
# Reverse
name[::-1]
'nohtyp olleh'
Finding Characters in A String
- find
- count
- startwith
- endswith
# Find the position of the character
name.find('l')
2
# Find the number/count of a character
"remember".count('e')
3
# Check if a character is in a string
'e' in "remember"
True
# Find the Position or Index of a character
"remember".index('e')
1
# Find the starting index position Index of a character
"remember".find('e')
1
# Check if a string has digits or alphabet
"remember".isalpha()
True
# Check if a string has digits or alphabet
"remember".isdigit()
False
# Check if a string has digits or alphabet
"remember23".isalnum()
True
# Startswith
"alpha".startswith("a")
True
# endswith
"alpha".endswith("a")
True
# Replace and Split
"hello python".replace("python","julia")
'hello julia'
# Replace and Split
"hello python".split()
['hello', 'python']
# String Concatenation
greet = "hello"
fname = "John"
# Method 1
greet + fname
'helloJohn'
# Method 2
"{} {}".format(greet,fname)
'hello John'
# Method 2
"{0} {1}. Yeah {0}".format(greet,fname)
'hello John. Yeah hello'
# Method 3 Using F-Strings
f"{greet} {fname}"
'hello John'
# Method 4 Using F-Strings
F"{greet} {fname.upper()}"
'hello JOHN'
### Extra
import string
dir(string)
['Formatter', 'Template', '_ChainMap', '_TemplateMetaclass', '__all__', '__builtins__', '__cached__', '__doc__', '__file__', '__loader__', '__name__', '__package__', '__spec__', '_re', '_string', 'ascii_letters', 'ascii_lowercase', 'ascii_uppercase', 'capwords', 'digits', 'hexdigits', 'octdigits', 'printable', 'punctuation', 'whitespace']
# Get All the Alphabets
string.ascii_letters
'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ'
# Get All the Digits
string.digits
'0123456789'
# Get All Punctuations and Special Characters
string.punctuation
'!"#$%&\'()*+,-./:;<=>?@[\\]^_`{|}~'
Arrays/List
- List are datatypes that contains items separated by commas and enclosed within square brackets
- [ ]
list()
- Python list can be of different types unlike strict Arrays
- Are mutable (changeable)
Extra Packages
- numpy
# Creating a List of different datatypes
arr = [1,3,"bonjour","medaase",3.5]
# Check for the type
type(arr)
list
arr2 = list((2,4,5.6,"holla"))
arr2
[2, 4, 5.6, 'holla']
type(arr2)
list
# Methods and Attributes of a List
dir(arr)
['__add__', '__class__', '__contains__', '__delattr__', '__delitem__', '__dir__', '__doc__', '__eq__', '__format__', '__ge__', '__getattribute__', '__getitem__', '__gt__', '__hash__', '__iadd__', '__imul__', '__init__', '__init_subclass__', '__iter__', '__le__', '__len__', '__lt__', '__mul__', '__ne__', '__new__', '__reduce__', '__reduce_ex__', '__repr__', '__reversed__', '__rmul__', '__setattr__', '__setitem__', '__sizeof__', '__str__', '__subclasshook__', 'append', 'clear', 'copy', 'count', 'extend', 'index', 'insert', 'pop', 'remove', 'reverse', 'sort']
# Check for the length of a list
len(arr)
5
# Slicing/Indexing
arr[0:5]
[1, 3, 'bonjour', 'medaase', 3.5]
# From 3 till the end
arr[3:]
['medaase', 3.5]
# Last 2 values
arr[-2:]
['medaase', 3.5]
# Adding to the list element at one location
arr.append(arr2)
print(arr)
[1, 3, 'bonjour', 'medaase', 3.5, [2, 4, 5.6, 'holla']]
# Delete the last value
arr.pop()
[2, 4, 5.6, 'holla']
arr
[1, 3, 'bonjour', 'medaase', 3.5]
# To Extend the list
# Adds element one by one in distinct locations
arr.extend([10,20,30])
arr
[1, 3, 'bonjour', 'medaase', 3.5, 10, 20, 30]
#### Note The Difference Between Extend and Append
even = [2,4,6]
odd = [3,5,7]
even.extend([8,10,12])
odd.append([8,10,12])
Extending None Appending None
print("Extending::",even)
print("Appending::",odd)
Extending:: [2, 4, 6, 8, 10, 12] Appending:: [3, 5, 7, [8, 10, 12]]
# Sorting A List
fruits = ["mango","apple","nut","banana"]
# Apply the sort function to the list
fruits.sort()
fruits
['apple', 'banana', 'mango', 'nut']
# Reverse sort
fruits.sort(reverse=True)
fruits
['nut', 'mango', 'banana', 'apple']
# Inserting An Element into a List
companies = ["Facebook","Netflix","Google","Apple","Amazon"]
# Insert JCharisTech into the 2 position List
companies.insert(2,"JCharisTech")
companies
['Facebook', 'Netflix', 'JCharisTech', 'Google', 'Apple', 'Amazon']
Arrays
- It can hold only homogeneous data, all of the same type, and so it uses only sizeof(one object) * length bytes of memory. Mostly,you should use it when you need to expose a C array to an extension or a system call (for example, ioctl or fctnl).
- It is useful when you need a homogeneous C array of data for reasons other than doing math.
List
- flexible
- can be heterogeneous
array (ex: numpy array)
- array of uniform values
- homogeneous
When To Use List or Arrays
- Use Arrays:: if you know that the array will not change and you want to expose a C array to a system call
- Use List:: if you plan on adding items, a list is the way to go.
- Use Lists:: almost all the time
- Arrays are more efficient than lists for some uses. If you need to allocate an array that you KNOW will not change, then arrays can be faster and use less memory.
- On the other hand, part of the reason why lists eat up more memory than arrays is because python will allocate a few extra elements when all allocated elements get used. This means that appending items to lists is faster. So if you plan on adding items, a list is the way to go.
import array
dir(array)
['ArrayType', '__doc__', '__loader__', '__name__', '__package__', '__spec__', '_array_reconstructor', 'array', 'typecodes']
code C-Type
'i' signed int
'f' float
'd' double
# Arrays of Integer
custom_arr = array.array('i',[1,2,3])
custom_arr
array('i', [1, 2, 3])
# Check Type
type(custom_arr)
array.array
# Extra
import numpy as np
# Create Arrays of Different dimensions
arr_0dim = np.array(42)
arr_1dim = np.array([1, 2, 3, 4, 5])
arr_2dim = np.array([[1, 2, 3], [4, 5, 6]])
arr_3dim = np.array([[[1, 2, 3], [4, 5, 6]], [[1, 2, 3], [4, 5, 6]]])
# Check for Dimensions and size
print("Dimensions:",arr_0dim.ndim, "Size",arr_0dim.size)
print("Dimensions:",arr_1dim.ndim, "Size",arr_1dim.size)
print("Dimensions:",arr_2dim.ndim, "Size",arr_2dim.size)
print("Dimensions:",arr_3dim.ndim, "Size",arr_3dim.size)
Dimensions: 0 Size 1 Dimensions: 1 Size 5 Dimensions: 2 Size 6 Dimensions: 3 Size 12
# Check the type
type(arr_0dim)
numpy.ndarray
# Create A List/Array of Zeros or Ones
ones = np.ones(20)
ones
array([1., 1., 1., 1., 1., 1., 1., 1., 1., 1., 1., 1., 1., 1., 1., 1., 1., 1., 1., 1.])
Dictionaries
- They are a form of associative arrays that consist of key-value pairs
- They are the most important data structure
- Are like hash tables
- {}
dict()
Extra Packages
- collections
# Create A Dictionary
# Method 1
students = {'name':'Mark','age':23,'address':'London'}
# Create A Dictionary
# Method 2
students2 = dict({'name':'John','age':20,'address':'Accra'})
# Check type
type(students)
dict
# Check type
type(students2)
dict
# Methods or Attributes
dir(students)
['__class__', '__contains__', '__delattr__', '__delitem__', '__dir__', '__doc__', '__eq__', '__format__', '__ge__', '__getattribute__', '__getitem__', '__gt__', '__hash__', '__init__', '__init_subclass__', '__iter__', '__le__', '__len__', '__lt__', '__ne__', '__new__', '__reduce__', '__reduce_ex__', '__repr__', '__setattr__', '__setitem__', '__sizeof__', '__str__', '__subclasshook__', 'clear', 'copy', 'fromkeys', 'get', 'items', 'keys', 'pop', 'popitem', 'setdefault', 'update', 'values']
# Get All the Keys in the dictionary
students.keys()
dict_keys(['name', 'age', 'address'])
# Get All the values in the dictionary
students.values()
dict_values(['Mark', 23, 'London'])
# Get All items in the dictionary
students.items()
dict_items([('name', 'Mark'), ('age', 23), ('address', 'London')])
# Find a Value using bracket notation or index
students['name']
'Mark'
# Find a Value using get function
# Best method if you don't know the key
students.get('name')
'Mark'
### When to use [] and get()
students['names']
--------------------------------------------------------------------------- KeyError Traceback (most recent call last) <ipython-input-165-0a94c04845a2> in <module> 1 ### When to use [] and get() ----> 2 students['names'] KeyError: 'names'
# Find a Value using get function
# Best method if you don't know the key
students.get('names')
# Iterating
for k,v in students.items():
print('{} ==> {}'.format(k,v))
name ==> Mark age ==> 23 address ==> London
parents = {'job':'Doctor','nationality':'Ghana'}
# Updating Dictionary
students.update(parents)
# Deleting or Removing the last
students.popitem()
('nationality', 'Ghana')
students
{'name': 'Mark', 'age': 23, 'address': 'London', 'job': 'Doctor'}
students
{'name': 'Mark', 'age': 23, 'address': 'London', 'job': 'Doctor', 'nationality': 'Ghana'}
# Python Trick For Merging Dictionary
# Method 1
family = {**students,**parents}
family
{'name': 'Mark', 'age': 23, 'address': 'London', 'job': 'Doctor', 'nationality': 'Ghana'}
# Method 2
family2 = dict(students2,**parents)
family2
{'name': 'John', 'age': 20, 'address': 'Accra', 'job': 'Doctor', 'nationality': 'Ghana'}
Tuples
- Tuples are a form of sequence datatype or collection that are enclosed within a parentheses
- ()
tuple()
- Are immutable (read only and unchangeable)
Extra Packages
- named tuples
# Creating a Tuple
t1 = (2,3,4,5)
# Check type
type(t1)
tuple
# Methods and Attributes
dir(t1)
['__add__', '__class__', '__contains__', '__delattr__', '__dir__', '__doc__', '__eq__', '__format__', '__ge__', '__getattribute__', '__getitem__', '__getnewargs__', '__gt__', '__hash__', '__init__', '__init_subclass__', '__iter__', '__le__', '__len__', '__lt__', '__mul__', '__ne__', '__new__', '__reduce__', '__reduce_ex__', '__repr__', '__rmul__', '__setattr__', '__sizeof__', '__str__', '__subclasshook__', 'count', 'index']
# Length
len(t1)
4
# Indexing
t1[0:2]
(2, 3)
# Are Immutable(You can't change them)
t1[2] = 40
--------------------------------------------------------------------------- TypeError Traceback (most recent call last) <ipython-input-193-8d0a61b14cba> in <module> ----> 1 t1[2] = 40 TypeError: 'tuple' object does not support item assignment
### Extra
from collections import namedtuple
# Declaring namedtuple()
Student = namedtuple('Student',['name','age','DOB'])
Student
__main__.Student
# Check Type
type(Student)
type
# Adding values
S = Student('Paul','19','2541997')
S
Student(name='Paul', age='19', DOB='2541997')
# Access using index
print ("The Student age using index is : ",end ="")
print (S[1])
The Student age using index is : 19
# Access using name
print ("The Student name using keyname is : ",end ="")
print (S.name)
The Student name using keyname is : Paul
# Access using getattr()
print ("The Student DOB using getattr() is : ",end ="")
print (getattr(S,'DOB'))
The Student DOB using getattr() is : 2541997
Sets
- A Set is an unordered and unindexed collection
- {} with comma separated items/element
set()
Extra Packages
- matplotlib-venn
- matplotlib-subsets
# Method 1
all_nums = {0,1,2,3,4,5,6,7,8,9}
even_nums = {2,4,6,8}
# Method 2
prime_num = set([2,3,5,7,11])
#Check they type
type(all_nums)
set
type(prime_num)
set
# Methods and Attributes
dir(all_nums)
['__and__', '__class__', '__contains__', '__delattr__', '__dir__', '__doc__', '__eq__', '__format__', '__ge__', '__getattribute__', '__gt__', '__hash__', '__iand__', '__init__', '__init_subclass__', '__ior__', '__isub__', '__iter__', '__ixor__', '__le__', '__len__', '__lt__', '__ne__', '__new__', '__or__', '__rand__', '__reduce__', '__reduce_ex__', '__repr__', '__ror__', '__rsub__', '__rxor__', '__setattr__', '__sizeof__', '__str__', '__sub__', '__subclasshook__', '__xor__', 'add', 'clear', 'copy', 'difference', 'difference_update', 'discard', 'intersection', 'intersection_update', 'isdisjoint', 'issubset', 'issuperset', 'pop', 'remove', 'symmetric_difference', 'symmetric_difference_update', 'union', 'update']
# Adding to A Set
prime_num.add(13)
prime_num
{2, 3, 5, 7, 11, 13}
# Removing an item (remove or discard)
prime_num.remove(2)
prime_num
{3, 5, 7, 11, 13}
# using discard() : doesn't raise an error if not found
prime_num.discard(2)
prime_num
{3, 5, 7, 11, 13}
# Raises a Key Error if you use remove()
prime_num.remove(2)
--------------------------------------------------------------------------- KeyError Traceback (most recent call last) <ipython-input-13-c37ca345cb90> in <module> 1 # Raises an Error if you use remove() ----> 2 prime_num.remove(2) KeyError: 2
# Remove the last item with pop
# Since they are unordered it can pop out any number
prime_num.pop()
3
prime_num
{5, 7, 11, 13}
# Remove all element with clear()
prime_num.clear()
prime_num
set()
Maths with Sets
- union
- intersection
- difference
- difference_update
- issubset
- issuperset
- symmetric_difference
odd_nums = {1,3,5,7,9}
# Union of Sets
# Method 1: Doesnt change the sets
even_nums.union(odd_nums)
{1, 2, 3, 4, 5, 6, 7, 8, 9}
even_nums
{2, 4, 6, 8}
even2 = even_nums
# Union of Sets by updating
# Method 2: Does change the initial sets
even2.update(odd_nums)
even2
{1, 2, 3, 4, 5, 6, 7, 8, 9}
even_nums
{1, 2, 3, 4, 5, 6, 7, 8, 9}
# Intersection of Sets
even_nums.intersection(odd_nums)
{1, 3, 5, 7, 9}
# Subset
even_nums.issubset(all_nums)
True
# Difference of Sets
even_nums.difference(odd_nums)
{2, 4, 6, 8}
# isdisjoint of Sets
even_nums.isdisjoint(odd_nums)
False
Ploting The Set
- matplotlib-venn
- matplotlib
import matplotlib_venn
dir(matplotlib_venn)
['___all___', '__builtins__', '__cached__', '__doc__', '__file__', '__loader__', '__name__', '__package__', '__path__', '__spec__', '_arc', '_common', '_math', '_region', '_util', '_venn2', '_venn3', 'venn2', 'venn2_circles', 'venn2_unweighted', 'venn3', 'venn3_circles', 'venn3_unweighted']
from matplotlib_venn import venn2,venn3,venn2_circles
import matplotlib.pyplot as plt
# Plot 2 Venn diagrams
venn2([even_nums,odd_nums],('Even Numbers','Odd Numbers'))
plt.show()
# Plot 2 Venn diagrams
venn2([all_nums,odd_nums],set_labels=('All Numbers','Odd Numbers'))
plt.show()
Conditionals
If,elif else
- For conditional statements
- Must obey indentation
- It can be nested
x = 30
y = 20
# if and else
if x == 30:
print("X is equal to 30")
else:
print("X is not equal")
X is equal to 30
# if ,elif and else
if x == 30:
print("X is equal to 30")
elif x < 20:
print("X is less")
else:
print("X is not equal")
X is equal to 30
Ternary Expressions
- One line if statement
result_if_true if a > b else result_if_false
print("Equal") if y == 20 else print("Not Equal")
Equal
For Loops
- A for loop is used for iterating over a sequence.
- Works as an iterator method
for
- Can be used with
break,continue,else,pass
range()
languages = ["Javascript","Python","C","C++","Julia","Golang","Assembly"]
# looping through our sequence
for i in languages:
print(i)
Javascript Python C C++ Julia Golang Assembly
# Looping through a string
for s in "hello world":
print(s.upper())
H E L L O W O R L D
# Using the Break Statement
# use to stop the loop before it iterate through all items
for lang in languages:
print(lang)
if lang == 'Python':
break
Javascript Python
# Using the Continue Statement
# use to continue the loop
for lang in languages:
if lang == 'Python':
continue
print(lang)
Javascript C C++ Julia Golang Assembly
# Using the Pass Statement
# for loops cannot be empty hence we use pass to pass the loop without erros
for lang in languages:
pass
Using the Range Functions
- range(end)
- range(start,end)
- range(start,end,step)
# End
range(10)
range(0, 10)
# Start to End
range(0,20)
range(0, 20)
# Start to End with Step
range(0,20,2)
range(0, 20, 2)
# Looping through
for i in range(10):
print(i)
0 1 2 3 4 5 6 7 8 9
# Looping through
for i in range(0,10,3):
print(i)
0 3 6 9
While Loop
- Used to execute a set of statement as long as a condition is true
while
- You can use it with
break,continue,else,pass
# Print i as long as i is less than 6
i = 1
while i < 7:
print(i)
i = i + 1
# i+=1
1 2 3 4 5 6
Functions
- A function is a block of code which only runs when it is called
- It is defined with the
def
which stands for defined function - We can define,declare and call a function
- Functions have arguments or parameters
- Parameters: the variable listed inside the parentheses in the function definition
- Arguments: the value that is sent to the function when it is called
- optional arguments
- keyword arguments
- postional arguments
Extra Packages
- kwargs
# Defining a function
def my_function(name):
print("Hello ", name)
# Calling a function
my_function("Jesse")
Hello Jesse
# Check the type
type(my_function)
function
# You Can Assign a function to a variable
new_func = my_function
new_func("John")
Hello John
Behind the scene of a function
- Disassembly of the code
- dis packages
- bytecode package
import dis
# methods/Attributes of dis
dir(dis)
['Bytecode', 'COMPILER_FLAG_NAMES', 'EXTENDED_ARG', 'FORMAT_VALUE', 'HAVE_ARGUMENT', 'Instruction', '_Instruction', '_OPARG_WIDTH', '_OPNAME_WIDTH', '__all__', '__builtins__', '__cached__', '__doc__', '__file__', '__loader__', '__name__', '__package__', '__spec__', '_disassemble_bytes', '_disassemble_recursive', '_disassemble_str', '_format_code_info', '_get_code_object', '_get_const_info', '_get_instructions_bytes', '_get_name_info', '_have_code', '_test', '_try_compile', '_unpack_opargs', 'cmp_op', 'code_info', 'collections', 'dis', 'disassemble', 'disco', 'distb', 'findlabels', 'findlinestarts', 'get_instructions', 'hascompare', 'hasconst', 'hasfree', 'hasjabs', 'hasjrel', 'haslocal', 'hasname', 'hasnargs', 'io', 'opmap', 'opname', 'pretty_flags', 'show_code', 'stack_effect', 'sys', 'types']
dis.dis(my_function)
3 0 LOAD_GLOBAL 0 (print) 2 LOAD_CONST 1 ('Hello ') 4 LOAD_FAST 0 (name) 6 CALL_FUNCTION 2 8 POP_TOP 10 LOAD_CONST 0 (None) 12 RETURN_VALUE
# Check for the code
my_function.__code__
<code object my_function at 0x7fc1783ab0c0, file "<ipython-input-58-21a95ee83b1c>", line 2>
# Check for the bytecode
my_function.__code__.co_code
b't\x00d\x01|\x00\x83\x02\x01\x00d\x00S\x00'
# Check for the name of the function
my_function.__code__.co_name
'my_function'
# Check for stacksize
my_function.__code__.co_stacksize
3
# Check for the non local variables
# Global variables
my_function.__code__.co_names
('print',)
# Check for the local variables
my_function.__code__.co_varnames
('name',)
# Defining a function with a return statement
def my_function2(name):
result = "Hi {}".format(name)
return result
my_function2("Jane")
'Hi Jane'
dis.dis(my_function2)
3 0 LOAD_CONST 1 ('Hi {}') 2 LOAD_METHOD 0 (format) 4 LOAD_FAST 0 (name) 6 CALL_METHOD 1 8 STORE_FAST 1 (result) 4 10 LOAD_FAST 1 (result) 12 RETURN_VALUE
Variable Number of Arguments
- Accepting multiple arguments if you don’t know
*args
def buy_items(*items):
items_list = [*items]
return items_list
buy_items("Banana")
['Banana']
buy_items("Banana","Apple","books")
['Banana', 'Apple', 'books']
Keyword Arguments (Kwargs)
+Attaching a value to a keyword as an argument
- For accepting an unknown number of keyword argument we can use
**kwargs
# Simple function with a keyword argument and a defaul parameter value of 0
def triangle(base=0,height=0):
result = 1/2*base*height
return result
# In a positional way
triangle(20,40)
400.0
# In a keyword way ireespective of position
triangle(height=40,base=20)
400.0
### Working with **kwargs
def make_emails(**names):
emails = "@".join(names.values())
return emails
make_emails(fname="Jesse",lname="Agbemabiase")
'Jesse@Agbemabiase'
make_emails(fname="Jesse",lname="Agbemabiase",email="gmail")
'Jesse@Agbemabiase@gmail'
dis.dis(make_emails)
3 0 LOAD_CONST 1 ('@') 2 LOAD_METHOD 0 (join) 4 LOAD_FAST 0 (names) 6 LOAD_METHOD 1 (values) 8 CALL_METHOD 0 10 CALL_METHOD 1 12 STORE_FAST 1 (emails) 4 14 LOAD_FAST 1 (emails) 16 RETURN_VALUE
Documentation For Functions
- using docstrings
- useful for automatic docs generation
def do_task(name):
"""Do this task """
print("Doing ",task)
# To get the docs
# method 1 using help
help(do_task)
Help on function do_task in module __main__: do_task(name) Do this task
# To get the docs using __doc__
do_task.__doc__
'Do this task '
# Inside Jupyter or Ipython
?do_task
Signature: do_task(name) Docstring: Do this task File: ~/Documents/JLabs/PathTut/<ipython-input-96-4cb8a8770c75> Type: function
FileIO (Input and Output)
- Open
open(file_name,[access_mode(r,a,w,b+)],[buffering])
- Read
- Write #### Output
print()
Input
input()
raw_input()
: returns as a string/ python2.7
print("Hello Learner")
Hello Learner
age = input("Enter Your Age")
print(age)
24
# Open A File and Create A File By Writing o it
file1 = open("examplefile.txt","wb")
file1.write(b"Writing to textfile")
19
file1.close()
# Open A File and Create A File By Writing o it
with open("examplefile.txt","rb") as f:
data = f.read()
print(data)
b'Writing to textfile'
Reading other file types
There are packages for reading each file types
- JSON : json
- CSV : csv
- YAML
- etc
Bookmarked!, I really like your blog!
Glad you liked it,Elisha
Saved as a favorite!, I enjoy it!
Glad it helped. Thanks Arthur
Saved as a favorite!, I love your blog!
tҺe website іѕ really good, I like your website!
First time visiting your website, I enjoy your site!