1. Python Programming
Python is a high-level, interpreted, dynamically typed, and general-purpose programming language.
* Interpreted: Python runs the program one line at a time using an interpreter.
print( " Hello World " )
print( 12 +9 )
print( " My name is Alex Lal Karn and I read in class 3. " )
Output: Hello World
21
My name is Alex Lal Karn and I read in class 3.
* Dynamically Typed: In Python, you don't have to tell Python what type of data a variable contains. Python automatically finds out the type while the program is running.
age = 12
name = "Ram"
gpa = 3.83
print ( type (age) )
print ( type (name) )
print ( type (gpa) )
Output: <class 'int'>
<class 'str'>
<class 'float'>
2. History of Python Programming :
Guido van Rossum, a Dutch programmer, started working on Python during his Christmas holidays in December 1989. He named it "Python" after the British comedy show Monty Python’s Flying Circus, not after the snake. He wanted a name that was short, unique, and slightly mysterious. He released Python in 1991.
3. Features of Python
(i) Easy to read and write: Python uses simple and understandable syntax, making it easy for programmers to write and understand the code.
(ii) Versatile: Python can be used for a wide range of tasks like simple automating systems to complex web development, data analysis, and Artificial Intelligence.
(iii) Beginner-friendly : Python uses simple syntax, making it a great choice for those who are new to programming.
(iv) Extensive standard library : Python has an extensive standard library of pre-written code that offers programmers ready-made solutions, without requiring them to write code from ground level.
(v) Rich ecosystem : Python has a vast collection of libraries and ready-made structures known as frameworks that provide ready-to-use tools for programmers.
4. Starting Python with IDLE :
Integrated Development and Learning Environment (IDLE) is Python's default Integrated Development Environment (IDE), included with Python installation. IDLE is appropriate for novices to write and test programs.
1. Using the Interactive Shell for Immediate Execution :
Launch IDLE to bring up the Python Shell. You can directly run one-line instructions to get instant feedback or result.
Example: print( " Hello World!")
2. Writing and Executing Scripts via the File Menu
1. Open a new script file: Navigate to the top menu bar in Python IDLE and click File → New File to open a fresh script editor window.
2. Write your code:Type out your multi-line Python program in the new editor window.
3. Save the program file:ave your code by clicking File → Save (or pressing Ctrl + S), making sure to give the file a .py extension.
4. Execute the script:Run your program by pressing F5 on your keyboard, or select Run → Run Module from the top menu bar.
5. Comments in Python
In Python, comments are brief messages that programmers write in their code to explain what the code is doing, like leaving helpful hints for others to understand the program. Comments are indicated by the ‘#’ sign, and the interpreter ignores them, treating them as notes for the programmer. They don’t affect the actual program.
There are two types of comments in Python.
5.1 Single line Comment
In Python, a short note or comment starts with the ‘#’ symbol and goes until the end of that line. If the note is longer and needs more than one line, each additional line should also begin with a ‘#’ symbol.
Example 1:
print(" I am from Nepal.")
Example 2:
print( " I am enjoying learning Python programming ")5.2 Multi-line comment
In Python, when a single-line comment is not sufficient and needs to go in multiple lines, it can be challenging to add a ‘#’ at the beginning of each line. In such cases, Python allows the use of triple single quotes (''') or triple double quotes (""") at the beginning and end of the comment to extend it over multiple lines.
Example 3:
print( " Welcome to you " )
6. Input/Output in Python
In Python programming, input() and print() are two fundamental functions used to get data from user and display output on screen.
print ( ) function
print() function is used to display or print the content on output screen.
input ( ) function
input() function is used to get the data instructions from user.
7. Data types in Python
The classification of data based on its nature is called datatype. Python also offers various data type which are listed as:
7.1 Integer (int):
It is a whole number ranging from negative infinity to positive infinity.
Examples: ...,-3,-2,-1,0,1,2,3,...
7.2 Float (float):
It is numbers with decimals. Examples: 3.14, -0.21, 1.567.
7.3 String (str):
It consists of alphabets, special characters, alphanumeric values which are enclosed in double quotes. Examples: "hello world" , "Python Programming " etc.
7.4 Boolean (bool):
It only provides True or False values. Example: is_student = True, has_mobile=False
8. Keywords in Python
In programming, keywords are reserved words that have predefined meanings. Keywords cannot be used as identifiers. Some of the common Python keywords are listed below:
| for | if | else | elif |
| and | or | not | while |
| None | True | False | import |
| as | in | try | except |
| finally | from | global | return |
9. Identifier in Python
Identifiers are names given to program units such as variables, functions, classes, or other entities. They are not predefined in the programming language but are defined by programmers themselves.
Rules for naming identifier
1. Name must start with a letter or an underscore(अन्डरस्कोर).
2. Name must not start with a number.
3. Name can contain alphanumeric (अल्फानुमेरिक) characters and underscores (A-Z, a-z, 0-9, and _).
4. Names are case-sensitive. (Example: roll, Roll, and ROLL are three different identifiers)
5. Don't use Python keywords as an identifier name.
| Valid identifiers |
| A1 | first_Name | x_1 |
| Invalid identifiers |
| 1A | first-Name | int |
10. Variables
A variable is a name used to store a value in a computer program. A variable holds a value, and this value can change during the execution of the program.
Example: a=10
user_name="Alex Lal "
11. Type Casting in Python
The process of converting a variable from one data type to another is called type casting.
11.1 Implicit Type casting
Implicit type casting, also known as automatic type conversion, occurs when the Python interpreter automatically converts one data type to another in certain situations.
Example program to show concept of implicit type casting
x = 12 # integer
y = 9.5 # float
z = x + y
print(z) # Output: 21.5
11.2 Explicit Type casting
In explicit type casting, you forcefully change a variable from one data type to another using built-in functions.
Here are the main ways to do this in Python:
* int(): Forcefully converts a value to a whole number.
* float(): Forcefully converts a value to a decimal number.
* str(): Forcefully converts a value to text.
Example program to show concept of explicit type casting
x = 21
y = float(x)
print("int to float:", y) # Output: 21.012. Operators : Arithmetic, Relational, Logical, Assignment
Operators are special symbols that we use to do different things with numbers and words which allows us to perform specific actions.
12.1 Arithmetic operator
Arithmetic operator is used in Python to do mathematical operations. We use arithmetic operators as special symbols to do basic math. It is like having a set of tools for simple calculation.
| Operators | Description | Example |
| + | Addition | print ( 5 + 2) = 7 |
| - | Subtraction | print ( 5 - 2) = 3 |
| * | Multiplication | print ( 5 * 2) = 10 |
| ** | Exponential (Power) | print ( 5 ** 2) = 25 |
| / | Division | print ( 5 / 2) = 2.5 |
| // | Floor Division | print ( 5 // 2) = 2 |
| % | Modulus(Remainder) | print ( 5 % 2) = 1 |
12.2 Relational operator
Relational operator is used to check and compare values. These operators check the relationship between two things and tell us if they are equal, greater than or less than each other.
| Operators | Name | Example |
| < | Less Than | print(2<1) False |
| <= | Less than or Equal to | print (2<=1) False |
| > | Greater than | print (2>1) True |
| >= | Greater than or Equal to | print (2>=1) True |
| == | Equal to | print(2==1) False |
| != | Not Equal to | print(2!=1) True |
12.3 Logical operator
Logical operators in Python are used to combine conditions and make decisions based on different situations. This operator is like a tool that helps us make decisions based on different situations. There are 3 main logical operators, 'and', 'or', and 'not'.
AND
Both the conditions must be true for the result to be true in the “and” operator.
Example: x = (5<2) and (5>3)
Result: False
Truth table for 'and' operator
| Input | Output |
| A | B | A and B |
| 0 | 0 | 0 |
| 0 | 1 | 0 |
| 1 | 0 | 0 |
| 1 | 1 | 1 |
OR:
Only one of the conditions needs to be true for the result to be true in the "or" operator.
Example: (5<2) or (5>3)
Result: True
Truth table for 'or' operator
| Input | Output |
| A | B | A or B |
| 0 | 0 | 0 |
| 0 | 1 | 1 |
| 1 | 0 | 1 |
| 1 | 1 | 1 |
NOT:
The logical operator "not" provides the opposite result of a given condition.
Example: not(5<2)
Result: True
Truth table for 'not' operators
| Input | Output |
| A | not A |
| 0 | 1 |
| 1 | 0 |
12.4 Assignment operator
Assignment operators are used to assign values to variables.
| Operators | Description | Example |
| = | Assignment Operator | a = 7 |
| += | Addition Assignment | a += 1
# a=a+1 |
| -= | Subtraction Assignment | a -=3
# a=a–3 |
| *= | Multiplication Assignment | a *=4
# a=a*4 |
| /= | Division Assignment | a /= 3
# a=a/3 |
| %= | Remainder Assignment | a %=10
# a=a%10 |
| **= | Exponent Assignment | a **=10
# a =a **10 |
# assign 10 to a
a = 10
# assign 5 to b
b = 5
# assign the sum of a and b to a
a += b
# a = a + b
print(a)
13. Expressions
An expression in Python is like a formula that tells the computer to do something with numbers and words. It is like a command that produces a value. They are like the building blocks of our code, telling the computer what to do with the information we provide.
Here, are some examples of expressions:
Maths expression: result = 5 + 3
Text expression: greeting = "Hello"
Combining expression: combined = (5 * 3) + "Python"
| Algebraic expression | Python expression |
| A+B -C | A+B–C |
| A x B ÷ C | A*B/C |
| (a+b) (a-b) | (a+b)*(a-b) |
| PTR/100 | I = (P*T*R)/100 |
14. Operands
In programming, operands are values or variables that operators operate on. Operands refer to the values or entities that are operated upon by an operator. They are the variables that utilize the operators.
Example: add = 5 + 3
Here, ‘5’ and ‘3’ are operands with '+' and '=' are operators, and it is performing an ‘addition’ operation.
15. Conditional Statement
A conditional statement is like a decision making tool that helps our program choose what to do based on conditions provided by the user. We can ask a question and provide different answers based on the conditions provided. The most fundamental form of conditional statement is
if statement,
"if - else" statement and
"if - elif -else" statement.
The statement to be executed follows the indentation rule of Python
15.1 if statement
"if statement" is a conditional statement that gives us output based on the requirement of the condition that we provide. “if statement” is written using the if keyword and after that condition is provided and ends with indentation.
Syntax:
if condition:
#statement for True statement
15.2 if-else condition
This is the most common type of conditional statement. In an if-else statement, there are instructions for both true and false conditions.
- If the condition is true, the computer runs the code after if.
- If the condition is false, the computer runs the code after else.
Remember: else never has its own condition written next to it.
Syntax:
if condition:
# statement for True statement
else:
# statement for False statement
15.3 if-elif-else condition
Syntax:
if condition1:
# statement for condition 1 true
elif condition2:
# statement for condition 2 true
else:
# statement when condition 1 and condition 2 are False
15.4 Nested if (if inside if)
Nested if statement is a construct where we put another if statement inside an existing if statement. It is used to test multiple criteria and increase the number of possible outcomes. It helps in decision making using multiple conditions.
Syntax:
if condition1:
#statement for condition 1 true
if condition2:
# statement for condition 2 True
else:
# statement for condition 2 False
else
# statement for condition 1 and condition 2 are False
16. Iteration (Looping)
Iteration is the process of repeating a particular task until a specified condition is satisfied. It allows a program to perform a task multiple times until a required condition is satisfied. The most fundamental example of iteration is the "for" loop and "while" loop.
16.1 for loop
A for loop in Python lets you run a block of code multiple times, once for each item in a list or sequence. You use it when you already know how many times you want to repeat an action, using the for keyword to start the loop.
Syntax:
for item in iterable:
# Code block to execute for each item
Components:
(i) for: The keyword that starts the loop.
(ii) item: A variable that holds the current element from the sequence during each cycle.
(iii) in: The keyword connecting the variable to the sequence.
(iv) iterable: Any collection of items (such as a list, string, tuple, or range()).
(v) : (Colon): Signals the start of the indented code block.
(vi) Indented Code: The statements that run once for every item in the sequence.
# Using for loop print "Computer" 10 times
for x in range(10):
print ( "Computer")
In Python, range is a function that helps you make a list of numbers in a certain order. It returns a sequence of numbers, starting from 0 by default and increments from 1 (by default), and stops before a given number by user.
16.2 while loop
A
while loop in Python is a control structure that repeatedly runs a block of code as long as a specified condition remains true. It is ideal for situations where you do not know the exact number of iterations or the condition in advance, allowing the program to keep executing until a specific state changes or a target goal is achieved. Once that condition turns false, the loop stops automatically.
Syntax:
while condition:
# Code block to execute repeatedly
# (Must include a step that eventually changes the condition)
Components:
(i) while: The keyword that starts the loop.
(ii) condition: A boolean expression evaluated before each loop cycle (True or False).
(iii) : (Colon): Signals the start of the indented block.
(iv) Indented Code: The statements that execute repeatedly as long as the condition remains True.
count = 1
while count <= 10:
print(count)
count += 1 # Updates variable so the loop eventually ends Difference between for loop and while loop
| For loop | While loop |
| 1. For loop is used when we know the number of iterations. |
1. While loop is used when we don’t know the number of iterations. |
| 2. This loop iterates an infinite number of times if the condition is not specified. |
2. If the condition is not specified, it shows compilation error. |
| 3. The increment is done after the execution of the statement. |
3. The increment can be done before or after the execution of a statement. |
| 4. The nature of increment is simple. |
4. The nature of increment is complex. |
| 5. Initialisation can be in or out of the loop. |
5. Initialisation is always out of the loop. |
17. Python Loop Controls
17.1 pass
In Python, the pass keyword is a null operation or a no-operation statement. It acts as a placeholder where some code is required but no action is necessary. It is often used when a statement is required by Python syntax, but you don’t want to execute any code.
# The 'pass' statement acts as a placeholder when code is required syntactically,
# but you don't want to execute any commands yet.
temperatures = [68, 72, 105, 88, 91]
for temp in temperatures:
if temp > 100:
# TODO: Send an overheat alert email to admin
pass # Placeholder to prevent a SyntaxError while building the feature
else:
print( " Normal temperature: " , temp, "degree F")
17.2 continue
In Python, the continue keyword is used in loops (such as for or while loops). It is used to skip the rest of the code inside the loop for the current iteration and move on to the next iteration. It allows us to bypass certain parts of the loop based on a condition without exiting the loop entirely.
# Example program that show the use of continue
for number in range(1, 6):
if number == 3:
continue # Skip the rest of the loop for number 3.
print(number)
17.3 break
In Python, the break keyword is used in loops (such as for or while loops) to exit the loop early, even if the loop’s condition hasn’t been fully satisfied. It allows us to terminate the loop based on a certain condition.
for number in range ( 1, 6 ):
if number == 3 :
break # Exit the loop when number is 3
print(number)
18. Python list
A list in Python is a built-in, mutable, and ordered data type used to store a collection of items in a single variable.
Lists are ordered, changeable (mutable), and can hold mixed data types (strings, numbers, booleans, or other lists) written inside square brackets [ ].
List elements are enclosed by square brackets [ ] and elements are separated by comma.
18.1 Key Characteristics of list:
(i) Ordered: Items keep the exact sequence they are added in.
(ii) Indexed: Each item has a position starting from 0.
(iii) Mutable(changeable): You can add, remove, or modify elements after creating the list.
18.2 Real-Life Use Cases
(i) E-Commerce Shopping Cart: Storing items a user adds to their online cart.
(ii) Todo & Task Managers: Keeping track of daily tasks to mark off as completed.
(iii) Music Playlists: Maintaining a queue of songs to play in specific order.
(iv) Sensor Data Logging: Collecting continuous temperature or heart rate readings over time.
18.3 List methods
List methods in Python are built-in functions that belong specifically to list objects. They allow you to add, remove, search, reorder, or manipulate the elements inside a list directly.
| Method | What it does |
| 1. append() | Add 1 item to end |
| 2. insert() | Add 1 item at index |
| 3. extend() | Add all items from another list |
| 4. pop() | Remove by index (returns value) |
| 5. remove() | Remove first matching value |
| 6. clear() | Wipe entire list |
| 7. index() | Get index of a value |
| 8. count() | Count occurrences of a value |
| 9. sort() | Sort elements (A-Z / 1-9) |
| 10. reverse() | Flip list order |
| 11. copy() | Make a duplicate list |
append() method
Adds a single item to the end of the existing list.
Syntax: list.append(element)
nums = [10, 20]
nums.append(30)
print(nums) # Output: [10, 20, 30]
insert() method
Inserts an item at a specific index position, shifting rightward elements.
The index always begins from 0. So, the first list element always has index[0] so as the second list element has index[1] and so on.
Syntax: list.insert(index, element)
colors = ["red", "blue"]
colors.insert(1, "green")
print(colors) # Output: ['red', 'green', 'blue']
extend() method
Merges all items from another list or iterable onto the end.
Syntax: list.extend(iterable)
fruits = ["apple"]
fruits.extend(["banana", "mango"])
print(fruits) # Output: ['apple', 'banana', 'mango']
pop() method
Removes and returns an item from a specified index (defaults to the last item).
Syntax: list.pop([index])
items = ["a", "b", "c"]
removed_item = items.pop(1)
print(removed_item, items) # Output: b ['a', 'c']
remove() method
Deletes the first matching occurrence of a specified value from the list.
Syntax: list.remove(element)
data = [5, 10, 5, 20]
data.remove(5)
print(data) # Output: [10, 5, 20]
clear() method
Removes all elements, leaving the list completely empty.
Syntax: list.clear()
tags = ["python", "code"]
tags.clear()
print(tags) # Output: []
index() method
Finds and returns the index position of the first matching value.
Syntax: list.index(element)
letters = ["x", "y", "z"]
pos = letters.index("y")
print(pos) # Output: 1 count() method
Returns the total number of times a specific value occurs in the list.
Syntax: list.count(element)
scores = [1, 2, 1, 3, 1]
total = scores.count(1)
print(total) # Output: 3
sort() method
Reorders elements directly inside the original list in ascending or customized order.
Syntax: list.sort(key=None, reverse=False)
nums = [40, 10, 30]
nums.sort()
print(nums) # Output: [10, 30, 40]
reverse() method
Inverts the sequence of elements in the list without sorting them by value.
Syntax: list.reverse()
chars = ["a", "b", "c"]
chars.reverse()
print(chars) # Output: ['c', 'b', 'a']
copy() method
Creates an independent shallow duplicate of the list.
Syntax: new_list = list.copy()
original = [1, 2, 3]
duplicate = original.copy()
print(duplicate) # Output: [1, 2, 3]
del () keyword
Deletes variables, individual list items, or slice ranges directly from memory without returning a value.
Syntax: del object or del list[index] or del list[start:stop]
# 1. Delete a specific list item by index
nums = [10, 20, 30, 40]
del nums[1]
print(nums) # Output: [10, 30, 40]
# 2. Delete a slice (range of items)
del nums[0:2]
print(nums) # Output: [40]
# 3. Delete an entire variable from memory
x = 100
del x
# print(x) # Raises NameError: name 'x' is not defined
List length
Returns the total number of items stored in a list.
Syntax: len(list)
fruits = ["apple", "banana", "cherry"]
total_items = len(fruits)
print(total_items) # Output: 3
Looping through List
Iterates over each item directly without needing indices.
Syntax: for item in list:
names = ["Gita", "Santoshi", "Sita"]
for item in names:
print(item)Gita
Santoshi
Sita
Built-in Functions
- Standalone names followed by parentheses ().
- Call them directly anywhere.
- Example: len(), print(), input(), type(), range(), sum()
Methods
- Attached to an object with dot notation .
- Belong to specific data types.
- Example: list.append(), str.upper(), dict.keys()
Keywords
- Reserved words with no parentheses.
- Built into Python syntax.
- Example: del, for, if, return, import
19. Python Dictionary
A dictionary in Python is an ordered, mutable collection of data that stores elements in key-value pairs. Each key within a dictionary must be unique and immutable (such as a string, number, or tuple), mapped directly to an associated value of any data type.
Key Properties
(i) Key-Value Mapping: Data is retrieved by referencing its key rather than a numerical index.
(ii) Uniqueness: Keys cannot contain duplicates; assigning a value to an existing key overwrites the previous value.
(iii) Mutability: Elements can be added, modified, or removed after creation.
In Python, dictionaries are used to store data in Key: Value pair.
A dictionary is a collection of data in Key: Value pairs, written within curly braces { }.
Features of dictionary
Dictionaries are changeable:
del () keyword
Accessing the value in dictionary
Dictionary length
Looping through Dictionary
List Vs. Dictionary
| List | Dictionary |
| 1. A list stores elements in a sequence. |
1. A dictionary stores data in key:value pairs. |
| 2. List elements are accessed by index. |
2. Dictionary values are accessed by keys. |
| 3. List elements have an order. |
3. Dictionary values don’t have any specific order. |
| 4. List elements can be added and removed. |
4. Dictionary values are added as key:value pair and removed by key. |
20. Uses of Library Functions
20.1 String Functions(center, upper, lower,len)
20.2 Numeric and mathematical Functions(sum, pow, round, abs, sqrt, int)