Python
Python is a language of coding used all over the world for different tasks in AI,
Factories where machines are used, web development, Data Science,
Application, Game development etc.
We can use different Python programming app like colab by google, Visual Studio
Code, Pycharm,etc.
Printing
Printing is a function used to display outputs
Example:
Printing Hello World for first time in python:
print(“Hello World!”)
Output:
Hello World!
Printing two different string in one time:
print("Hello"+"Aditya")
Output:
HelloAditya
Comments
Comments are lines of text after Hash (#).The lines that are ignored by the python
running code. They are used to keep explanations or notes without any error.
Example:
print(“Hello World”) #This function is used to show to output
#This is a comment
Output:
Data Types
Data that defines the values, operations, and stores information for python to run it is
called Data types.
integer(int): integer is a symbol used for numbers.
float: float is used for decimal number
string: string is used for word
boolean: boolean is used for
Example:
integer1 = int
Variables
Variable is a symbol that refers to a value that is stored.
Example:
name = Aditya
age = 12
Type conversion
Operators
Arithmetic Operators
Arithmetic operators are used to perform basic mathematical operations like
addition(+), subtraction(-), multiplication(*), division(/)
Example:
First operation:
num1 = 5
num2 = 10
num3 = num1 + num2
print(num3)
Output:
15
Second Operation:
x=69
y=5
z=x-y
print(z)
Output:
20
Simple calculator:
num1 = int(input("Enter a first nunber:"))
num2 = int(input("Enter a second nunber:"))
addition = num1 + num2
subtraction = num1 - num2
multiplication = num1 * num2
division = num1 / num2
print("Addition:", addition)
print("Subtraction:", subtraction)
print("Multiplication:", multiplication)
print("Division:", division)
Output:
Enter a first number:65
Enter a second number:5
Addition: 70
Subtraction: 60
Multiplication: 325
Division: 13.0
Comparison Operators
Operator Meaning Example Result
== Equal to 5 == 5 True
!= Not equal to 5 != 3 True
> Greater than 7>3 True
< Less than 2<8 True
>= Greater or 5 >= 5 True
equal
<= Less or equal 4 <= 6 True
Comparison Operations compare two values and decide their relation
Logical Operations
Logical operations are those operations that combine conditional statements.
Operator Example
and x>7 and x>10
or x>7 or x>10
not not(x>7and x>10)
Python Basics – Strings
A string is a sequence of characters written inside single quotes (' '), double quotes ("
"), or triple quotes (''' ''' or """ """).
Example:
name = "Python"
1. String Indexing
● Each character in a string has a position (index).
● Indexing starts from 0.
● We can also use negative indexing (from the end).
Example:
word = "Python"
print(word[0]) # P (first character)
print(word[3]) # h (4th character)
print(word[-1]) # n (last character)
Slicing “Python” with two methods:
word = "Python"
print (word[0])
print (word[-6])
print (word[1])
print (word[-5])
print (word[2])
print (word[-4])
print (word[3])
print (word[-3])
print (word[4])
print (word[-2])
print (word[5])
print (word[-1])
Output:
P
P
y
y
t
t
h
h
o
o
n
n
2. String Slicing
● Slicing means taking a part of the string using [start:end].
● start → index to begin
● end → index before which to stop (not included)
Example:
Slicing Python and Programming in different lines:
text = "PythonProgramming"
print(text[0:6])
print(text[6:17])
Output:
Python
Programming
Writing a program to print "Python" from the string "Python Programming is the
best language" using slicing.
text = "Python Programming is the Best language"
print (text[0:])
Output:
Python
3. Common String Functions
Python has many built-in string functions. Here are some useful ones:
Function Example Output
.upper() "hello".upper() HELLO
.lower() "HELLO".lower() hello
.title() "python Python
programming".title() Programming
.strip() " hello ".strip() hello (removes
spaces)
.replace() "apple".replace("a","A") Apple
.count() "banana".count("a") 3
.find() "python".find("t") 2
4. Examples
String Functions:
msg = " Hello World "
print([Link]())
Output:
HELLO WORLD
String Functions:
msg = " Hello World "
print([Link]())
Output:
hello world
String Functions:
msg = " Hello World "
print([Link]())
Output:
Hello World
String Functions:
msg = " Hello World "
print([Link]("World", "Aditya"))
Output:
Hello Aditya
String Functions:
msg = " Hello World "
print([Link]('o'))
Output:
2
Quick Tip for Students:
● Strings are like a box of letters where you can pick (index), cut (slice), and modify
(functions).
Practice Questions – Strings
1. Take your name as input and print the first character and the last character using
indexing.
Answer:
Input = input("Enter your name: ")
print(Input[0])
print(Input[5])
Output:
Enter your name: Aditya
a
2. Write a program to print "Python" from the string "I am learning Python
Programming" using slicing.
Answer:
text = "I am learning Python Programming"
print (text[14:20])
Output:
Python
3. Given word = "Programming", print:
word = "Programming"
○ First 5 characters
print (word[0:5])
○ Last 5 characters
print (word[6:11])
○ Every 2nd character
print (word[::2])
Output:
Progr
mming
Pormig
4. Write a program that takes a string and converts it to:
word = input("Enter a string: ")
○ Uppercase
print([Link]())
○ Lowercase
print([Link]())
Output:
Enter a string: ApPlE
APPLE
apple
5. Take a sentence and print how many times the letter "a" appears.
sentence = input("Enter a sentence: ")
print([Link]('a'))
Output:
Enter a sentence: dangeration
6. Write a program to remove extra spaces from .
input = " Apple ball is expensive and useful "
print([Link]())
Output:
Apple ball is expensive and usefull
7. Replace the word "dog" with "cat" in the string "I have a dog".
text = "I have a dog"
print([Link]("dog", "cat"))
Output:
I have a cat
8. Check if the string contains the word "Python"
text = "Python is a programming language"
TODO: check if "Python" is in text
if "Python" in text:
print("Yes, it contains 'Python'")
else:
print("No, it does not contain 'Python'")
Output:
Yes, it contains 'Python'
text = "I have a dog"
print([Link]("dog", "cat"))
9. Write a program to reverse a string using slicing.
word = "naman"
print(word[::-1])
Output:
naman
10.Take a word as input and print whether it is a palindrome or not. (Palindrome means
the same forward and backward, like "madam").
word = "naman"
if word == word[::-1]:
print("Yes, it is a palindrome")
else:
print("No, it is not a palindrome")
Output:
Yes, it is a palindrome
Lists & Tuples in Python
1. Lists
● A list is a collection of items (can be numbers, strings, etc.).
● Lists are mutable → you can change, add, or remove items.
● Defined using square brackets [].
Example:
fruits = ["apple", "banana", "cherry"]
print(fruits) # ['apple', 'banana', 'cherry']
Indexing in Lists
● Items are accessed using indexes.
● Index starts from 0.
● Negative indexing starts from -1 (last element).
numbers = [10, 20, 30, 40, 50]
print(numbers[0])
print(numbers[-1])
Output:
10
Slicing in Lists
● Extract part of a list.
● Syntax: list[start:end:step]
Example:
nums = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18,
19, 20]
print(nums[1:4]) # [2, 3, 4]
print(nums[:3]) # [1, 2, 3]
print(nums[::2]) # [1, 3, 5]
print(nums[::3])
print(nums[7:14])
print(nums[7:14:2])
Output:
[2, 3, 4]
[1, 2, 3]
[1, 3, 5, 7, 9, 11, 13, 15, 17, 19]
[1, 4, 7, 10, 13, 16, 19]
[8, 9, 10, 11, 12, 13, 14]
[8, 10, 12, 14]
Common List Methods
● append(item) → Add item at the end
● insert(index, item) → Add item at specific position
● remove(item) → Remove first occurrence of item
● pop(index) → Remove item by index (default last)
● sort(reverse=True) → Sort list
● reverse() → Reverse list order
nums = [3, 1, 4, 2]
[Link](5) # [3, 1, 4, 2, 5]
[Link]() # [1, 2, 3, 4, 5]
[Link]() # [5, 4, 3, 2, 1]
Output:
Append function:
animal = [ "Tiger", "Lion", "Dog", "Cat", "Snake", "Leopard" ]
[Link]('Cow')
#[Link]("Horse")
print(animal[1])
Output:
['Tiger', 'Lion', 'Dog', 'Cat', 'Snake', 'Leopard', 'Cow']
Reverse function:
nums = [1, 4, 8, 3, 7, 2, 5, 9, 6, 10, 98765, 600, 3065, 3029]
[Link]()
print(nums)
Output:
[98765, 3065, 3029, 600, 10, 9, 8, 7, 6, 5, 4, 3, 2, 1]
Reverse function:
nums = [3, 1, 4, 2]
[Link]()
print(nums)
Output:
[1, 2, 3, 4]
2. Tuples
● A tuple is similar to a list, but it is immutable (cannot be changed).
● Defined using parentheses ().
Example:
t = (100, 200, 300, 400)
print(t[0])
print(t[1])
Output:
100
200
Immutability of Tuples
● You cannot modify a tuple (add/remove/change elements).
t = (1, 2, 3)
# t[0] = 5 ❌ Error (cannot modify tuple)
● But you can convert tuple → list → tuple to make changes.
t = (1, 2, 3)
temp = list(t) # convert to list
[Link](4)
t = tuple(temp) # convert back to tuple
print(t) # (1, 2, 3, 4)
3. When to use List vs Tuple
● List → When you need a collection that can change (dynamic).
● Tuple → When you need a fixed collection (constant data).
Practice Questions (Lists & Tuples)
1. Create a list of 5 numbers and print the second and last element.
t = [1, 2, 3, 45, 12345]
print(t[1])
print(t[-1])
print(t[4])
Output:
12345
12345
2. Write a program to slice a list and print elements from index 2 to 5.
nums = [1, 2, 3, 4, 5, 6, 7]
print(nums[2:6])
Output:
[3, 4, 5, 6]
3. Add "grapes" to the list ["apple", "banana"].
fruits = ["Apple", "Banana"]
[Link]("Grapes")
print(fruits)
Output:
['Apple', 'Banana', 'Grapes']
4. Remove the number 30 from the list [10, 20, 30, 40].
nums = [10, 20, 30, 40]
[Link](30)
print(nums)
Output:
[10, 20, 40]
5. Sort the list [5, 3, 8, 1] in ascending order.
nums = [5, 3, 8, 1]
[Link]()
print(nums)
Output:
[1, 3, 5, 8]
6. Reverse the list [10, 20, 30, 40].
nums = [10, 20, 30, 40]
[Link]()
print(nums)
Output:
[40, 30, 20, 10]
7. Create a tuple with 4 elements and print its first two items.
t = (100, 200, 300, 400)
print(t[0:2])
Output:
(100, 200)
8. Convert tuple (10, 20, 30) into a list, add 40, then convert back to a tuple.
t = (10, 20, 30)
temp = list(t)
[Link](40)
tup =tuple(temp)
print(tup)
Output:
(10, 20, 30, 40)
9. Take two lists and join them into one list.
listno1 = [1, 2, 3]
listno2 = [4, 5, 6]
finallist = listno1 + listno2
print(finallist)
Output:
[1, 2, 3, 4, 5, 6]
10.Write a program to check if an element exists in a tuple.
t = (1,2,3,4,5,6,7,8,9,10)
element = int(input("Enter a number "))
if element in t:
print("Element Found In Tuple")
else:
print('Element Not Found')
Output:
Enter a number 67
Element Not Found
Dictionaries & Sets
1. Dictionaries
A dictionary is a collection of key–value pairs in Python.
Each key must be unique and immutable (like strings, numbers, or
tuples).
Values can be of any type and can repeat.
Syntax
dictionary_name = {
"key1": "value1",
"key2": "value2"
Example
my_dict = {
"name": "Aditya",
"age": 12,
"city": "Bhaktapur"
student = {"name": "Ram","age": 17,"grade": "A",”Roll”: 12}
print(student)
Accessing values:
print(my_dict["name"]) # Output: Aditya
print(my_dict.get("age")) # Output:
Adding / Updating values:
my_dict["Class"] =
my_dict["age"] =
Removing items:
my_dict.pop("city") # Removes key 'city'
del my_dict["age"] # Deletes key 'age'
my_dict.clear() # Empties dictionary
Looping:
for key, value in my_dict.items():
print(key, value)
2. Sets
A set is a collection of unique and unordered elements.
It automatically removes duplicates.
Syntax
my_set = {1, 2, 3, 3, 4}
print(my_set) # Output: {1, 2, 3, 4}
Adding / Removing items:
my_sefsdt.add(5)
my_set.remove(3)
Set Operations:
A = {1, 2, 3, 4}
B = {3, 4, 5, 6}
print(A | B) # Union → {1, 2, 3, 4, 5, 6}
print(A & B) # Intersection → {3, 4}
print(A - B) # Difference → {1, 2}
print(A ^ B) # Symmetric Difference → {1, 2, 5, 6}
Conditional Statements in Python
Conditional statements are used to make decisions in a program.
They allow the program to choose what to do depending on some condition (True or False).
Syntax
if condition:
# code runs if condition is True
elif another_condition:
# code runs if first condition is False but this one is True
else:
# code runs if all above conditions are False
Example
age = 12
if age >= 18:
print("You are an adult.")
elif age >= 13:
print("You are a teenager.")
else:
print("You are a child.")
Explanation:
● If age is 18 or more → prints “You are an adult.”
● If the age is not 18 but at least 13 → prints “You are a teenager.”
● Otherwise → prints “You are a child.”
Practice 1. Check if a number is positive or negative
# Program to check if a number is positive or negative
num = int(input("Enter a number: "))
if num > 0:
print("The number is positive.")
elif num == 0:
print("The number is zero.")
else:
print("The number is negative.")
# Explanation:
# We check three cases using if, elif, and else.
2. Check if a number is even or odd
# Program to check even or odd
num = int(input("Enter a number: "))
if num % 2 == 0:
print("Even number")
else:
print("Odd number")
# Explanation:
# If the remainder after dividing by 2 is 0 → Even, otherwise Odd.
Output
num = 5
odd number
Loops in Python
What is a Loop?
A loop is used when we want to repeat something again and again.
For example:
● Say “Hello” 5 times
● Print numbers 1 to 10
● Add all numbers in a list
Instead of writing the same line many times, we use a loop!
Syntax:
for variable in sequence:
# code to repeat
Example
Print your name 5 times
for i in range(5):
print("Hello, I am Aditya!")
While Loop
Repeat while a condition is True
A while loop keeps running as long as a condition is true.
It’s like saying:
“Keep doing this until I tell you to stop!”
Example
[Link] numbers 1 to 5
num = 1
while num <= 5:
print(num)
num += 1
Output
1
2
3
4
5
Nested Loops
Loop inside another loop
A nested loop means → one loop runs inside another loop.
Think of it like:
Outer loop = rows
Inner loop = columns
Example
Loop Control Statements in Python
Loop control statements change how the loop behaves — they can stop, skip, or
do nothing (temporarily) inside a loop.
There are 3 main types:
break
continue
pass
Break - Stop the loop completely
Theory:
The break statement is used to exit (stop) the loop even if the loop condition is
still true.
Example
for i in range(1, 11):
if i == 5:
break # stop the loop when i becomes 5
print(i)
Continue — Skip the current loop and move to next one
Theory:
The continue statement tells Python to skip the rest of the code inside the loop for
that iteration and continue to the next round.
Example
for i in range(1, 6):
if i == 3:
continue
print(i)
Pass - Do nothing
Theory:
The pass statement does nothing — it’s used when a statement is required but
you don’t want any code to run yet.
Example
for i in range(1,6):
if i == 3:
pass
print(i)
Functions (defining, parameters, return values)
Theory:
What is a Function?
A function is a block of code that runs only when it is called.
Why use functions?
To reuse code (write once, use many times)
To make your code organized and easy to read
To divide a big problem into smaller parts
def → keyword to define a function
greet → function name
() → parentheses (can hold inputs, called parameters)
Inside the function: we write the code to run