Learn Python step-by-step with practical examples, essential concepts, coding tips, and best practices. Perfect for beginners who want to build strong programming skills and start coding with confidence!
Python Programming
1.
Introduction to Python
Python is a high-level, general-purpose programming language known
for its simple syntax, readability, flexibility, and large collection of
libraries.
Python was created by Guido van
Rossum. Development began in the late 1980s, and Python was first released
publicly in 1991.
Python is used for:
- Software development
- Web development
- Data analysis
- Artificial Intelligence
- Machine Learning
- Automation
- Scientific computing
- Cybersecurity
- Desktop applications
- Game development
- Network programming
- Database applications
Simple
Python Program
print("Hello,
World!")
Output
Hello,
World!
2. History of Python
Python was designed by Guido van
Rossum as a successor to the ABC programming language.
Important
milestones
|
Year |
Development |
|
1989 |
Python development began |
|
1991 |
Python 0.9.0 released |
|
1994 |
Python 1.0 released |
|
2000 |
Python 2.0 released |
|
2008 |
Python 3.0 released |
|
Present |
Python 3.x is the actively used
major version |
Python's name was inspired by the
British comedy group Monty Python, rather than the snake.
3. Characteristics of Python
Python has several important
characteristics.
3.1
High-Level Language
Python hides many low-level hardware
details from programmers.
Example:
a
= 10
b
= 20
print(a
+ b)
The programmer does not need to
manage memory addresses manually.
3.2
Interpreted
Python is commonly described as an
interpreted language because Python programs are executed through the Python
interpreter.
Modern Python implementations
internally compile source code into bytecode, which is then executed by
the Python virtual machine.
3.3
Dynamically Typed
The programmer does not normally
need to declare a variable's data type.
x
= 10
x
= "Python"
The same variable name can refer to
objects of different types at different times.
3.4
Object-Oriented
Python supports object-oriented
programming.
It provides:
- Classes
- Objects
- Inheritance
- Encapsulation
- Polymorphism
- Abstraction
3.5
Portable
Python programs can generally run on
different operating systems with little or no modification.
Examples:
- Windows
- Linux
- macOS
3.6
Open Source
Python is freely available and its
source code can be examined and modified under its open-source license.
3.7
Extensible
Python can work with code written in
other languages such as C and C++.
3.8
Large Standard Library
Python provides many built-in
modules for:
- Mathematics
- File handling
- Dates and times
- Networking
- Operating-system operations
- Data processing
- Internet protocols
4. Advantages of Python
Major
advantages
- Easy syntax
- Easy to learn
- Highly readable
- Free and open source
- Cross-platform
- Large standard library
- Huge ecosystem of third-party packages
- Supports multiple programming paradigms
- Useful for rapid development
- Large developer community
- Excellent for automation
- Widely used in AI and data science
5. Limitations of Python
Python also has some disadvantages.
5.1
Execution Speed
Python is generally slower than
compiled languages such as C and C++ for many CPU-intensive tasks.
5.2
Memory Consumption
Python programs can consume
relatively more memory.
5.3
Mobile Development
Python is not generally the first
choice for native mobile application development.
5.4
Runtime Type Errors
Because Python uses dynamic typing,
some type-related errors may appear only when a particular part of the program
runs.
5.5
Global Interpreter Lock
The standard CPython implementation
has a Global Interpreter Lock (GIL), which historically limits simultaneous
execution of Python bytecode by multiple threads in many CPU-bound workloads.
6. Python Installation
To program in Python, you generally
need:
- Python interpreter
- Code editor or IDE
Common development environments
include:
- IDLE
- Visual Studio Code
- PyCharm
- Jupyter Notebook
- Other editors supporting Python
After installing Python, you can
check the version using:
python
--version
or, on some systems:
python3
--version
7. Python Program Structure
A simple Python program:
name
= "Ram"
age
= 20
print("Name:",
name)
print("Age:",
age)
Python uses indentation to
define blocks of code.
Example:
age
= 20
if
age >= 18:
print("Adult")
The indented statement belongs to
the if block.
8. Python Comments
Comments are explanatory notes that
are ignored by the Python interpreter.
Single-line
comment
#
This is a comment
print("Hello")
Multi-line
documentation/string
Python does not have a separate
multiline-comment syntax, but triple-quoted strings are commonly used for
documentation:
"""
This
is a multi-line string.
It
can be used as documentation.
"""
9. Tokens in Python
A token is the smallest
meaningful unit of a Python program.
Major types include:
- Keywords
- Identifiers
- Literals
- Operators
- Delimiters
Example:
x
= 10 + 5
Here:
- x → identifier
- = → assignment operator
- 10 →
integer literal
- + → arithmetic operator
- 5 → integer literal
10. Python Keywords
Keywords are reserved words that have
special meaning.
Examples include:
if
else
elif
for
while
break
continue
def
return
class
try
except
finally
import
from
as
and
or
not
True
False
None
They cannot normally be used as
ordinary variable names.
11. Identifiers
An identifier is the name given
to a variable, function, class, module, etc.
Examples:
name
= "Ram"
age
= 20
student_marks
= 85
Rules
for identifiers
- Can contain letters, digits, and underscore.
- Cannot begin with a digit.
- Cannot contain spaces.
- Cannot be a Python keyword.
- Python is case-sensitive.
Valid:
name
student_name
marks1
_total
Invalid:
1name
student
name
class
12. Variables
A variable is a name that refers to
an object/value.
name
= "Sita"
age
= 18
marks
= 85.5
Python automatically determines the
type of the assigned object.
x
= 100
print(type(x))
Output:
<class
'int'>
13. Constants
Python does not enforce constants
using a special keyword.
Programmers commonly use uppercase
names to indicate that a value should not be changed.
PI
= 3.14159
MAX_MARKS
= 100
This is a naming convention rather
than strict enforcement by Python.
14. Data Types
Python provides several built-in
data types.
Main
categories
|
Category |
Examples |
|
Numeric |
int, float, complex |
|
Boolean |
bool |
|
Text |
str |
|
Sequence |
list, tuple, range |
|
Mapping |
dict |
|
Set |
set, frozenset |
|
Binary |
bytes, bytearray |
|
Special |
NoneType |
15. Integer
Integers are whole numbers.
x
= 100
y
= -25
z
= 0
Python integers can represent
arbitrarily large values subject to available memory.
16. Floating-Point Numbers
Floating-point values represent
numbers with decimal parts.
price
= 99.50
temperature
= 36.5
17. Complex Numbers
Complex numbers contain real and
imaginary components.
z
= 3 + 4j
print(z)
Output:
(3+4j)
18. Boolean Data Type
Boolean values are:
True
False
Example:
is_student
= True
Booleans are commonly used in
conditions.
19. String
A string is a sequence of
characters.
name
= "Python"
Strings can use single or double
quotes:
name
= 'Python'
language
= "Python"
String
operations
text
= "Python"
print(text[0])
print(text[1])
print(len(text))
Output:
P
y
6
20. String Slicing
Slicing extracts part of a string.
text
= "Python Programming"
print(text[0:6])
Output:
Python
Other examples:
text[:6]
text[7:]
text[::2]
text[::-1]
21. Common String Methods
text
= "hello python"
print(text.upper())
print(text.lower())
print(text.title())
print(text.replace("python",
"world"))
Common methods:
- upper()
- lower()
- title()
- capitalize()
- strip()
- replace()
- split()
- join()
- find()
- startswith()
- endswith()
22. Type Conversion
Type conversion means changing one
data type into another.
x
= "100"
number
= int(x)
print(number)
Common functions:
int()
float()
str()
bool()
list()
tuple()
set()
Example:
a
= 10
b
= 5.5
print(float(a))
print(int(b))
23. Input Function
The input() function accepts user input.
name
= input("Enter your name: ")
print("Hello",
name)
Important: input() normally returns a string.
For numeric input:
age
= int(input("Enter your age: "))
print(age)
24. Output Function
The print() function displays output.
print("Hello")
print(10)
print(10
+ 20)
Multiple values:
name
= "Ram"
age
= 20
print("Name:",
name, "Age:", age)
25. Operators in Python
Operators perform operations on
values.
Major categories:
- Arithmetic
- Comparison
- Assignment
- Logical
- Bitwise
- Membership
- Identity
26. Arithmetic Operators
|
Operator |
Meaning |
|
+ |
Addition |
|
- |
Subtraction |
|
* |
Multiplication |
|
/ |
Division |
|
% |
Modulus |
|
// |
Floor division |
|
** |
Exponentiation |
Example:
a
= 10
b
= 3
print(a
+ b)
print(a
- b)
print(a
* b)
print(a
/ b)
print(a
% b)
print(a
// b)
print(a
** b)
27. Comparison Operators
Comparison operators return Boolean
values.
== Equal
!= Not equal
> Greater than
< Less than
>= Greater than or equal
<= Less than or equal
Example:
a
= 10
b
= 20
print(a
< b)
Output:
True
28. Logical Operators
Python has three main logical
operators:
and
or
not
Example:
age
= 20
print(age
>= 18 and age <= 60)
29. Assignment Operators
Examples:
=
+=
-=
*=
/=
%=
**=
//=
Example:
x
= 10
x
+= 5
print(x)
Output:
15
30. Membership Operators
Membership operators are:
in
not
in
Example:
fruits
= ["Apple", "Mango", "Banana"]
print("Mango"
in fruits)
Output:
True
31. Identity Operators
Identity operators:
is
is
not
They test whether two references
refer to the same object, rather than merely whether their values are equal.
a
= [1, 2]
b
= a
print(a
is b)
32. Conditional Statements
Conditional statements allow a
program to make decisions.
if
age
= 20
if
age >= 18:
print("Adult")
if-else
age
= 15
if
age >= 18:
print("Adult")
else:
print("Minor")
if-elif-else
marks
= 75
if
marks >= 80:
print("A")
elif
marks >= 60:
print("B")
elif
marks >= 40:
print("C")
else:
print("Fail")
33. Nested if
An if statement can contain another if.
age
= 20
citizen
= True
if
age >= 18:
if citizen:
print("Eligible")
34. Loops
Loops execute a block repeatedly.
Python mainly provides:
- for
- while
35. For Loop
for
i in range(1, 6):
print(i)
Output:
1
2
3
4
5
36. While Loop
i
= 1
while
i <= 5:
print(i)
i += 1
37. Range Function
range() generates a sequence of numbers.
range(stop)
range(start,
stop)
range(start,
stop, step)
Example:
for
i in range(2, 10, 2):
print(i)
Output:
2
4
6
8
38. Break Statement
break
terminates the loop.
for
i in range(10):
if i == 5:
break
print(i)
39. Continue Statement
continue skips the current iteration.
for
i in range(5):
if i == 2:
continue
print(i)
40. Pass Statement
pass
does nothing and is used as a placeholder.
for
i in range(5):
pass
41. Lists
A list is an ordered, mutable
collection.
students
= ["Ram", "Sita", "Hari"]
Lists can contain different data
types:
data
= [10, "Python", 5.5, True]
42. List Indexing
fruits
= ["Apple", "Banana", "Mango"]
print(fruits[0])
print(fruits[-1])
Output:
Apple
Mango
43. List Methods
Common methods:
append()
extend()
insert()
remove()
pop()
clear()
index()
count()
sort()
reverse()
copy()
Example:
numbers
= [3, 1, 2]
numbers.append(4)
numbers.sort()
print(numbers)
Output:
[1,
2, 3, 4]
44. Tuples
A tuple is an ordered and immutable
collection.
numbers
= (10, 20, 30)
Because tuples are immutable, their
elements cannot normally be changed after creation.
45. Sets
A set is an unordered collection of
unique elements.
numbers
= {1, 2, 3, 3}
print(numbers)
Duplicate values are removed.
Sets support operations such as:
- Union
- Intersection
- Difference
- Symmetric difference
Example:
a
= {1, 2, 3}
b
= {3, 4, 5}
print(a
| b)
print(a
& b)
46. Dictionary
A dictionary stores data as key-value
pairs.
student
= {
"name": "Ram",
"age": 20,
"marks": 85
}
Accessing data:
print(student["name"])
Adding data:
student["address"]
= "Mahottari"
47. Dictionary Methods
Common methods:
keys()
values()
items()
get()
update()
pop()
clear()
Example:
student
= {"name": "Ram", "age": 20}
print(student.keys())
print(student.values())
48. Functions
A function is a reusable block of
code.
Syntax:
def
function_name(parameters):
statements
Example:
def
greet():
print("Hello")
greet()
49. Function Parameters
def
greet(name):
print("Hello", name)
greet("Ram")
50. Return Statement
def
add(a, b):
return a + b
result
= add(10, 20)
print(result)
Output:
30
51. Types of Function Arguments
Python supports:
- Positional arguments
- Keyword arguments
- Default arguments
- Variable-length arguments
Example:
def
greet(name="User"):
print("Hello", name)
greet()
greet("Ram")
52. *args
*args
allows a function to receive multiple positional arguments.
def
total(*numbers):
return sum(numbers)
print(total(10,
20, 30))
53. **kwargs
**kwargs allows multiple keyword arguments.
def
student_info(**data):
print(data)
student_info(name="Ram",
age=20)
54. Lambda Function
A lambda is a small anonymous
function.
square
= lambda x: x * x
print(square(5))
Output:
25
55. Scope of Variables
Local
Variable
Created inside a function.
def
test():
x = 10
Global
Variable
Created outside functions.
x
= 10
def
test():
print(x)
Python also provides global and nonlocal statements for specific scope-management cases.
56. Recursion
Recursion occurs when a function
calls itself.
Example:
def
factorial(n):
if n == 0:
return 1
return n * factorial(n - 1)
print(factorial(5))
Output:
120
57. Object-Oriented Programming
Python supports OOP.
Important concepts:
- Class
- Object
- Constructor
- Inheritance
- Encapsulation
- Polymorphism
- Abstraction
58. Class
A class is a blueprint for creating
objects.
class
Student:
name = "Ram"
59. Object
An object is an instance of a class.
class
Student:
name = "Ram"
student1
= Student()
print(student1.name)
60. Constructor
The __init__() method is commonly used to initialize an object.
class
Student:
def __init__(self, name, age):
self.name = name
self.age = age
student
= Student("Ram", 20)
print(student.name)
print(student.age)
61. Inheritance
Inheritance allows one class to
inherit attributes and methods from another class.
class
Animal:
def speak(self):
print("Animal sound")
class
Dog(Animal):
pass
dog
= Dog()
dog.speak()
62. Polymorphism
Polymorphism means that the same
interface or method name can behave differently for different objects.
class
Dog:
def sound(self):
print("Bark")
class
Cat:
def sound(self):
print("Meow")
for
animal in [Dog(), Cat()]:
animal.sound()
63. Encapsulation
Encapsulation involves keeping data
and the methods operating on it together and controlling access to internal
implementation details.
Python uses naming conventions such
as:
_name
__name
A double underscore triggers name
mangling in many class contexts.
64. Modules
A module is a Python file containing
definitions and statements.
Example:
import
math
print(math.sqrt(25))
65. Common Built-in Modules
Examples include:
- math
- random
- datetime
- os
- sys
- json
- statistics
- re
- time
Example:
import
math
print(math.pi)
print(math.sqrt(16))
66. Import Statement
import
math
Specific import:
from
math import sqrt
print(sqrt(25))
Alias:
import
math as m
print(m.sqrt(25))
67. Packages
A package is a way of organizing
related Python modules into a directory structure.
For example, a project might have:
project/
main.py
utilities/
__init__.py
calculation.py
display.py
68. Exception Handling
Exceptions are runtime events that
can interrupt normal program execution.
Python uses:
try
except
else
finally
Example:
try:
x = int(input("Enter a number:
"))
print(10 / x)
except
ValueError:
print("Please enter a valid
number.")
except
ZeroDivisionError:
print("Cannot divide by zero.")
69. Finally Block
finally executes whether or not an exception occurs.
try:
print("Processing")
finally:
print("Finished")
70. Raising Exceptions
Programmers can deliberately raise
exceptions.
age
= -5
if
age < 0:
raise ValueError("Age cannot be
negative")
71. File Handling
Python provides the open() function for file operations.
Common modes:
|
Mode |
Meaning |
|
r |
Read |
|
w |
Write |
|
a |
Append |
|
x |
Create |
|
b |
Binary |
|
t |
Text |
72. Reading a File
with
open("data.txt", "r") as file:
content = file.read()
print(content)
The with statement helps ensure that the file is properly closed.
73. Writing to a File
with
open("data.txt", "w") as file:
file.write("Python Programming")
74. Appending to a File
with
open("data.txt", "a") as file:
file.write("\nNew line")
75. CSV Files
Python provides the csv module.
import
csv
with
open("students.csv", newline="") as file:
reader = csv.reader(file)
for row in reader:
print(row)
76. JSON
JSON is commonly used for exchanging
structured data.
import
json
data
= {
"name": "Ram",
"age": 20
}
text
= json.dumps(data)
print(text)
To convert JSON text back into a
Python object:
data
= json.loads(text)
print(data["name"])
77. List Comprehension
List comprehension provides a
concise way to create lists.
Traditional:
squares
= []
for
i in range(1, 6):
squares.append(i * i)
List comprehension:
squares
= [i * i for i in range(1, 6)]
78. Dictionary Comprehension
squares
= {x: x*x for x in range(1, 6)}
print(squares)
79. Iterators
An iterator is an object that
produces values one at a time.
Important functions:
iter()
next()
Example:
numbers
= iter([10, 20, 30])
print(next(numbers))
print(next(numbers))
80. Generators
Generators produce values lazily
using yield.
def
numbers():
yield
1
yield 2
yield 3
for
number in numbers():
print(number)
Generators are useful when working
with large sequences because values can be produced one at a time.
81. Decorators
A decorator is a mechanism for
modifying or extending the behavior of a function or class without changing its
original source code.
Basic example:
def
decorator(function):
def wrapper():
print("Before function")
function()
print("After function")
return wrapper
@decorator
def
hello():
print("Hello")
hello()
82. Regular Expressions
Python provides the re module for pattern matching.
import
re
text
= "My phone number is 12345"
result
= re.search(r"\d+", text)
if
result:
print(result.group())
83. Date and Time
Python provides the datetime module.
from
datetime import datetime
now
= datetime.now()
print(now)
Specific components:
print(now.year)
print(now.month)
print(now.day)
84. Random Numbers
The random module generates pseudo-random values.
import
random
number
= random.randint(1, 10)
print(number)
85. Math Module
import
math
print(math.sqrt(25))
print(math.factorial(5))
print(math.pi)
86. Object Identity and Equality
There is an important difference
between ==
and is.
==
Checks whether values compare equal.
a
= [1, 2]
b
= [1, 2]
print(a
== b)
Output:
True
is
Checks object identity.
print(a
is b)
This is normally False because they are separate list objects.
87. Python Indentation
Indentation is fundamental to Python
syntax.
Correct:
if
True:
print("Correct")
Incorrect:
if
True:
print("Incorrect")
Python generally uses four spaces
for each indentation level.
88. Python's None
None
represents the absence of a value.
result
= None
print(result)
It is different from:
0
False
""
89. pass, break, and continue
|
Statement |
Purpose |
|
pass |
Does nothing; placeholder |
|
break |
Terminates loop |
|
continue |
Skips current iteration |
90. Python Package Management
Python packages are commonly
installed using pip.
Example:
pip
install requests
Upgrade:
pip
install --upgrade requests
Remove:
pip
uninstall requests
List installed packages:
pip
list
91. Virtual Environment
A virtual environment isolates
project dependencies.
Create:
python
-m venv myenv
Activation commands depend on the
operating system and shell.
This is useful because different
projects may require different package versions.
92. Python and Databases
Python can work with many databases.
Examples:
- SQLite
- MySQL
- PostgreSQL
- Microsoft SQL Server
- Oracle Database
SQLite example:
import
sqlite3
connection
= sqlite3.connect("school.db")
cursor
= connection.cursor()
cursor.execute("""
CREATE
TABLE IF NOT EXISTS students (
id INTEGER PRIMARY KEY,
name TEXT,
marks INTEGER
)
""")
connection.commit()
connection.close()
93. Python for Web Development
Popular Python web frameworks
include:
Django
A powerful framework suitable for
larger web applications.
Flask
A lightweight framework that
provides flexibility.
FastAPI
Designed for building modern APIs
with strong support for type hints and asynchronous programming.
94. Python for Data Science
Python is extremely popular in data
science.
Important libraries:
NumPy
Used for numerical computing and
multidimensional arrays.
Pandas
Used for data manipulation and
analysis.
Matplotlib
Used for creating charts and graphs.
Seaborn
Used for statistical data
visualization.
Example:
import
pandas as pd
data
= pd.DataFrame({
"Name": ["Ram",
"Sita"],
"Marks": [80, 90]
})
print(data)
95. Python for Artificial Intelligence
Python is widely used in AI because
of its libraries and ecosystem.
Important tools include:
- NumPy
- Pandas
- Scikit-learn
- TensorFlow
- PyTorch
- OpenCV
Applications include:
- Image recognition
- Natural language processing
- Recommendation systems
- Speech processing
- Predictive modeling
- Computer vision
96. Python for Machine Learning
A typical machine-learning workflow
may involve:
- Collecting data
- Cleaning data
- Exploring data
- Preparing features
- Training a model
- Evaluating the model
- Improving the model
- Deploying the model
Scikit-learn provides many classical
machine-learning algorithms.
97. Python for Automation
Python can automate repetitive
tasks.
Examples:
- Renaming files
- Processing documents
- Generating reports
- Reading spreadsheets
- Sending automated notifications
- Data processing
- System administration
Example:
import
os
for
filename in os.listdir("."):
print(filename)
98. Python for Networking
Python provides modules and
libraries for network programming.
Examples:
- socket
- http
- urllib
- requests
Basic example:
import
socket
hostname
= socket.gethostname()
print(hostname)
99. Python for GUI Development
Python can create graphical user
interfaces.
Popular options include:
- Tkinter
- PyQt
- PySide
- Kivy
Simple Tkinter example:
import
tkinter as tk
window
= tk.Tk()
window.title("My
Application")
label
= tk.Label(window, text="Hello Python")
label.pack()
window.mainloop()
100. Python Programming Paradigms
Python supports multiple programming
styles.
Procedural
Programming
Programs are organized around
procedures/functions.
Object-Oriented
Programming
Programs are organized around
classes and objects.
Functional
Programming
Python supports concepts such as:
- Lambda functions
- map()
- filter()
- reduce()
- Higher-order functions
- Comprehensions
Example:
numbers
= [1, 2, 3, 4]
squares
= list(map(lambda x: x*x, numbers))
print(squares)
101. Python Memory Management
Python automatically manages memory.
The interpreter keeps track of
objects and can reclaim memory that is no longer needed.
Important concepts include:
- References
- Object allocation
- Reference counting in CPython
- Garbage collection
Programmers generally do not
manually allocate and free memory as they do in languages such as C.
102. Garbage Collection
Python includes automatic garbage
collection for managing certain objects, particularly reference cycles.
Example concept:
a
= [1, 2, 3]
a
= None
When an object is no longer
reachable, Python can eventually reclaim the memory associated with it.
103. Python Bytecode
When Python source code is executed
in CPython, it is generally compiled into an intermediate representation called
bytecode.
Conceptually:
Python
Source Code
↓
Python
Compiler
↓
Bytecode
↓
Python
Virtual Machine
↓
Execution
Implementation details can vary
between Python implementations and versions.
104. Python Interpreter
The interpreter executes Python
programs.
Common implementations include:
- CPython
— the reference implementation and most widely used
- PyPy
— alternative implementation with a JIT compiler
- Jython
— Python implementation for the Java platform
- IronPython
— Python implementation for the .NET ecosystem
105. Error Types
Python programs can encounter
different kinds of errors.
Syntax
Error
Occurs when Python syntax is
invalid.
if
True
print("Hello")
NameError
Occurs when an undefined name is
referenced.
print(value)
TypeError
Occurs when an operation is applied to
an inappropriate type.
"10"
+ 5
ValueError
Occurs when a value has the correct
general type but an inappropriate value.
int("hello")
IndexError
Occurs when a sequence index is
outside its valid range.
items
= [1, 2]
print(items[5])
KeyError
Occurs when a dictionary key does
not exist.
data
= {"name": "Ram"}
print(data["age"])
106. Debugging
Debugging means identifying and
correcting errors in a program.
Common approaches:
- Read error messages
- Use print() for simple inspection
- Use an IDE debugger
- Check variables
- Test smaller sections
- Use logging
- Write automated tests
107. Python Testing
Testing checks whether software
behaves as expected.
Python provides the built-in unittest framework.
Example:
import
unittest
def
add(a, b):
return a + b
class
TestAdd(unittest.TestCase):
def test_add(self):
self.assertEqual(add(2, 3), 5)
if
__name__ == "__main__":
unittest.main()
Another popular testing framework is
pytest.
108. Python Coding Style
Python programmers commonly follow PEP
8, the Python style guide.
Good practices include:
- Use meaningful variable names.
- Use consistent indentation.
- Keep functions focused.
- Add useful documentation.
- Avoid unnecessary complexity.
- Follow consistent naming conventions.
Example:
student_name
= "Ram"
total_marks
= 450
This is generally clearer than:
sn
= "Ram"
tm
= 450
109. Complete Beginner Example
name
= input("Enter your name: ")
marks
= float(input("Enter your marks: "))
if
marks >= 80:
grade = "A"
elif
marks >= 60:
grade = "B"
elif
marks >= 40:
grade = "C"
else:
grade = "F"
print("Name:",
name)
print("Marks:",
marks)
print("Grade:",
grade)
Working
of the program
- The user enters a name.
- The user enters marks.
- float()
converts the marks into a number.
- if-elif-else
determines the grade.
- print()
displays the result.
110. Example: Simple Calculator
a
= float(input("Enter first number: "))
operator
= input("Enter operator (+, -, *, /): ")
b
= float(input("Enter second number: "))
if
operator == "+":
result = a + b
elif
operator == "-":
result = a - b
elif
operator == "*":
result = a * b
elif
operator == "/":
if b != 0:
result = a / b
else:
result = "Cannot divide by
zero"
else:
result = "Invalid operator"
print("Result:",
result)
111. Example: Finding Even and Odd Numbers
number
= int(input("Enter a number: "))
if
number % 2 == 0:
print("Even number")
else:
print("Odd number")
112. Example: Finding the Largest Number
a
= 10
b
= 25
c
= 15
largest
= max(a, b, c)
print("Largest:",
largest)
113. Example: Factorial
n
= int(input("Enter a number: "))
factorial
= 1
for
i in range(1, n + 1):
factorial *= i
print("Factorial:",
factorial)
114. Example: Multiplication Table
number
= int(input("Enter a number: "))
for
i in range(1, 11):
print(number, "×", i,
"=", number * i)
115. Example: Student Record Using Dictionary
student
= {
"name": "Ram",
"roll": 15,
"class": 11,
"marks": 85
}
print("Name:",
student["name"])
print("Roll:",
student["roll"])
print("Class:",
student["class"])
print("Marks:",
student["marks"])
116. Python in Computer Operator / Loksewa Preparation
For computer-related competitive
examinations, important Python topics include:
Basic
concepts
- Definition of Python
- History
- Features
- Advantages and disadvantages
- Applications
Syntax
- Indentation
- Comments
- Keywords
- Identifiers
- Variables
- Literals
Data
types
- Integer
- Float
- Complex
- Boolean
- String
- List
- Tuple
- Set
- Dictionary
Operators
- Arithmetic
- Relational/comparison
- Logical
- Assignment
- Bitwise
- Membership
- Identity
Control
statements
- if
- if-else
- if-elif-else
- for
- while
- break
- continue
- pass
Functions
- Defining functions
- Parameters
- Arguments
- Return values
- Lambda functions
- Recursion
- *args
- **kwargs
OOP
- Class
- Object
- Constructor
- Inheritance
- Polymorphism
- Encapsulation
- Abstraction
Advanced
topics
- Modules
- Packages
- Exceptions
- File handling
- Regular expressions
- Iterators
- Generators
- Decorators
- Virtual environments
- Package management
117. Important Python Differences from C/C++
|
Feature |
Python |
C/C++ |
|
Typing |
Dynamically typed |
Primarily statically typed |
|
Memory management |
Automatic |
More explicit/manual mechanisms |
|
Syntax |
Indentation-based blocks |
Braces commonly used |
|
Compilation |
Typically executed through
interpreter/runtime |
Typically compiled |
|
Variable declaration |
Usually not required |
Usually required |
|
Pointer manipulation |
Not exposed like C/C++ |
Supported |
|
Ease of learning |
Generally easier |
Generally more complex |
|
Execution speed |
Generally slower |
Generally faster for many compiled
workloads |
118. Important Python Built-in Functions
Some frequently used built-in
functions are:
print()
input()
len()
type()
int()
float()
str()
bool()
list()
tuple()
set()
dict()
range()
sum()
max()
min()
abs()
round()
sorted()
enumerate()
zip()
map()
filter()
open()
Example:
numbers
= [10, 20, 30]
print(len(numbers))
print(sum(numbers))
print(max(numbers))
print(min(numbers))
119. Important Python Concepts at a Glance
Python
│
├──
Basic Syntax
│ ├── Variables
│ ├── Keywords
│ ├── Identifiers
│ └── Comments
│
├──
Data Types
│ ├── Numbers
│ ├── String
│ ├── List
│ ├── Tuple
│ ├── Set
│ └── Dictionary
│
├──
Operators
│ ├── Arithmetic
│ ├── Comparison
│ ├── Logical
│ ├── Assignment
│ ├── Bitwise
│ ├── Membership
│ └── Identity
│
├──
Control Flow
│ ├── if
│ ├── for
│ ├── while
│ ├── break
│ ├── continue
│ └── pass
│
├──
Functions
│ ├── Parameters
│ ├── Arguments
│ ├── Return
│ ├── Lambda
│ └── Recursion
│
├──
OOP
│ ├── Class
│ ├── Object
│ ├── Inheritance
│ ├── Polymorphism
│ └── Encapsulation
│
├──
Modules & Packages
│
├──
File Handling
│
├──
Exception Handling
│
└──
Libraries & Frameworks
├── NumPy
├── Pandas
├── Django
├── Flask
├── TensorFlow
└── PyTorch
Conclusion
Python is a powerful, readable,
versatile programming language that can be used from basic programming
education to advanced software engineering, data science, artificial intelligence,
automation, web development, and scientific computing.
For exam preparation, the
highest-priority areas are Python features and history, syntax and
indentation, variables and data types, operators, conditional statements,
loops, functions, lists/tuples/sets/dictionaries, exception handling, file
handling, modules, and object-oriented programming.
