Python_Notes_for_100_Days
Python_Notes_for_100_Days
Programming is a way for us to tell computers what to do. Computer is a very dumb machine and it
only does what we tell it to do. Hence we learn programming and tell computers to do what we are
very slow at - computation. If I ask you to calculate 5+6, you will immediately say 11. How about
23453453 X 56456?
You will start searching for a calculator or jump to a new tab to calculate the same. This 100 days of
code series will help you learn python from starting to the end. We will start from 0 and by the time
we end this course, I promise you will be a Job ready Python developer!
What is Python?
Features of Python
Python provides very big library support. Some of the popular libraries include NumPy, Tensorflow,
Python helps in Data Analytics to analyze and understand raw data for insights and trends.
It is used in AI and Machine Learning to simulate human behavior and to learn from past data
It is used in business and accounting to perform complex mathematical operations along with
Module is like a code library which can be used to borrow code written by somebody else in our
Built in Modules - These modules are ready to import and use and ships with the python interpreter.
External Modules - These modules are imported from a third party file or can be installed using a
package manager like pip or conda. Since this code is written by someone else, we can install
It can be used as a package manager to install a python module. Lets install a module called
We use the import syntax to import a module in Python. Here is an example code:
import pandas
df = pandas.read_csv('words.csv')
print(df) # This will display first few rows from the words.csv file
Similarly we can install other modules and look into their documentations for usage instructions.
We will find ourselved doing this often in the later part of this course
Python Comments
A comment is a part of the coding file that the programmer does not want to execute, rather the
programmer uses it to either explain a block of code or to avoid the execution of a specific part of
To insert characters that cannot be directly used in a string, we use an escape sequence character.
An escape sequence character is a backslash \ followed by the character you want to insert.
An example of a character that cannot be directly used in a string is a double quote inside a string
What is a variable?
Variable is like a container that holds data. Very similar to how our containers in kitchen holds sugar,
salt etc Creating a variable is like creating a placeholder in memory and assigning it some value. In
Data type specifies the type of value a variable holds. This is required in programming to do various
In python, we can print the type of any operator using type function:
int: 3, -8, 0
complex: 6 + 2i
2. Text data: str
3. Boolean data:
list: A list is an ordered collection of data with elements separated by a comma and enclosed within
square brackets. Lists are mutable and can be modified after creation.
dict: A dictionary is an unordered collection of data containing a key:value pair. The key:value pairs
Typecasting in python
The conversion of one data type into the other data type is known as type casting in python or type
conversion in python.
Python supports a wide variety of functions or methods like: int(), float(), str(), ord(), hex(), oct(),
tuple(), set(), list(), dict(), etc. for the type casting in python.
Explicit typecasting:
The conversion of one data type into another data type, done via developer or programmer's
It can be achieved with the help of Python?s built-in type conversion functions such as int(), float(),
Data types in Python do not have the same level i.e. ordering of data types is not the same in
Python. Some of the data types have higher-order, and some have lower order. While performing
any operations on variables with different data types in Python, one of the variable's data types will
be changed to the higher data type. According to the level, one data type is converted into other by
the Python interpreter itself (automatically). This is called, implicit typecasting in python.
Python converts a smaller data type to a higher data type to prevent data loss.
What are strings? In python, anything that you enclose between single or double quotation marks is
considered a string. A string is essentially a sequence or array of textual data. Strings are used
Multiline Strings
If our string has multiple lines, we can create them like this:
a = """ Hi I am ankit
print(a)
In Python, string is like an array of characters. We can access parts of string by using its index
print(name[0])
print(name[1])
Above code prints all the characters in the string name one by one!
Length of a String
fruit = "Banana"
Banana = len(fruit)
String as an array
A string is essentially a sequence of characters also called an array. Thus we can access the
Fruit = "Banana"
print(Fruit[0:7])
print(Fruit[0:])
Python provides a set of built-in methods that we can use to alter and modify the strings.
upper() :
lower()
print(a.lower())
strip() :
The strip() method removes any white spaces before and after the string.
print(a.strip())
rstrip() :
print(str3.rstrip("!"))
replace() :
The replace() method replaces all occurences of a string with another string. Example:
print(str2.replace("Sp", "M"))
capitalize() :
The capitalize() method turns only the first character of the string to uppercase and the rest other
characters of the string are turned to lowercase. The string has no effect if the first character is
already uppercase.
print(movie.capitalize())
center() :
The center() method aligns the string to the center as per the parameters given by the user.
print(str1.center(50))
print(str1.center(50, "."))
count() :
The count() method returns the number of times the given value has occurred within the given
string.
Example:
str2 = "Abracadabra"
countStr = str2.count("a")
print(countStr)
endswith() :
The endswith() method checks if the string ends with a given value. If yes then return True, else
return False.
Example :
print(str1.endswith("!!!"))
print(str1.endswith("to", 4, 10))
find() :
The find() method searches for the first occurrence of the given value and returns the index where it
is present. If given value is absent from the string then return -1.
Example:
print(str1.find("is"))
As we can see, this method is somewhat similar to the index() method. The major difference being
that index() raises an exception if value is absent whereas find() does not.
Example:
print(str1.find("Daniel"))
Output:
-1
index() :
The index() method searches for the first occurrence of the given value and returns the index where
it is present. If given value is absent from the string then raise an exception.
Example:
print(str1.index("Dan"))
Output:
13
As we can see, this method is somewhat similar to the find() method. The major difference being
that index() raises an exception if value is absent whereas find() does not.
Example:
print(str1.index("Daniel"))
Output:
isalnum() :
The isalnum() method returns True only if the entire string only consists of A-Z, a-z, 0-9. If any other
str1 = "WelcomeToTheConsole"
print(str1.isalnum())
Output:
True
isalpha() :
The isalnum() method returns True only if the entire string only consists of A-Z, a-z. If any other
Example :
str1 = "Welcome"
print(str1.isalpha())
Output:
True
islower() :
The islower() method returns True if all the characters in the string are lower case, else it returns
False.
Example:
print(str1.islower())
Output:
True
isprintable() :
The isprintable() method returns True if all the values within the given string are printable, if not, then
return False.
Example :
print(str1.isprintable())
Output:
True
isspace() :
The isspace() method returns True only and only if the string contains white spaces, else returns
False.
Example:
print(str1.isspace())
print(str2.isspace())
Output:
True
True
istitle() :
The istitile() returns True only if the first letter of each word of the string is capitalized, else it returns
False.
Example:
print(str1.istitle())
Output:
True
Example:
print(str2.istitle())
Output:
False
isupper() :
The isupper() method returns True if all the characters in the string are upper case, else it returns
False.
Example :
print(str1.isupper())
Output:
True
startswith() :
The endswith() method checks if the string starts with a given value. If yes then return True, else
return False.
Example :
print(str1.startswith("Python"))
Output:
True
swapcase() :
The swapcase() method changes the character casing of the string. Upper case are converted to
Example:
print(str1.swapcase())
Output:
title() :
The title() method capitalizes each letter of the word within the string.
Example:
print(str1.title())
Output:
if-else Statements
Sometimes the programmer needs to check the evaluation of certain expression(s), whether the
expression(s) evaluate to True or False. If the expression evaluates to False, then the program
execution follows a different path than it would have if the expression had evaluated to True.
Based on this, the conditional statements are further classified into following types:
if
if-else
if-else-elif
nested if-else-elif.
Execute the block of code inside if statement. After execution return to the code out of the if??else
block.\
Execute the block of code inside else statement. After execution return to the code out of the
if??else block.
Example:
applePrice = 210
budget = 200
else:
Output:
elif Statements
Sometimes, the programmer may want to evaluate more than one condition, this can be done using
an elif statement.
Execute the block of code inside if statement if the initial expression evaluates to True. After
Execute the block of code inside the second elif statement if the expression inside it evaluates True.
Execute the block of code inside the nth elif statement if the expression inside it evaluates True.
Execute the block of code inside else statement if none of the expression evaluates to True. After
Example:
num = 0
print("Number is negative.")
print("Number is Zero.")
else:
print("Number is positive.")
Output:
Number is Zero.
Nested if statements
We can use if, if-else, elif statements inside other if statements as well.
Example:
num = 18
print("Number is negative.")
else:
else:
print("Number is zero")
Output:
Match Case Statements : To implement switch-case like characteristics very similar to if-else
functionality, we use a match case in python. If you are coming from a C, C++ or Java like language,
you must have heard of switch-case statements. If this is your first language, don?t worry as I will
tell you everything you need to know about match case statements in this video!
A match statement will compare a given variable?s value to different shapes, also referred to as the
pattern. The main idea is to keep on comparing the variable with all the present patterns until it fits
into one.
The case clause consists of a pattern to be matched to the variable, a condition to be evaluated if
the pattern matches, and a set of statements to be executed if the pattern matches.
Syntax:
match variable_name:
Example:
x=4
match x:
# if x is 0
case 0:
print("x is zero")
case 4 if x % 2 == 0:
# default case(will only be matched if the above cases were not matched)
case _:
print(x)
Output:
x % 2 == 0 and case is 4
Introduction to Loops
Sometimes a programmer wants to execute a group of statements a certain number of times. This
can be done using loops. Based on this loops are further classified into following main types;
for loop
while loop
for loops can iterate over a sequence of iterable objects in python. Iterating over a sequence is
nothing but iterating over strings, lists, tuples, sets and dictionaries.
name = 'Abhishek'
for i in name:
Output:
A, b, h, i, s, h, e, k,
print(x)
Output:
Red
Green
Blue
Yellow
range():
What if we do not want to iterate over a sequence? What if we want to use for loop for a specific
number of times?
Example:
for k in range(5):
print(k)
Output:
Here, we can see that the loop starts from 0 by default and increments at each iteration.But we can
Output:
As the name suggests, while loops execute statements while the condition is True. As soon as the
condition becomes False, the interpreter comes out of the while loop.
Example:
count = 5
print(count)
count = count - 1
Output:
Here, the count variable is set to 5 which decrements after each iteration. Depending upon the while
loop condition, we need to either increment or decrement the counter variable (the variable count, in
our case) or the loop will continue forever.
We can even use the else statement with the while loop. Essentially what the else statement does is
that as soon as the while loop condition becomes False, the interpreter comes out of the while loop
Example:
x=5
print(x)
x=x-1
else:
print('counter is 0')
Output: 5
counter is 0
do..while is a loop in which a set of instructions will execute at least once (irrespective of the
condition) and then the repetition of loop's body will depend on the condition passed at the end of
The most common technique to emulate a do-while loop in Python is to use an infinite while loop
with a break statement wrapped in an if statement that checks a given condition and breaks the
Example
while True:
print(number)
break
Output
-1
Explanation
This loop uses True as its formal condition. This trick turns the loop into an infinite loop. Before the
conditional statement, the loop runs all the required processing and updates the breaking condition.
If this condition evaluates to true, then the break statement breaks out of the loop, and the program
The break statement enables a program to skip over a part of the code. A break statement
example
for i in range(1,101,1):
if(i==50):
break
else:
print("Mississippi")
print("Thank you")
output
1 Mississippi
2 Mississippi
3 Mississippi
4 Mississippi
5 Mississippi
50 Mississippi
Continue Statement
The continue statement skips the rest of the loop statements and causes the next iteration to occur.
example
for i in [2,3,4,6,8,0]:
if (i%2!=0):
continue
print(i)
output
Python Functions
A function is a block of code that performs a specific task whenever it is called. In bigger programs,
where we have large amounts of code, it is advisable to create or use existing functions that make
Built-in functions
User-defined functions
Built-in functions:
These functions are defined and pre-coded in python. Some examples of built-in functions are as
follows:
min(), max(), len(), sum(), type(), range(), dict(), list(), tuple(), set(), print(), etc.
User-defined functions:
We can create functions to perform specific tasks as per our needs. Such functions are called
user-defined functions.
Syntax:
def function_name(parameters):
pass
Create a function using the def keyword, followed by a function name, followed by a paranthesis (())
and a colon(:).
Any statements and other code within the function should be indented.
Calling a function:
We call a function by giving the function name, followed by parameters (if any) in the parenthesis.
Example:
name("Sam", "Wilson")
Output: