Python Notes Update-1
Python Notes Update-1
• Python has a lot of applications. It's used for developing web applications, data science,
rapid application development, and so on.
• Python allows you to write programs in fewer lines of code than most of the
programming languages.
• The popularity of Python is growing rapidly. Now it's one of the most popular
programming languages.
5. Then Go to Run > Run current script or simply click F5 to run it.
Install Python Separately
If you don't want to use Thonny, here's how you can install and run Python on your
computer.
2. Run the installer file and follow the steps to install Python
During the install process, check Add Python to environment variables. This will add
Python to environment variables, and you can run Python from any part of the computer.
Installing
We can use any text editing software to write a Python script file.
We just need to save it with the .py extension. But using an IDE can make our life a lot
easier. IDE is a piece of software that provides useful features like code hinting, syntax
highlighting and checking, file explorers, etc. to the programmer for application
development.
By the way, when you install Python, an IDE named IDLE is also installed. You can use
it to run Python on your computer. It's a decent IDE for beginners.
When you open IDLE, an interactive Python Shell is opened.
Now you can create a new file and save it with .py extension. For example, hello.py
Write Python code in the file and save it. To run the file, go to Run > Run Module or
simply click F5.
Your first Python Program
Now that we have Python up and running, we can write our first Python program.
Let's create a very simple program called Hello World. A "Hello, World!" is a simple
program that outputs Hello, World! on the screen. Since it's a very simple program, it's
often used to introduce a new programming language to beginners.
Type the following code in any text editor or an IDE and save it as hello_world.py
print("Hello, world!")
Then, run the file. You will get the following output.
Hello, world!
More Examples
print(‘Hello World’)
print(100)
print(1,2,3) //multiple values can be printed and it must be separated by coma and output
will be 1 2 3 . Notice that in output, we have space as a separator because default
separator value is space.
Print( ) //in this case, only end argument default value will be printed which is “\n”
Print(end=”&”)
Print(1)
Print(“hello”)
Print(end=”&”)
Print(1, end=”@”)
Print(“hello”)
Print(2)
Print(4)
Print (“the answer is”, 100) //here we have string argument and number argument. Both
can be used
Python Keywords
Keywords are the reserved words in Python.
We cannot use a keyword as a variable name, function name or any other identifier. They
are used to define the syntax and structure of the Python language. In Python, keywords
are case sensitive. There are 33 keywords in Python 3.7. This number can vary slightly
over the course of time.
All the keywords except True, False and None are in lowercase and they must be written
as they are.
Python Identifiers
An identifier is a name given to entities like class, functions, variables, etc. It helps to
differentiate one entity from another.
Rules for writing identifiers
global = 1
Output
a@ = 0
Output
Python is a case-sensitive language. This means, Variable and variable are not the same.
Always give the identifiers a name that makes sense. While c = 10 is a valid name,
writing count = 10 would make more sense, and it would be easier to figure out what it
represents when you look at your code after a long gap.
Multiple words can be separated using an underscore, like this_is_a_long_variable.
Python Statement
Instructions that a Python interpreter can execute are called statements. For example, a =
1 is an assignment statement. if statement, for statement, while statement, etc. are other
kinds of statements
Multi-line statement
In Python, the end of a statement is marked by a newline character. But we can make a
statement extend over multiple lines with the line continuation character (\). For example:
a=1+2+3+\
4+5+6+\
7+8+9
a = (1 + 2 + 3 +
4+5+6+
7 + 8 + 9)
Here, the surrounding parentheses ( ) do the line continuation implicitly. Same is the case
with [ ] and { }. For example:
colors = ['red',
'blue',
'green']
We can also put multiple statements in a single line using semicolons, as follows:
a = 1; b = 2; c = 3
Python Comments
Comments are very important while writing a program. They describe what is going on
inside a program, so that a person looking at the source code does not have a hard time
figuring it out.
#This is a comment
#print out Hello
print('Hello')
Multi-line comments
We can have comments that extend up to multiple lines. One way is to use the hash(#)
symbol at the beginning of each line. For example:
Another way of doing this is to use triple quotes, either ''' or """.
"""This is also a
perfect example of
multi-line comments"""
Python Variables
A variable is a named location used to store data in the memory. It is helpful to think of
variables as a container that holds data that can be changed later in the program. For
example,
number = 10
Here, we have created a variable named number. We have assigned the value 10 to the
variable.
You can think of variables as a bag to store books in it and that book can be replaced at
any time.
number = 10
number = 1.1
Initially, the value of number was 10. Later, it was changed to 1.1.
website = "apple.com"
print(website)
Output
apple.com
In the above program, we assigned a value apple.com to the variable website. Then, we
printed out the value assigned to website i.e. apple.com
you don't have to explicitly define the variable type. It automatically knows
that apple.com is a string and declares the website variable as a string.
website = "apple.com"
print(website)
print(website)
Output
apple.com
programiz.com
In the above program, we have assigned apple.com to the website variable initially.
Then, the value is changed to programiz.com.
a, b, c = 5, 3.2, "Hello"
print (a)
print (b)
print (c)
If we want to assign the same value to multiple variables at once, we can do this as:
x = y = z = "same"
print (x)
print (y)
print (z)
The second program assigns the same string to all the three variables x, y and z.
In Python, constants are usually declared and assigned in a module. Here, the module is a
new file containing variables, functions, etc which is imported to the main file. Inside the
module, constants are written in all capital letters and underscores separating the words.
Example 3: Declaring and assigning value to a constant
Create a constant.py:
PI = 3.14
GRAVITY = 9.8
Create a main.py:
import constant
print(constant.PI)
print(constant.GRAVITY)
Output
3.14
9.8
In the above program, we create a constant.py module file. Then, we assign the constant
value to PI and GRAVITY. After that, we create a main.py file and import
the constant module. Finally, we print the constant value.
Note: In reality, we don't use constants in Python. Naming them in all capital letters is a
convention to separate them from variables, however, it does not actually prevent
reassignment.
3. MACRO_CASE
4. camelCase
CapWords
5. Create a name that makes sense. For example, vowel makes more sense than v.
6. If you want to create a variable name having two words, use underscore to separate
them. For example:
7. my_name
current_salary
9. PI
10. G
11. MASS
12. SPEED_OF_LIGHT
TEMP
13. Never use special symbols like !, @, #, $, %, etc.
Python Literals
Literals are representations of fixed values in a program. They can be numbers,
characters, or strings, etc. For example, 'Hello, World!' , 12 , 23.0 , 'C' , etc.
Literals are often used to assign values to variables or constants. For example,
site_name = 'hello.com'
result1 = True
some_character = 'S'
For example,
print(value)
# Output: None
Here, we get None as an output as the value variable has no value assigned to it.
Python Data Types
Every value in Python has a datatype. Since everything is an object in Python
programming, data types are actually classes and variables are instance (object) of these
classes.
There are various data types in Python. Some of the important types are
Python Numbers
Integers, floating point numbers and complex numbers fall under Python
numbers category. They are defined as int, float and complex classes in Python.
We can use the type() function to know which class a variable or a value belongs to.
a=5
print(a, "is of type", type(a))
a = 2.0
print(a, "is of type", type(a))
a = 1+2j
print(a, "is complex number?", isinstance(1+2j,complex))
Output
The float type in Python designates a floating-point number. float values are specified
with a decimal point. Integer and floating points are separated by decimal points. 1 is an
integer, 1.0 is a floating-point number.
Complex numbers are written in the form, x + yj, where x is the real part and y is the
imaginary part. Here are some examples.
>>> a = 1234567890123456789
>>> a
1234567890123456789
>>> b = 0.1234567890123456789
>>> b
0.12345678901234568
>>> c = 1+2j
>>> c
(1+2j)
Python List
List is an ordered sequence of items. It is one of the most used datatype in Python and is
very flexible. All the items in a list do not need to be of the same type.
Declaring a list is pretty straight forward. Items separated by commas are enclosed within
brackets [ ].
We can use the slicing operator to extract an item or a range of items from a list. The
index starts from 0 in Python.
a = [5,10,15,20,25,30,35,40]
# a[2] = 15
print("a[2] = ", a[2])
Output
a[2] = 15
a[0:3] = [5, 10, 15]
a[5:] = [30, 35, 40]
Lists are mutable, meaning, the value of elements of a list can be altered.
a = [1, 2, 3]
a[2] = 4
print(a)
Output
[1, 2, 4]
Python Tuple
Tuple is an ordered sequence of items same as a list. The only difference is that tuples are
immutable. Tuples once created cannot be modified.
Tuples are used to write-protect data and are usually faster than lists as they cannot
change dynamically.
t = (5,'program', 1+3j)
We can use the slicing operator [] to extract items but we cannot change its value.
t = (5,'program', 1+3j)
# t[1] = 'program'
print("t[1] = ", t[1])
Output
Example
a = range(5)
01234
Another Example
numbers = range(4)
for i in numbers:
print(i)
# Output:
#0
#1
#2
#3
Note: range() returns an immutable sequence of numbers that can be easily converted
to lists, tuples, sets etc.
Syntax of range()
The range() function can take a maximum of three arguments:
In this case, range() returns a sequence of numbers starting from start (inclusive) up
to stop (exclusive).
The step argument specifies the incrementation between two numbers in the sequence.
Note: The default value of start is 0, and the default value of step is 1. That's
why range(0, 5, 1) is equivalent to range(5) .
range() in for Loop
The range() function is commonly used in a for loop to iterate the loop a certain
number of times. For example,
# iterate the loop 5 times
for i in range(5):
print(i, 'Hello')
Output
0 Hello
1 Hello
2 Hello
3 Hello
4 Hello
Set Type
A set is an unordered collection of elements. Its order is not maintained in the set. It
means that elements are not appear in the same order as they are entered into the set.
Example
A = {1,2,3,”test”}
B = {1,1,2,2,3,3}
Example
a = {10,100,200}
Example
Output
Example
a = {1,2,2,3,3,3}
print(a)
Output
{1, 2, 3}
Since, set are unordered collection, indexing has no meaning. Hence, the slicing
operator [] does not work.
>>> a = {1,2,3}
>>> a[1]
Traceback (most recent call last):
File "<string>", line 301, in runcode
File "<interactive input>", line 1, in <module>
TypeError: 'set' object does not support indexing
Python Dictionary
In Python, dictionaries are defined within braces {} with each item being a pair in the
form key:value. keys are unique identifiers that are associated with each value. Key
and value can be of any type.
>>> d = {1:'value','key':2}
>>> type(d)
<class 'dict'>
Example
print(names)
Output
{'A': 'B', 'C': 'D', 'E': 'F'}
We use keys to retrieve the respective value . But not the other way around. For
example,
# create a dictionary named capital_city
capital_city = {'Nepal': 'Kathmandu', 'Italy': 'Rome', 'England': 'London'}
Here, we have accessed values using keys from the capital_city dictionary.
Since 'Nepal' is key, capital_city['Nepal'] accesses its respective value i.e. Kathmandu
However, 'Kathmandu' is the value for the 'Nepal' key, so capital_city['Kathmandu'] throws an
error message.
Example
d = {1:'value','key':2}
print(type(d))
# Generates error
print("d[2] = ", d[2])
Output
<class 'dict'>
d[1] = value
d['key'] = 2
Traceback (most recent call last):
File "<string>", line 9, in <module>
KeyError: 2
Python Type Conversion
In programming, type conversion is the process of converting data of one type to
another. For example: converting int data to str .
There are two types of type conversion in Python.
integer_number = 123
float_number = 1.23
Value: 124.23
Data Type: <class 'float'>
As we can see new_number has value 124.23 and is of the float data type.
It is because Python always converts smaller data types to larger data types to avoid
the loss of data.
Note:
• We get TypeError , if we try to add str and int . For example, '12' + 23 . Python is not
able to use Implicit Conversion in such conditions.
• Python has a solution for these types of situations which is known as Explicit
Conversion.
We use the built-in functions like int() , float() , str() , etc to perform explicit type
conversion.
This type of conversion is also called typecasting because the user casts (changes) the
data type of the objects.
Example 2: Addition of string and integer Using Explicit
Conversion
num_string = '12'
num_integer = 23
print("Sum:",num_sum)
print("Data type of num_sum:",type(num_sum))
Output
num_string = int(num_string)
Here, we have used int() to perform explicit type conversion of num_string to integer
type.
After converting num_string to an integer value, Python is able to add these two
variables.
Finally, we got the num_sum value i.e 35 and data type to be int .
4. Explicit Type Conversion is also called Type Casting, the data types of objects
are converted using predefined functions by the user.
5. In Type Casting, loss of data may occur as we enforce the object to a specific
data type.
Python Basic Input and Output
Python Output
In Python, we can simply use the print() function to print output. For example,
print('Python is powerful')
Here, the print() function displays the string enclosed inside the single quotation.
Syntax of print()
In the above code, the print() function is taking a single parameter.
Here,
• end (optional) - allows us to add add specific values like new line "\n" , tab "\t"
• file (optional) - where the values are printed. It's default value
is sys.stdout (screen)
• flush (optional) - boolean specifying if the output is flushed or buffered.
Default: False
Good Morning!
It is rainy today
In the above example, the print() statement only includes the object to be printed.
Here, the value for end is not used. Hence, it takes the default value '\n' .
Output
Notice that we have included the end= ' ' after the end of the first print() statement.
Hence, we get the output in a single line separated by space.
In the above example, the print() statement includes multiple items separated by a
comma.
Notice that we have used the optional parameter sep= ". " inside the print() statement.
Hence, the output includes items separated by . not comma.
name = "Programiz"
# print literals
print(5)
# print variables
print(number)
print(name)
Output
5
-10.6
Programiz
Programiz is awesome.
Here,
Python Input
While programming, we might want to take the input from the user. In Python, we can
use the input() function.
Syntax of input()
input(prompt)
Output
Enter a number: 10
You Entered: 10
Data type of num: <class 'str'>
In the above example, we have used the input() function to take input from the user and
stored the user input in the num variable.
It is important to note that the entered value 10 is a string, not a number.
So, type(num) returns <class 'str'> .
To convert user input into a number we can use int() or float() functions as:
Here, the data type of the user input is converted from string to integer .
% Modulus Divides left hand operand by right hand operand and returns b%a=
remainder 0
9//2 = 4 and
// Floor Division - The division of operands where the result is the
9.0//2.0 = 4.0,
quotient in which the digits after the decimal point are removed. -11//3 = -4, -
11.0//3 = -4.0
But if one of the operands is negative, the result is floored, i.e.,
rounded away from zero (towards negative infinity) −
== If the values of two operands are equal, then the condition becomes (a == b) is
true. not true.
> If the value of left operand is greater than the value of right (a > b) is
operand, then condition becomes true. not true.
< If the value of left operand is less than the value of right operand, (a < b) is
then condition becomes true. true.
>= If the value of left operand is greater than or equal to the value of (a >= b) is
right operand, then condition becomes true. not true.
<= If the value of left operand is less than or equal to the value of right (a <= b) is
operand, then condition becomes true. true.
Python Assignment Operators
= Assigns values from right side operands to left side operand c=a+b
assigns
value of a
+ b into c
+= Add It adds right operand to the left operand and assign the result c += a is
to left operand equivalent
to c = c +
a
-= Subtract It subtracts right operand from the left operand and assign the c -= a is
result to left operand equivalent
to c = c -
a
*= Multiply It multiplies right operand with the left operand and assign the c *= a is
result to left operand equivalent
to c = c *
a
/= Divide It divides left operand with the right operand and assign the c /= a is
result to left operand equivalent
to c = c /
a
%= Modulus It takes modulus using two operands and assign the result to c %= a is
AND left operand equivalent
to c = c %
a
//= Floor It performs floor division on operators and assign value to the c //= a is
Division left operand equivalent
to c = c //
a
Python Logical Operators
and Returns True if both statements are true x < 5 and x < 10
not Reverse the result, returns False if the result is not(x < 5 and x <
true 10)
Python Built In Math Functions
In Python, the round method rounded off the given number. If you have not specified
how many decimals points to rounding off given number then it rounds the given
number in the integer.
Syntax
round(number, digits)
x = round(5.5)
print(x)
x = round(6.76543, 2)
print(x)
Output
6
6.77
x power y (xy)
One more great in-built method is available in Python. In Python, the ABS () method
is used when the absolute value of a given number is to be found.
Syntax
abs(n)
Output
5.50
In Python, the min() method is used when the smallest value is to be obtained from a
list or a given input list.
Syntax
print(x) // output
Output
5
Max method in python
In Python, the max() method is used when the largest value is to be obtained from a
list or a given input list.
Syntax
print(x)
Output
55
The CMP() method in Python compares the two given objects and returns a result of
1,- 1, 0.
Syntax
cmp(a, b)
# when x = y
x=2
y=2
print(cmp(x, y))
# when x>y
x=3
y=2
print(cmp(x, y))
Output
-1
0
1
Use of hex () method in python changed the given number to hexadecimal value.
Syntax
hex(number)
Output
0x22b
Use of oct() method in python changed the given number to octal string.
Syntax
oct(number)
Output
0o1053
int() method in python
The int() method returns an integer object from any number or string.
# float
print("int(123.23) is:", int(123.23))
# string
print("int('123') is:", int('123'))
Output
Example
mylist = [1, 2, 3, 4, 5]
x = len(mylist)
print(x)
Output
Sometimes when working with some kind of financial or scientific projects it becomes
necessary to implement mathematical calculations in the project. Python provides the
math module to deal with such calculations. Math module provides functions to deal with
both basic operations such as addition(+), subtraction(-), multiplication(*), division(/)
and advance operations like trigonometric, logarithmic, exponential functions.
pow() function computes x**y. This function first converts its arguments into float and
then computes the power.
Example:
# version 1
# Returns 81
print (pow(3,4))
Output
# fabs()
import math
a = -10
# returning the absolute value.
print (math.fabs(a))
Output
# sqrt() method
import math
print(math.sqrt(0))
print(math.sqrt(4))
print(math.sqrt(3.5))
Output
0.0
2.0
1.8708286933869707
import math
print (math.isinf(math.pi))
Output
False
math.factorial() function
import math
x=5
print (math.factorial(x))
Output
120
Python Random Module
# import random
import random
Output
2
Output
Syntax: random.random()
# import random
from random import random
Output
0.3717933555623072
import random
Output
5
Example 2: Python random.sample() function is used to return a random item
from a list, tuple, or string.
# import random
from random import sample
print(sample(list1,3))
print(sample(list2,3))
print(sample(list3,3))
Output
[1, 5, 4]
[8, 5, 6]
# declare a list
sample_list = [1, 2, 3, 4, 5]
# first shuffle
random.shuffle(sample_list)
print("\nAfter the first shuffle : ")
print(sample_list)
# second shuffle
random.shuffle(sample_list)
print("\nAfter the second shuffle : ")
print(sample_list)
Output:
Original list :
[1, 2, 3, 4, 5]
[4, 3, 5, 2, 1]
[1, 3, 4, 5, 2]
Python Random uniform() Method
Example
Return a random number between, and included, 20 and 60:
import random
print(random.uniform(20, 60))
import random
print(random.randrange(3, 9))
Example
Return a list that contains any 2 of the items from a list:
import random
print(random.sample(mylist, k=2))
Output
['apple', 'cherry']
Conditional Statement
Decision making is required when we want to execute a code only if a certain condition is
satisfied.
if test expression:
statement(s)
Here, the program evaluates the test expression and will execute statement(s) only if the
test expression is True.
If the test expression is False, the statement(s) is not executed.
In Python, the body of the if statement is indicated by the indentation. The body starts
with an indentation and the first unindented line marks the end.
Python interprets non-zero values as True. None and 0 are interpreted as False.
Example: Python if Statement
num = 3
if num > 0:
print(num, "is a positive number.")
print("This is always printed.")
num = -1
if num > 0:
print(num, "is a positive number.")
print("This is also always printed.")
3 is a positive number
This is always printed
This is also always printed.
Syntax of if...else
if test expression:
Body of if
else:
Body of else
The if..else statement evaluates test expression and will execute the body of if only when
the test condition is True.
If the condition is False, the body of else is executed. Indentation is used to separate the
blocks.
Example of if...else
num = 3
if num >= 0:
print("Positive or Zero")
else:
print("Negative number")
Output
Positive or Zero
In the above example, when num is equal to 3, the test expression is true and the body
of if is executed and the body of else is skipped.
If num is equal to -5, the test expression is false and the body of else is executed and the
body of if is skipped.
If num is equal to 0, the test expression is true and body of if is executed and body of
else is skipped.
Syntax of if...elif...else
if test expression:
Body of if
Body of elif
else:
Body of else
The elif is short for else if. It allows us to check for multiple expressions.
If the condition for if is False, it checks the condition of the next elif block and so on.
If all the conditions are False, the body of else is executed.
Only one block among the several if...elif...else blocks is executed according to the
condition.
The if block can have only one else block. But it can have multiple elif blocks.
statement in Python
Example of if...elif...else
num = 3.4
if num > 0:
print("Positive number")
elif num == 0:
print("Zero")
else:
print("Negative number")
Output 1
Enter a number: 5
Positive number
Output 2
Enter a number: -1
Negative number
Output 3
Enter a number: 0
Zero
Ternary Operator
Ternary operators provide a shorthand way to write conditional statements, which makes
the code more concise. Its just if-else condition in a single line
The ternary operator evaluates the condition first. If the result is true, it returns
the value_if_true. Otherwise, it returns value_if_false
For example
Program
s = 10
If s > 5:
Print(“Yes”) //option 1
else:
Print(“No”) //option 2
Print(A)
Another Example
Example
Print each fruit in a fruit list:
Output
apple
banana
cherry
Example
Loop through the letters in the word "banana":
for x in "banana":
print(x)
Output
b
a
n
a
n
a
The break Statement
With the break statement we can stop the loop before it has looped through all the items:
Example
Exit the loop when x is "banana":
Example
Exit the loop when x is "banana", but this time the break comes before the print:
The range() function returns a sequence of numbers, starting from 0 by default, and
increments by 1 (by default), and ends at a specified number.
Example
Using the range() function:
for x in range(6):
print(x)
Output
0
1
2
3
4
5
Example
Using the start parameter:
Output
2
3
4
5
Example
Increment the sequence with 3 (default is 1):
Output
2
5
8
11
14
17
20
23
26
29
Else in For Loop
The else keyword in a for loop specifies a block of code to be executed when the loop is
finished:
Example
Print all numbers from 0 to 5, and print a message when the loop has ended:
for x in range(6):
print(x)
else:
print("Finally finished!")
Output
0
1
2
3
4
5
Finally finished!
Note: The else block will NOT be executed if the loop is stopped by a break statement.
Example
Break the loop when x is 3, and see what happens with the else block:
for x in range(6):
if x == 3: break
print(x)
else:
print("Finally finished!")
Output
0
1
2
Nested Loops
A nested loop is a loop inside a loop.
Example
Print each adjective for every fruit:
for x in adj:
for y in fruits:
print(x, y)
Output
red apple
red banana
red cherry
big apple
big banana
big cherry
tasty apple
tasty banana
tasty cherry
Example
for x in [0, 1, 2]:
pass
Output
Nothing
Example
Print i as long as i is less than 6:
i=1
while i < 6:
print(i)
i += 1
Output
1
2
3
4
5
Note: remember to increment i, or else the loop will continue forever.
The while loop requires relevant variables to be ready, in this example we need to define an
indexing variable, i, which we set to 1.
Example
Exit the loop when i is 3:
i=1
while i < 6:
print(i)
if i == 3:
break
i += 1
Output
1
2
3
Example
Continue to the next iteration if i is 3:
i=0
while i < 6:
i += 1
if i == 3:
continue
print(i)
Output
1
2
4
5
6
The else Statement
With the else statement we can run a block of code once when the condition no longer is
true:
Example
Print a message once the condition is false:
i=1
while i < 6:
print(i)
i += 1
else:
print("i is no longer less than 6")
Output
1
2
3
4
5
i is no longer less than 6
Python Functions
A function is a block of code which only runs when it is called.
Creating a Function
In Python a function is defined using the def keyword:
Example
def my_function():
print("Hello from a function")
Calling a Function
To call a function, use the function name followed by parenthesis:
def my_function():
print("Hello from a function")
my_function()
Arguments
Information can be passed into functions as arguments.
Arguments are specified after the function name, inside the parentheses. You
can add as many arguments as you want, just separate them with a comma.
The following example has a function with one argument (fname). When the
function is called, we pass along a first name, which is used inside the function
to print the full name:
def my_function(fname):
print(fname + " Refsnes")
my_function("Emil")
my_function("Tobias")
my_function("Linus")
Parameters or Arguments?
A parameter is the variable listed inside the parentheses in the function
definition.
Number of Arguments
By default, a function must be called with the correct number of arguments.
Meaning that if your function expects 2 arguments, you have to call the function
with 2 arguments, not more, and not less.
Example
This function expects 2 arguments, and gets 2 arguments:
my_function("Emil", "Refsnes")
If you try to call the function with 1 or 3 arguments, you will get an error:
Example
This function expects 2 arguments, but gets only 1:
my_function("Emil")
Arbitrary Arguments, *args
If you do not know how many arguments that will be passed into your function,
add a * before the parameter name in the function definition.
Example
If the number of arguments is unknown, add a * before the parameter name:
def my_function(*kids):
print("The youngest child is " + kids[2])
Keyword Arguments
You can also send arguments with the key = value syntax.
Example
def my_function(child3, child2, child1):
print("The youngest child is " + child3)
Example
If the number of keyword arguments is unknown, add a double ** before the
parameter name:
def my_function(**kid):
print("His last name is " + kid["lname"])
Example
def my_function(country = "Norway"):
print("I am from " + country)
my_function("Sweden")
my_function("India")
my_function()
my_function("Brazil")
E.g. if you send a List as an argument, it will still be a List when it reaches the
function:
Example
def my_function(food):
for x in food:
print(x)
my_function(fruits)
Return Values
To let a function return a value, use the return statement:
Example
def my_function(x):
return 5 * x
print(my_function(3))
print(my_function(5))
print(my_function(9))
Example
def myfunction():
pass
Python Classes and Objects
Python is an object oriented programming language.
Create a Class
To create a class, use the keyword class:
Example
Create a class named MyClass, with a property named x:
class MyClass:
x = 5
Create Object
Now we can use the class named MyClass to create objects:
Example
Create an object named p1, and print the value of x:
p1 = MyClass()
print(p1.x)
All classes have a function called __init__(), which is always executed when the
class is being initiated.
Use the __init__() function to assign values to object properties, or other
operations that are necessary to do when the object is being created:
Example
Create a class named Person, use the __init__() function to assign values for
name and age:
class Person:
def __init__(self, name, age):
self.name = name
self.age = age
p1 = Person("John", 36)
print(p1.name)
print(p1.age)
Note: The __init__() function is called automatically every time the class is
being used to create a new object.
Note: The self parameter is a reference to the current instance of the class,
and is used to access variables that belong to the class.
Object Methods
Objects can also contain methods. Methods in objects are functions that belong
to the object.
Example
Insert a function that prints a greeting, and execute it on the p1 object:
class Person:
def __init__(self, name, age):
self.name = name
self.age = age
def myfunc(self):
print("Hello my name is " + self.name)
p1 = Person("John", 36)
p1.myfunc()
It does not have to be named self , you can call it whatever you like, but it has
to be the first parameter of any function in the class:
Example
Use the words mysillyobject and abc instead of self:
class Person:
def __init__(mysillyobject, name, age):
mysillyobject.name = name
mysillyobject.age = age
def myfunc(abc):
print("Hello my name is " + abc.name)
p1 = Person("John", 36)
p1.myfunc()
Example
Set the age of p1 to 40:
p1.age = 40
Example
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.age = 40
print(p1.age)
Example
Delete the age property from the p1 object:
del p1.age
Example
class Person:
self.name = name
self.age = age
def myfunc(self):
p1 = Person("John", 36)
del p1.age
print(p1.age)
Output
Traceback (most recent call last):
File "demo_class7.py", line 13, in <module>
print(p1.age)
AttributeError: 'Person' object has no attribute 'age'
Delete Objects
You can delete objects by using the del keyword:
Example
Delete the p1 object:
del p1
Example
class Person:
self.name = name
self.age = age
def myfunc(self):
del p1
print(p1)
Output
Traceback (most recent call last):
File "demo_class8.py", line 13, in <module>
print(p1)
NameError: 'p1' is not defined
Example
class Person:
pass
Abstraction
Abstract Class
Syntax
From abc import ABC
Class d(ABC):
@abstractmethod
Def function2(self): #child class will implement this method body
Example
From abc import ABC, abstractmethod
Class Car(ABC):
Def show(self):
@abstractmethod
Def speed(self):
pass #this method should be abstract because, we
want to implement car speed but we dnt know
which car speed
class Suzuki(Car):
def speed(self):
class Toyota(Car):
def speed(self):
obj = Suzuki()
obj.show()
obj.speed()
obj2 = Toyota()
obj2.show()
obj2.speed()
Data Encapsulation
When we have data members and function members inside a class and if we
make data members private, its called encapsulation
Public access
Public variables and methods are those that can be accessed by any part of the
program. In Python, variables and methods are public by default, and they do
not require any special keyword to be declared as public.
Example:
class Car:
color = "red"
def start(self):
print("Car started!")
In the above example, the “color” variable and the “start” method are public
and can be accessed by any part of the program.
Private access
Private variables and methods are those that can only be accessed within the
class. In Python, private variables and methods are declared by prefixing them
with double underscores (__).
Example:
class Car:
__engine_capacity = "2000cc"
def __start_engine(self):
print("Engine started!")
Protected access
Protected variables and methods are those that can be accessed within the class
and its subclasses. In Python, protected variables and methods are declared by
prefixing them with a single underscore (_).
Example:
class Car:
_mileage = 0
def _drive(self):
self._mileage += 10
In the above example, the “_mileage” variable and the “_drive” method are
protected and can be accessed within the “Car” class and its subclasses.
Private access Example
As mentioned earlier, private variables and methods in Python are declared by
prefixing them with double underscores (__). Private variables cannot be
accessed outside the class, and private methods can only be called from within
the class.
Example:
class Person:
__name = "John"
def __greet(self):
p = Person()
Example
class Animal:
_legs = 4
def _walk(self):
print("Animal is walking")
class Dog(Animal):
def bark(self):
print("Woof!")
d = Dog()
d._walk() # this will call the _walk method from the Animal class
Example:
class Person:
__name = "John"
def get_name(self):
return self.__name
self.__name = name
p = Person()
p.set_name("Mike")
By default, python provides the access to all the data members and methods
but with the help of encapsulation, you can prevent the variables and methods
access by making them private or protected.
To make them protected, we use single underscore and to make them private,
we use double underscore
Example
class Test:
__b = 20 #private
#if a class has private and protected members, then it is called encapsulation
def show(self):
print(self._a)
print(self.__b)
obj.show()
Output
10
20
#because, obj is the object of Test class, so it can access public method show,
and that show method can access the private and protected members of class,
thats why we are getting the result (indirectly using show function)
and if we want to access protected member (a) outside the class using obj, we
can access it
In inheritance, the child class acquires the properties and can access all the data members
and functions defined in the parent class.
In python, a derived class can inherit base class by just mentioning the base in the
bracket after the derived class name.
Syntax
1. class derived-class(base class):
A class can inherit multiple classes by mentioning all of them inside the bracket. Consider the
following syntax.
Syntax
1. class derive-class(<base class 1>, <base class 2>, ..... <base class n>):
Example
1. class Animal:
2. def speak(self):
3. print("Animal Speaking")
4. #child class Dog inherits the base class Animal
5. class Dog(Animal):
6. def bark(self):
7. print("dog barking")
8. d = Dog()
9. d.bark()
10. d.speak()
Output:
dog barking
Animal Speaking
Syntax
class class1:
class class2(class1):
class class3(class2):
Example
1. class Animal:
2. def speak(self):
3. print("Animal Speaking")
4. #The child class Dog inherits the base class Animal
5. class Dog(Animal):
6. def bark(self):
7. print("dog barking")
8. #The child class Dogchild inherits another child class Dog
9. class DogChild(Dog):
10. def eat(self):
11. print("Eating bread...")
12. d = DogChild()
13. d.bark()
14. d.speak()
15. d.eat()
Output:
dog barking
Animal Speaking
Eating bread...
Syntax
class Base1:
class Base2:
.
.
.
class BaseN:
Output:
30
200
0.5
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.
Function Polymorphism
An example of a Python function that can be used on different objects is
the len() function.
String
For strings len() returns the number of characters:
Example
x = "Hello World!"
print(len(x))
Tuple
For tuples len() returns the number of items in the tuple:
Example
mytuple = ("apple", "banana", "cherry")
print(len(mytuple))
Dictionary
For dictionaries len() returns the number of key/value pairs in the dictionary:
Example
thisdict = {
"brand": "Ford",
"model": "Mustang",
"year": 1964
}
print(len(thisdict))
Class Polymorphism
Polymorphism is often used in Class methods, where we can have multiple
classes with the same method name.
For example, say we have three classes: Car, Boat, and Plane, and they all have a
method called move():
Example
Different classes with the same method:
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.move()
boat1.move()
plane1.move()
Output:
Drive!
Sail!
Fly!
What is Machine Learning
In the real world, we are surrounded by humans who can learn everything from
their experiences with their learning capability, and we have computers or
machines which work on our instructions. But can a machine also learn from
experiences or past data like a human does? So here comes the role of Machine
Learning.
A machine can learn if it can gain more data to improve its performance.
• Supervised learning
• Unsupervised learning
• Reinforcement learning
1) Supervised Learning
In supervised learning, sample labeled data are provided to the machine
learning system for training, and the system then predicts the output based on
the training data.
The system uses labeled data to build a model that understands the datasets
and learns about each one. After the training and processing are done, we test
the model with sample data to see if it can accurately predict the output.
Here, you start by creating a set of labeled data. This data includes:
• Weather conditions
• Time of the day
• Holidays
All these details are your inputs in this Supervised learning example. The
output is the amount of time it took to drive back home on that specific
day.
• Classification
• Regression
Regression and Classification algorithms are Supervised Learning algorithms. Both the
algorithms are used for prediction in Machine learning and work with the labeled
datasets. But the difference between both is how they are used for different machine
learning problems.
The main difference between Regression and Classification algorithms that Regression
algorithms are used to predict the continuous values (Continuous data is data that can
take any value. Height, weight, temperature and length are all examples of continuous
data. Some continuous data will change over time; the weight of a baby in its first year
or the temperature in a room throughout the day. This data is best shown on a line
graph as this type of graph can show how the data changes over a given period of
time.) such as price, salary, age, etc. and Classification algorithms are used
to predict/Classify the discrete values (Discrete data is information that can only take
certain values. These values don’t have to be whole numbers (a child might have a
shoe size of 3.5 or a company may make a profit of £3456.25 for example) but they are
fixed values – a child cannot have a shoe size of 3.72!
The number of each type of treatment a salon needs to schedule for the week, the
number of children attending a nursery each day or the profit a business makes each
month are all examples of discrete data. This type of data is often represented using
tally charts, bar charts or pie charts.) such as Male or Female, True or False, Spam or Not
Spam, etc.
Unsupervised Learning
Unsupervised learning is a learning method in which a machine learns without
any supervision.
The training is provided to the machine with the set of data that has not been
labeled, classified, or categorized, and the algorithm needs to act on that data
without any supervision. The goal of unsupervised learning is to restructure the
input data into a group of objects with similar patterns.
In this, the machine tries to find useful insights from the huge amount of data.
It can be further classifieds into two categories of algorithms:
Reinforcement Learning
Reinforcement learning is a feedback-based learning method, in which a
learning agent gets a reward for each right action and gets a penalty for each
wrong action. The agent learns automatically with these feedbacks and
improves its performance. In reinforcement learning, the agent interacts with
the environment and explores it. The goal of an agent is to get the most reward
points, and hence, it improves its performance.
The robotic dog, which automatically learns the movement of his arms, is an
example of Reinforcement learning.