Python Tutorial For Beginners in Hindi
Python Tutorial For Beginners in Hindi
Chapter – 0
What is Programming?
What is Python?
Features of Python:
Installation
When you click on the download button, python can be installed right
after you complete the setup by executing the file for your platform.
Create a file called hello.py and paste the below code into it
print(“Hello World”) # print is a function (more later)
Copy
Execute this file (.py file) by typing python hello.py, and you will see
Hello World printed on the screen.
Modules
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
Comments
Comments are used to write something which the programmer does not
want to execute.
Types of Comments:
b=”Harry”
c=71.22
Copy
Variable – Container to store a value
Data Types:
1. Integers
2. Floating point numbers
3. Strings
4. Booleans
5. None
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>
Copy
A number can be converted into a string and vice versa (if possible)
There are many functions to convert one data type into another.
Str(31) # ”31” Integer to string conversion
input() function
This function allows the user to take input from the keyboard as a string.
a = input(“Enter name”) #if a is “harry”, the user
entered harry
Copy
Note: The output of the input function is always a string even if the
number is entered by the user.
Chapter 3 – Strings
The string is a data type in Python.
String Functions
<|DATE|>
Copy
List Indexing
L1[0] – 7
L1[1] – 9
L1[70] – Error
List Methods
Tuples in Python:
Tuple methods:
Syntax:
''' a = {“key”: “value”,
“harry”: “code”,
“marks” : “100”,
“list”: [1,2,9]}
a[“key”] # Prints value
a[“list”] # Prints [1,2,9] '''
Copy
1. It is unordered
2. It is mutable
3. It is indexed
4. It cannot contain duplicate keys
Dictionary Methods
Sets in Python
S.add(1)
S.add(2)
# or Set = {1,2}
Copy
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
Operations on Sets
S.add(20)
S.add(20.0)
S.add(“20”)
Copy
What will be the length of S after the above operations?
All these are decisions that depend on the condition being met.
If else and elif statements are a multiway decision taken by our program
due to certain conditions in our code.
Syntax:
'''
if (condition1): // if condition 1 is true
print(“yes”)
elif (condition2): // if condition 2 is true
print(“No”)
else: // otherwise
print(“May be”)
'''
Copy
Code example:
a = 22
if (a>9):
print(“Greater”)
else:
print(“lesser”)
Copy
Quick Quiz: Write a program to print yes when the age entered by the
user is greater than or equal to 18.
Relational Operators
<=, etc.
Copy
Logical Operators
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
elif (condition 2):
#code
elif (condition 2):
#code
….
else:
#code '''
Copy
Important Notes:
“make a lot of money”, “buy now”, “subscribe this”, “click this”. Write a
program to detect these spams.
90- E
100 x
80-90 A
70-80 B
60-70 C
50-60 D
<50 F
Loops make it easy for a programmer to tell the computer, which set of
instructions to repeat, and how!
1. While loop
2. For loop
While loop
An Example:
i = 0
while i<5:
print(“Harry”)
i = i+1
Copy
(Above program will print Harry 5 times)
Note: if the condition never becomes false, the loop keeps getting
executed.
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)
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:
print(“Done”) #This is printed when the loop exhausts!
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:
for i in range(0, 80):
print(i) #This will print 0, 1, 2 and 3
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”)
if i == 2: #if i is 2, the iteration is skipped
continue
print(i)
Copy
pass statement
pass is a null statement in python. It instructs to “Do nothing.”
Example:
l = [1, 7, 8]
for item in l:
pass #without pass, the program will throw an error
Copy
***
**
*** for n = 3
Copy
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!
Function call
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
a = greet(“Harry”) #“Harry” is passed to greet in name
For Example:
def greet(name=’stranger’):
#function body
Copy
greet() #Name will be ‘stranger’ in function
body(default)
Recursion
** #For n = 3
*
Copy
Types of Files
Python has a lot of functions for reading, updating, and deleting files.
Opening a file
We can also use f.readline() function to read one full line at a time.
f.readline() #Reads one line from the file
Copy
Modes of opening a file
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
#There is no need to write f.close() as it is done automatically
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.
5. Repeat program 4 for a list of such words to be censored.
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.
8. Write a program to make a copy of a text file “this.txt.”
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.
11. Write a python program to rename a file to
“renamed_by_python.txt.”
Class
A class is a blueprint for creating objects.
Object
Class Attributes
harry.attribute1 :
‘self’ parameter
For Example:
class Employee:
def __init__(self,name):
self.name = name
def getSalary(self):
#Some code…
harry = Employee(“Harry”) #Object can be instantiated using
constructor like this!
Copy
Syntax:
class Emoloyee: #Base Class
#Code
class Programmer(Employee): #Derived or child class
#Code
Copy
We can use the methods and attributes of Employee in Programmer
object.
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
A class method is a method which is bound to the class and not the
object of the class.
These methods are called when a given operator is used on the objects.
p1 – p2 -> p1.__sub__(p2)
p1 * p2 -> p1.__mul__(p2)
p1 / p2 -> p1.__truediv__(p2)
p1 // p2 -> p1.__floordiv__(p2)
Copy
Other dunder/magic methods in Python
__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
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.