Python Notes
Python Notes
Every learner or organization must check whether their code is returning what
the programmer intended to return. For that people invented test cases. Their
purpose is to make sure that the program is doing what it meant to do. the test
cases test your code and they return a "Success" or "Fail" whether you returned
the right or wrong output.
The test cases check if the output matches EXACTLY to the expected
output
For example if the expected output is Hello and we try to print hello the test case
will fail because the first letter h must be uppercasea but we printed hello with a
lowercase letter.
Numbers
Variables are the reference name given to a value in your code.
Basically, you give a name to a value using variables.
For example,
a = 20
In Python, there are two types of numbers values:-
int - all the numbers, without decimals. e.g. 5, -3, 0, 1, 10, etc.
float - all the numbers, with decimals, 3.2 or -1.03
Note: We don't need to tell python about what types you are storing.
But, it's good if you know which type is being used.
String
As we previously understood about variables with number value, let's
learn about variables with string value now.
String Value is the combination of one or more characters written between
single quotation mark or double quotation mark.
Boolean
Boolean simply means either True or False.
These values are used to give a decision in conditional statements.
Storing a Boolean value in a variable is no different than numbers and strings.
You can store Boolean values like this,
a = True
or,
a = False
Arrays
Arrays are a combination of multiple same or different values.
In Python, we initiate an array with [], and inside these array brackets, we put
the values separated with a comma.
For example the following array contains strings (because every element inside
that array starts with ' and ends with '),
arr = ['a', 'b', 'c']
Another example is an array of integers
arr = [1, 2, 3]
Note: [1, 2, 3] and ['1', '2', '3'] are not the same! the first is an array of integers and
the second is an array of strings
Arithmetic operators
Arithmetic Operators are the symbols used to perform some mathematical
operations.
Some of the Arithmetic Operators are:
1. Addition: 10 + 9
2. Subtraction: 10 - 7
3. Multiplication: a * b
4. Division: 9 / 1
5. Modulus: 7 % 2
6. Exponentiation: 2 ** 3
Note: Modulus gives you the remainder which comes from dividing the first
value from the second.
E.g.
7 % 2 will be 1 because:
When we divide 7 with 2, we can divide up to 6 and 1 remains as a remainder.
Assignment operators
These are the operators which assign one value to a variable.
Let's discuss some of the assignment operators.
1. = - This simply assigns the value in the right side to the left side variable.
E.g. a = 1
2. += - This adds the right-side value to the left-side value and then assigns
it. E.g. a += 1 means, a = a + 1.
3. -= - This subtracts the right-side value to the left-side value and then
assigns it. E.g. a -= 1 means, a = a - 1.
4. *= - This multiplies the right-side value to the left-side value and then
assigns it. E.g. a *= 2 means, a = a * 2.
Let's see a Python code using these assignment operators.
a = 10
b = 2
a += 1
print(a)
A will store 11 after running this code
This will firstly assign 10 and 2 to a and b respectively.
Then it adds 1 to a which becomes 11, and assigns this new value to a.
Comparison operators
The word itself says "comparison" which means to compare between two
different values.
There are multiple ways to compare the values in python. Some are:
Less Than < - E.g. 6 < 7
Greater Than > - E.g. 7 > 8
Is Equal To == - E.g. 6 == 6
Is Not Equal To != - E.g. 6 != 5
All these comparisons return the Boolean Values. Remember? True or False?
For example:
a = 10
print(a != 10)
This will print False because the statement a != 10, is not correct.
Logical operators
Logical Operators are used to operate between two Boolean Values.
This means if you have two Boolean values you want to compare with, logical
operator has got you covered.
There is something called the Truth Table, which will give you an
understanding of what the output of certain logical operator will be.
Truth Table - OR
True or True -> True
True or False -> True
False or True -> True
False or False -> False
If you analyze this, even if one value is True, or operator returns True.
If Else
Whenever we have to do conditional activities, we use conditional
statements, also known as If...Elif...Else.
For example, imagine that you want to ask the user whether he is 18+ or not, if
yes, you want to perform a certain activity, if not, you don't.
In such cases where you need to work out with test cases and conditions, these
statements come into play.
The syntax of the conditional statement is pretty simple,
if condition1:
perform_something
elif condition2:
perform_something
else:
perform_something
While loop
The repetition of a certain code is known as a loop. There are two main ways to
perform looping in Python.
The first is while loop. The second is for loop.
The main thing that separates while from the for loop is that while loop
uses conditions to repeat the code.
The syntax of while loop is,
while condition1:
the_code_to_repeat
The way while loop works are that it keeps repeating the code until the
condition becomes False.
Therefore, we usually make a logic to end the loop by making the
condition go False after running some rounds.
For example,
c = 0
while c < 10:
print(c)
c+=1
c += 1 incrementing the c by 1.
So, what we are doing in this code is that in the first round, c < 10 is True, but we
are incrementing c every time, and eventually in the 10th round, c will be 11 and
then c < 10 will become False, and the while loop will eventually stop.
For loop
For loop is another way to perform looping or repetition of code in Python.
We don't use conditions in for loop, but we use, looping variable with a set
of elements to loop with.
Let us understand this with an example and sytax.
for i in 'Hello':
print(i)
The output of this code will be:
H
e
l
l
o
Basically, it goes through all the elements in the string 'Hello' and i is the
temporary looping variable that carries individual element in every
round.
Break
In order to manipulate the looping rounds, we can use the break and/or
continue.
break is usually used to stop the loop permanently. This means that the use of
this will terminate the loop. Example,
for i in range(5):
if i == 3:
break
else:
print(i)
The output of this code will be:
0
1
2
In round 3, the if condition will be valid and it will terminate the
consecutive rounds, because of the use of break.
Continue
Contrary to break, continue, however, is used to skip the current round only.
Example,
for i in range(5):
if i == 3:
continue
else:
print(i)
The output of this code will be:
0
1
2
4
In round 3, the if condition will be valid and it will skip the current round,
because of the use of continue.
Functions
The use of functions in programming is known as Functional
Programming.
Function literally means a certain method that performs a particular action.
Similarly, in programming, functions are a set of code that are put
together to perform a particular action.
Or, you can also understand functions as giving some name to the code.
The syntax of functions in Python is:
def function_name():
#BLOCK_OF_CODE
You can name the function as you want.
After you define a function with the above code, you also have to call it. To
call a function, simply write the name of the function with parenthesis (). E.g.
function_name()
Now that you know the syntax of a function. Let's now see how you can do
functional programming to create a simple Hello World program.
def hello_world():
print("Hello World!")
hello_world()
Arguments
Function originally comes from mathematics and in mathematics, functions
are just like formulas. One of the popular mathematical functions is:
f(x) = mx + c
The x inside f(x) is
known as argument or parameter. This is an input given
to a function to calculate it's output. If we write a code based off this
mathematical function, it would look like this,
def f(x):
m = 1
c = 1
y = m * x + c
print(y)
f(7)
Arguments/Parameters are the input values based on which the function is
written. You can pass more parameters separated with commas. E.g.
function(a, b, c)
Return
With parameters, we understood how to take input values into a function.
return however, is used in order to out a value to a function.
Let's take the same example as before
def f(x):
m = 1
c = 1
y = m * x + c
return y
return will just
send back the value to the function instead of printing it to the
console. That is why you might have to print the function when you call it. E.g.
print(f(7))
Recursion
Recursion means to repeat something by calling itself. Recursion, in
programming, is done by using functions.
To understand this simply, it's a process of calling a function within the
same function.
First let's see an easy example:
def recur(n):
if n == 0:
return
print(n)
recur(n-1) # Call itself with n-1
First we check if n == 0. This
is called stop condition. If we neglect the stop
condition and remove it, the function will call itself infinite times and it will
never stop.
Than we print the number n and after that we call the same function but this
time with n-1
The output example:
recur(3)
Output:
3
2
1
A more complex example:
def sum_all(n):
if n == 0:
return 0
return n + sum_all(n-1)
This example shows how to sum all the numbers from 1 to n
for the input 5 the program will execute:
sum_all(5)
5 + sum_all(4) + sum_all(3) + sum_all(2) + sum_all(1) + sum_all(0) # <-- stops
Scope
The concept of scope is that a variable is only available inside the
region it is created.
Basically, there are two scopes in Python:
1. local
2. global
local and global variables in Python code would look like this
b = 200
def f():
a = 300
print(a)
f()
print(b)
In this case, if you had used print(a) outside the function, it would throw us a
SyntaxError. This is because a is a local variable assigned within a function.
However b can be used wherever necessary. This is because b is a global
variable assigned in the main code.
It is also possible to change a local variable to a global variable. To do this, you
should use a global keyword before assigning it.
Now, let's see what its' code would look like,
def f():
global a
a = 300
f()
print(a)
Since, a iscalled a global variable, it will work even outside the function as well
as inside the function.
Input
In Python, you can take user's input using input() function. Inside it you can
pass an argument of an instruction.
For example,
name = input("Enter your name: ")
This will print to the console Enter your name: and the program will wait until the
user types any string he wants. after pressing enter the program will store that
string inside the name variable.
Note: In Coddy, the input() method doesn't wait for the user to enter anything
but rather is takes the input from the test cases and stores it inside the
variables
Output
Outputting some value in Python is pretty easy. In fact, you have been doing it
already.
There are two types of output in Python. They are:
1. Functional Output
2. Console Output
Functional Output
return is a functional output. This means the return is used to output some value
to a function.
Console Output
print() is a console output. It is used in order to display some value to the
console.
Cast
What happens when we want to treat a number: 158 as a string rather than an
integer?
For example when combining two integerss together the output would be the
sum of the numbers: 15 + 15 = 30, but if these numbers are strings then the
output is different: "15" + "15" = "1515". Managing and monitoring the types of the
variables is critical for having a healthy program.
Changing the type of the variable is called Cast i.e. Casting.
To convert an integer to a string use the str() function:
a = str(5)
a = 5
a = str(a)
To convert a string to integer use the int() function:
a = int("5")
a = "5"
a = int("5")
Warning: converting a non string number to integer will fail and will result
an error:
int("abc") --> ERROR
Class
Classes are the main part where the "class code" is written.
Think of classes as blueprints of an object.
If a "car" is an object, the blueprint that the engineer creates for that car's
specs is the class of its object.
Now, let's see the syntax of class in OOP.
class Car:
manufacturer = "Lamborghini"
build_date = 2020
The class definition is very simple,
you write class and then your class name.
The good thing about the class is that all the variables in them have a
global scope, meaning, they can be accessed from anywhere within that
program.
Object
You just created a blueprint with Class. Now, you can create an object out
of that blueprint.
For example, we had our blueprint for a car. The object of that car would look
like this:
class Car:
manufacturer = "Lamborghini"
build_date = 2020
huracan = Car()
You simply call and store that class name with parenthesis () to an object. In
the above case, huracan is the object.
You can access the variables stored inside the class using dot notation (.).
print(huracan.manufacturer)
Methods
Methods are the functions created within the class.
The important thing to remember here is that every method in a class
takes self as a parameter when defining. This is a no-brainer and you must
always take care of it. Let's see its syntax:
class Car:
manufacturer = "Lamborghini"
build_date = 2020
def print_info(self):
print("Manufacturer:", self.manufacturer)
print("Build:", self.build_date)
You can access the method through the object like this; using dot notation (.)
huracan = Car()
huracan.print_info()
A thing to note is, for every class variable we have to use it with dot notation on
self. i.e. self.YOUR_CLASS_VARIABLE.
Class Variable
Class Variables are any variables that we can find within a class. A point to
remember is that the class variable isn't inside any methods but in the main
class.
Let's look at what they would look like,
class Car:
class_variable_1 = "Hello World"
class_variable_2 = 20
def method(self):
...
You can access class variables within the class with the use of dot notation on
self, i.e. self.YOUR_CLASS_VARIABLE
You can access class variables outside the class with the use of dot notation on
a class object, i.e. object.YOUR_CLASS_VARIABLE E.g:
huracan = Car()
huracan.YOUR_CLASS_VARIABLE
Init Method
One of the crucial types of method in OOP (Object Oriented Programming)
is __init__().
Basically, this init method gets initialized at the time of creating the objects,
technically known as instantiation.
The syntax of init method in the class is:
class Car:
def __init__(self, parameters):
# code to initialize
Using __init__, you can create some initial values to be stored as well. You can
also take parameters inside it to make it more dynamic.
A small example code of this is:
class Sports:
def __init__(self, sports_name, sports_type):
self.name = sports_name
self.type= sports_type
golf = Sports("Golf", "Hand Sports")
print(golf.name)
print(golf.type)