Python Dev Basic Notes
Python Dev Basic Notes
Python Dev Basic Notes
What is Programming?
Just like we use Hindi or English to communicate with each other, we use a Programming language to
communicate with the computer.
What is Python?
Python is a simple and easy-to-understand language that feels like reading simple English. This Pseudo
code nature of Python makes it easy to learn and understandable for beginners.
Features of Python:
Easy to understand = Less development time
High-level language
Create a file called hello.py and paste the below code into it
Copy
Execute this file (.py file) by typing python hello.py, and you will see Hello World printed on the screen.
Modules
A module is a file containing code written by somebody else (usually) which can be imported and used in
our programs.
Pip
Pip is a package manager for python. You can use pip to install a module on your system.
E.g., pip install flask (It will install flask module in your system)
Types of modules
import os
print(directory)
If you want import specific part to module and not whole module, then use below syntax
We can use python as a calculator by typing “python” + TO DO on the terminal. [It opens REPL or read
evaluation print loop]
Comments
Comments are used to write something which the programmer does not want to execute.
Types of Comments:
There are two types of comments in python,
2. Multi-line comments – Written using ‘’’ Comment ‘’’ or “”” Comment “””.
**
***
****
*****
3. Install an external module and use it to perform an operation of your interest. (External module)
4. Write a python program to print the contents of a directory using os module. Search online for
the function which does that. (internal Module)
a=30
b=”Harry”
c=71.22
d = True
d=False
Variable – Container to store a value
Data Types:
1. Integers
3. Strings
4. Booleans
5. None
Python is a fantastic language that automatically identifies the type of data for us.
a = 71 #Identifies a as class<int>
Operators in Python
type function is used to find the data type of a given variable in Python.
a = 31
type(a) #class<int>
b = “31”
type(b) #class<str>
Typecasting –
A number can be converted into a string and vice versa (if possible)
There are many functions to convert one data type into another.
input() function
This function allows the user to take input from the keyboard as a string.
Note: The output of the input function is always a string even if the number is entered by the user.
Suppose if a user enters 34, then this 34 will automatically convert to “34” string literal.
2. Write a Python program to find the remainder when a number is divided by Z(Integer).
3. Check the type of the variable assigned using the input() function.
4. Use a comparison operator to find out whether a given variable a is greater than b or not. (Take
a=34 and b=80)
5. Write a Python program to find the average of two numbers entered by the user.
6.
7. Write a Python program to calculate the square of a number entered by the user.
Chapter 3 – Strings
The string is a data type in Python.
String Slicing:
The index in a string starts from 0 to (length-1) in Python. To slice a string, we use the following syntax:
Negative Indices: Negative indices can also be used as shown in the figure above. -1 corresponds to the
(length-1) index, -2 to (length-2).
word = “amazing”
word = ‘amazing’
String Functions
Some of the most used functions to perform operations on or manipulate strings are:
len(‘harry’) #Returns 5
2. endswith(“rry”) : This function tells whether the variable string ends with the string “rry” or not.
If string is “harry”, it returns for “rry” since harry ends with rry.
5. find(word) : This function finds a word and returns the index of first occurrence of that word in
the string.
6. replace(oldword, newword) : This function replaces the old word with the new word in the
entire string.
Escape Sequence Characters comprises of more than one character but represents one character when
used within the string.
1. Write a Python program to display a user-entered name followed by Good Afternoon using
input() function.
2. Write a program to fill in a letter template given below with name and date.
<|DATE|>
Copy
3. Write a program to detect double spaces in a string.
5. Write a program to format the following letter using escape sequence characters.
The list can contain different types of elements such as int, float, string, Boolean, etc. Above list is a
collection of different types of elements.
List Indexing
L1 = [7, 9, ‘harry’]
L1[0] – 7
L1[1] – 9
L1[70] – Error
Copy
5. pop(2) – It will delete the element at index 2 and return its value
For example, when connecting multiple tuples with + operator, note that if you try to add one element
and forget a comma ,, an error will occur.
# print((0, 1, 2) + (3)) #invalid
# TypeError: can only concatenate tuple (not "int") to tuple
The reason why you need a comma , for a single tuple is that "tuple is an object delimited by comma ,",
not "an object enclosed in parentheses ()".
Note that it is actually the comma which makes a tuple, not the parentheses. The parentheses are
optional, except in the empty tuple case, or when they are needed to avoid syntactic ambiguity. but are
required when creating an empty tuple.
print(empty_tuple)
print(type(empty_tuple))
# ()
# <class 'tuple'>
# empty_tuple_error =
# SyntaxError: invalid syntax
# empty_tuple_error = ,
# SyntaxError: invalid syntax
# empty_tuple_error = (,)
# SyntaxError: invalid syntax
empty_tuple = tuple()
print(empty_tuple)
print(type(empty_tuple))
# ()
# <class 'tuple'>
Multiple arguments are specified by separating them with a comma ,. If you want to specify a tuple as
one argument, parentheses () are required.
Without parentheses (), each value is passed to each argument, and with parentheses (), a tuple is
passed to one argument.
def example(a, b):
print(a, type(a))
print(b, type(b))
example(0, 1)
# 0 <class 'int'>
# 1 <class 'int'>
# example((0, 1))
# TypeError: example() missing 1 required positional argument: 'b'
example((0, 1), 2)
# (0, 1) <class 'tuple'>
# 2 <class 'int'>
If you add * to the tuple, you can unpack the tuple and pass each element to each argument.
example(*(0, 1))
# 0 <class 'int'>
# 1 <class 'int'>
Tuple methods:
a = (1, 7, 2)
Copy
2. Write a program to accept the marks of 6 students and display them in a sorted manner.
a = (7, 0, 8, 0, 0, 9)
Chapter 5 – Dictionary and Sets
Syntax:
“harry”: “code”,
“marks” : “100”,
“list”: [1,2,9]}
1. It is unordered
2. It is mutable
3. It is indexed by key
Dictionary Methods
a = {“name”: “Harry”,
“from”: “India”,
“marks”: [92,98,96]}
1. items() : returns a list of (key,value) tuple.
4. get(“name”) : returns the value of the specified keys (and value is returned e.g., “Harry” is
returned here)
More methods are available on docs.python.org
Sets in Python
S.add(1)
S.add(2)
# or Set = {1,2}
If you are a programming beginner without much knowledge of mathematical operations on sets, you
can simply look at sets in python as data types containing unique values.
Properties of Sets
S = {1,8,2,3}
Copy
3. pop() : Removes an arbitrary (random) element from the set and returns the element removed.
5. union({8, 11}) : Returns a new set with all items from both sets. #{1,8,2,3,11}
6. intersection({8, 11}) : Returns a set which contains only items in both sets. #{8}
Chapter 5 – Practice Set
1. Write a program to create a dictionary of Hindi words with values as their English translation.
Provide the user with an option to look it up!
2. Write a program to input eight numbers from the user and display all the unique numbers
(once).
S = Set()
S.add(20)
S.add(20.0)
S.add(“20”)
Copy
6. Create an empty dictionary. Allow 4 friends to enter their favorite language as values and use
keys as their names. Assume that the names are unique.
7. If the names of 2 friends are the same; what will happen to the program in Program 6?
8. If the languages of two friends are the same; what will happen to the program in Program 6?
9. Can you change the values inside a list which is contained in set S
All these are decisions that depend on the condition being met.
In python programming too, we must be able to execute instructions on a condition(s) being met. This is
what conditions are for!
If else and elif statements are a multiway decision taken by our program due to certain conditions in our
code.
Syntax:
'''
print(“yes”)
print(“No”)
else: // otherwise
print(“May be”)
'''
Copy
Code example:
a = 22
if (a>9):
print(“Greater”)
else:
print(“lesser”)
>>> x = 0
>>> y = 5
>>> if x: # Falsy
... print('yes')
...
>>> if y: # Truthy
... print('yes')
...
yes
>>> if x or y: # Truthy
... print('yes')
...
yes
>>> if x and y: # Falsy
... print('yes')
...
Quick Quiz: Write a program to print yes when the age entered by the user is greater than or equal to
18.
Relational Operators
Relational operators are used to evaluate conditions inside if statements. Some examples of relational
operators are:
= = -> equals
<=, etc.
Copy
Logical Operators
Copy
elif clause
elif in python means [else if]. If statement can be chained together with a lot of these elif statements
followed by an else statement.
'''
if (condition1):
#code
#code
#code
….
else:
#code '''
Copy
Important Notes:
Last else is executed only if all the conditions inside elifs fail.
1. Write a program to find the greatest of four numbers entered by the user.
2. Write a program to find out whether a student is pass or fail if it requires a total of 40% and at
least 33% in each subject to pass. Assume 3 subjects and take marks as an input from the user.
“make a lot of money”, “buy now”, “subscribe this”, “click this”. Write a program to detect these spams.
4. Write a program to find whether a given username contains less than 10 characters or not.
5. Write a program that finds out whether a given name is present in a list or not.
6. Write a program to calculate the grade of a student from his marks from the following scheme:
90- E
100 x
80-90 A
70-80 B
60-70 C
50-60 D
<50 F
7. Write a program to find out whether a given post is talking about “Harry” or not.
Chapter 7 – Loops in Python
Sometimes we want to repeat a set of statements in our program. For instance: Print 1 to 1000
Loops make it easy for a programmer to tell the computer, which set of instructions to repeat, and how!
a loop is a sequence of instruction s that is continually repeated until a certain condition is reached.
Typically, a certain process is done, such as getting an item of data and changing it, and then some
condition is checked such as whether a counter has reached a prescribed number.
1. While loop
2. For loop
While loop
In while loops, the condition is checked first. If it evaluates to true, the body of the loop is executed,
otherwise not!
If the loop is entered, the process of condition check and execution is continued until the condition
becomes false.
An Example:
i=0
while i<5:
print(“Harry”)
i = i+1
Copy
Quick Quiz: Write a program to print the content of a list using while loops.
For loop
A for loop is used to iterate through a sequence like a list, tuple, or string (iterables)
l = [1, 7, 8]
for item in l:
print(item)
Copy
print(i) #prints 0 to 6
Copy
An optional else can be used with a for loop if the code is to be executed when the loop exhausts.
Example:
l = [1, 7, 8]
for item in l:
print(item)
else:
Copy
Output:
1
Done
Copy
‘break’ is used to come out of the loop when encountered. It instructs the program to – Exit the loop
now.
Example:
if i == 3:
break
Copy
‘continue’ is used to stop the current iteration of the loop and continue with the next one. It instructs
the program to “skip this iteration.”
Example:
for i in range(4):
print(“printing”)
continue
print(i)
Copy
pass statement
l = [1, 7, 8]
for item in l:
Copy
1. Write a program to print the multiplication table of a given number using for loop.
2. Write a program to greet all the person names stored in a list l1 and which starts with S.
Copy
5. Write a program to find the sum of first n natural numbers using a while loop.
6. Write a program to calculate the factorial of a given number using for loop.
***
Copy
**
*** for n = 3
Copy
* * #For n=3
***
Copy
10. Write a program to print the multiplication table of n using for loop in reversed order.
When a program gets bigger in size and its complexity grows, it gets difficult for a programmer to keep
track of which piece of code is doing what!
A function can be reused by the programmer in a given program any number of times.
def func1():
print(“Hello”)
Copy
This function can be called any number of times, anywhere in the program.
Function call
Whenever we want to call a function, we put the name of the function followed by parenthesis as
follows:
Copy
Function definition
The part containing the exact set of instructions that are executed during the function call.
Quick Quiz: Write a program to greet a user with “Good day” using functions.
A function can accept some values it can work with. We can put these values in the parenthesis. A
function can also return values as shown below:
def greet(name):
gr = “Hello” + name
return gr
Copy
Copy
If we specify name = “stranger” in the line containing def, this value is used when no argument is
passed.
For Example:
def greet(name=’stranger’):
#function body
Copy
Copy
Recursion
factorial(n) = n * factorial(n-1)
Copy
This function can be defined as follows:
def factorial(n):
return i
else:
Copy
The programmer needs to be extremely careful while working with recursion to ensure that the function
doesn’t infinitely keep calling itself.
1. Write a program using the function to find the greatest of three numbers.
3. How do you prevent a python print() function to print a new line at the end?
5. Write a python function to print the first n lines of the following pattern.
***
** #For n = 3
Copy
7. Write a python function to remove a given word from a list and strip it at the same time.
We all have played snake, water gun game in our childhood. If you haven’t, google the rules of this game
and write a Python program capable of playing this game with the user.
A file is data stored in a storage device. A python program can talk to the file by reading content from it
and writing content to it.
Types of Files
Python has a lot of functions for reading, updating, and deleting files.
Opening a file
Python has an open() function for opening files. It takes 2 parameters: filename and mode.
open(“this.txt”, “r”)
Copy
Here, “this” is the file name and “r” is the mode of opening (read mode)
Copy
Copy
We can also use f.readline() function to read one full line at a time.
Copy
w – open for writing, creates a new file if it does not exist or truncates the file if it exists.
x - Opens a file for exclusive creation. If the file already exists, the operation fails.
a – Opens a file for appending at the end of the file without truncating it.
In order to write to a file, we first open it in write or append mode, after which, we use the python’s
f.write() method to write to the file!
f = open(“this.txt”, “w”)
f.close()
Copy
With statement
The best way to open and close the file automatically is the “with” statement.
with open(“this.txt”) as f:
f.read()
Copy
1. Write a program to read the text from a given file, “poems.txt” and find out whether it contains
the word ‘twinkle’.
2. The game() function in a program lets a user play a game and returns the score as an integer.
You need to read a file “Hiscore.txt” which is either blank or contains the previous Hi-score. You
need to write a program to update the Hi-score whenever game() breaks the Hi-Score.
3. Write a program to generate multiplication tables from 2 to 20 and write it to the different files.
Place these files in a folder for a 13- year old boy.
4. A file contains the word “Donkey” multiple times. You need to write a program which replaces
this word with ###### by updating the same file.
6. Write a program to mine a log file and find out whether it contains ‘python’.
7. Write a program to find out the line number where python is present from question 6.
9. Write a program to find out whether a file is identical and matches the content of another file.
10. Write a program to wipe out the contents of a file using python.
Class
Copy
Object
Objects of a given class can invoke the methods available to it without revealing the implementation
details to the user. #Abstraction & Encapsulation!
Class Attributes
An attribute that belongs to the class rather than a particular object.
Class attributes are the variables defined directly in the class that are shared by all objects of the class.
Example:
Class Employee:
objEmployee.company
Copy
Instance Attributes
objEmployee.name = “Harry”
Note: Instance attributes take preference over class attributes during assignment and retrieval.
objEmployee.attribute1 :
Accessed using class name as well as using object with Accessed using object dot notation
dot notation, e.g. object.instance_attribute
e.g. classname.class_attribute or object.class_attribute
Changing value by using classname.class_attribute = Changing value of instance attribute will not be reflected to
value will be reflected to all the objects. other objects.
‘self’ parameter
harry.getSalary()
Copy
here, self is harry, and the above line of code is equivalent to Employee.getSalary(harry)
class Employee:
company = “Google”
def getSalary(self):
Copy
Static method
Static methods, much like class methods, are methods that are bound to a class rather than its object.
They do not require a class instance creation. So, they are not dependent on the state of the object.
Static method knows nothing about the class and just deals with the parameters.
Class method works with the class since its parameter is always the class itself.
def greet():
print(“Hello user”)
__init__() constructor
__init__() is a special method which runs as soon as the object is created.
The task of constructors is to initialize(assign values) to the data members of the class when an object of
the class is created. In Python the __init__() method is called the constructor and is always called when
an object is created.
For Example:
class Employee:
def __init__(self,name):
self.name = name
def getSalary(self):
#Some code…
Types of constructors:
default constructor: The default constructor is a simple constructor which doesn’t accept any
arguments. Its definition has only one argument which is a reference to the instance being
constructed.
# default constructor
def __init__(self):
self.name = "Credence"
# creating object of the class
obj = GeekforGeeks()
class Addition:
first = 0
second = 0
answer = 0
# parameterized constructor
def __init__(self, f, s):
self.first = f
self.second = s
1. Create a class programmer for storing information of a few programmers working at Microsoft.
2. Write a class calculator capable of finding square, cube, and the square root of a number.
3. Create a class with a class attribute a; create an object from it and set a directly using object.a=0
Does this change the class attribute?
5. Write a class Train which has methods to book a ticket, get status(no of seats), and get fare
information of trains running under Indian Railways.
6. Can you change the self parameter inside a class to something else (say ‘harry’)? Try changing
self to ‘slf’ or ‘harry’ and see the effects.
Syntax:
#Code
#Code
Copy
Also, we can overwrite or add new attributes and methods in the Programmer class.
Type of Inheritance
1. Single inheritance
2. Multiple inheritance
3. Multilevel inheritance
Single Inheritance
Single inheritance occurs when a child class inherits only a single parent class.
Multiple Inheritance
Multiple inheritances occurs when the child class inherits from more than one parent class.
Multilevel Inheritance
Super() method
Super method is used to access the methods of a superclass in the derived class.
Copy
Class methods
A class method is a method which is bound to the class and not the object of the class.
@classmethod
#code
Copy
@property decorators
class Employee:
@property
def name(self):
return self.ename
Copy
if e = Employee() is an object of class employee, we can print (e.name) top print the ename/call name()
function.
@name.setter
self.ename = value
Copy
These methods are called when a given operator is used on the objects.
p1 + p2 -> p1.__add__(p2)
p1 – p2 -> p1.__sub__(p2)
p1 * p2 -> p1.__mul__(p2)
p1 / p2 -> p1.__truediv__(p2)
p1 // p2 -> p1.__floordiv__(p2)
Copy
__str__() -> used to set what gets displayed upon calling str(obj)
__len__() -> used to set what gets displayed upon calling .__len__() or len(obj)
Copy
Chapter 11 – Practice Set
1. Create a class C-2d vector and use it to create another class representing a 3-d vector.
2. Create a class of pets from a class Animals and further create class Dog from Pets. Add a method
bark to class Dog.
3. Create a class Employee and add salary and increment properties to it.
Write a method SalaryAfterIncrement method with a @property decorator with a setter which changes
the value of increment based on the salary.
4. Write a class complex to represent complex numbers, along with overloaded operators + and *
which adds and multiplies them.
5. Write a class vector representing a vector of n dimension. Overload the + and * operator which
calculates the sum and the dot product of them.
7i + 8j + 10k
Copy
7. Override the __len__() method on vector of problem 5 to display the dimension of the vector.
We are going to write a program that generates a random number and asks the user to guess it.
If the player’s guess is higher than the actual number, the program displays “Lower number please”.
Similarly, if the user’s guess is too low, the program prints “higher number please”.
When the user guesses the correct number, the program displays the number of guesses the player
used to arrive at the number.