Python
RAJAD SHAKYA
Why Python?
● Readability
● Versatility
● Large Standard Library
● Free and Open-Source
Static vs. Dynamic Typing
● Statically Typed Languages
○ You declare the data type of a variable at the time of
definition
○ prevent runtime errors but may require more verbose
code
○ e.g., C++, Java
○ int age = 30; // Declares an integer variable 'age'
○ age = "thirty"; // Compiler error!
Static vs. Dynamic Typing
● Dynamically Typed Languages
○ data type of a variable is not explicitly declared
○ offers flexibility but can lead to runtime errors if
you accidentally assign an incompatible type.
○ e.g., Python, JavaScript
○ age = 30 # Implicitly integers
○ age = "thirty" # Works
Variables
● named containers that store data throughout your
program.
● allow you to manage and manipulate information
during code execution.
Variable Naming Rules:
● Start with a letter or underscore (_)
● Variable names can only contain letters (A-Z, a-z),
numbers (0-9), and underscores (_).
● Special characters like symbols or spaces are not
allowed.
● Case-Sensitive:
● Avoid Keywords
Naming Conventions:
● Snake_case:
○ This convention uses underscores to separate
words (e.g., first_name, total_cost).
● CamelCase:
○ This convention starts each word with a capital
letter (e.g., firstName, totalPrice).
Variable Naming Rules:
● My_variable
● 1st_name
● If
● _temporary_value
● Total-cost
● user_age
Data Types in Python
● Integers (int): Whole numbers (e.g., 10, -5, 0).
● Floats (float): Decimal numbers (e.g., 3.14, -2.5).
● Strings (str): Text data enclosed in quotes (single ''
or double "").
● Booleans (bool): Logical values representing True or
False.
Data Types in Python
● print(type(1))
● print(type(1.1))
● print(type('1.1'))
● print(type(True))
Data Types in Python
● number = "123"
● numeric_value = int(number)
# Convert string to integer
● print(type(numeric_value))
Data Types in Python
● Lists (list):
○ Ordered, mutable collections of elements
enclosed in square brackets []
○ Elements can be of different data types.
Data Types in Python
● Tuples (tuple):
○ Ordered, immutable collections of elements
enclosed in parentheses ().
○ Elements cannot be changed after creation.
Data Types in Python
● Dictionaries (dict):
○ Unordered collections of key-value pairs
enclosed in curly braces {}.
○ Keys must be unique and immutable (often
strings or numbers).
○ Values can be of any data type.
print()
● fundamental tool for displaying output to the
console or a specified file.
○ print("Hello, world!")
○ name = "Alice"
○ age = 30
○ print(name, "is", age, "years old.")
○ print("Hello", end="")
○ print("World!")
F-strings:
● allow you to directly embed variables within a string
for clear formatting:
○ name = "Bob"
○ age = 25
○ print(f"{name} is {age} years old.")
input():
● allows you to get user input during program
execution.
● name = input("What is your name? ")
● print("Hello,", name + "!")
● input() always returns a string, even if the user
enters a number.
input():
● Get user's age and convert to integer for calculation:
age = int(input("How old are you? "))
year_born = 2024 - age
print("You were born in", year_born)
input():
● Get user's favorite number and display a message:
fav = input("What is your favorite number? ")
print("Interesting choice! " + fav + " is a great number.")
Question
name = "Bob"
age = 25
# Concatenate the following string using f-strings:
# "Hello, my name is ___ and I am ___ years old."
print(f"Hello, my name is {name} and I am {age} years
old.")
Question
Write a Python program that asks the user for their
favorite color and stores it in a variable. Print a message
that says "Your favorite color is [color]".
Question
Given variables `first_name` and `last_name`, write a
print statement using an f-string to display "Hello,
[first_name] [last_name]!".
print(f"Hello, {first_name} {last_name}!")
Question
Write a program that takes two numbers as input from
the user, converts them to integers, and prints their
product.
num1 = int(input("Enter the first number: "))
num2 = int(input("Enter the second number: "))
product = num1 * num2
print(f"The product of {num1} and {num2} is
{product}.")
Question
Write a program that takes two numbers as input from
the user, converts them to integers, and prints their
product.
num1 = int(input("Enter the first number: "))
num2 = int(input("Enter the second number: "))
product = num1 * num2
print(f"The product of {num1} and {num2} is
{product}.")
Arithmetic Operators
Addition (+)
Subtraction (-)
Multiplication (*)
Division (/)
Arithmetic Operators
Floor Division (//)
Modulus (%)
Exponentiation (**)
Question
a = 10
b=3
result = a // b + a
print(result)
Comparison Operators
Equal (==)
Not Equal (!=)
Greater Than (>)
Less Than (<)
Comparison Operators
Greater Than or Equal To (>=)
Less Than or Equal To (<=)
Logical Operators
And (and)
Or (or)
Not (not)
Logical Operators
And (and)
Or (or)
Not (not)
Logical Operators
x=7
y=7
result = x >= y
print(result)
Logical Operators
a = True
b = False
c = a and not b
print(c)
Logical Operators
x=4
y = 10
result = (x < 5) or (y > 15)
print(result)
Assignment Operators
Equals (=)
Add and Assign (+=)
Subtract and Assign (-=)
Multiply and Assign (*=)
Divide and Assign (/=)
Modulus and Assign (%=)
Question
x = 15
x -= 5
x *= 2
print(x)
Question
a=9
a /= 3
a += 2
print(a)
Question
Calculate the area of a triangle given the base and
height.
base = 10
height = 5
area = 0.5 * base * height
print(area)
Question
Double a number and then add 10 using assignment
operators.
num = 5
num *= 2
num += 10
print(num)
Question
string = "hello"
result = string * 3
print(result)
hellohellohello
Question
condition1 = (5 == 5)
condition2 = (10 < 5)
result = condition1 or condition2
print(result)
Output: True
Question
Concatenate two strings using assignment operators.
string1 = "Hello, "
string2 = "World!"
string1 += string2
print(string1)
Question
word = "hi"
repeated_word = word * 4
print(repeated_word)
Lists
● mutable, ordered collection of elements that can
contain elements of different data types.
● # Creating an empty list
● my_list = []
● # Creating a list with elements
● my_list = [1, 2, 3, 'a', 'b', 'c']
Indexing
● # Accessing elements
● first_element = my_list[0]
● #1
● second_element = my_list[1]
● #2
● last_element = my_list[-1]
● # 'c'
Slicing
● # Slicing syntax: list[start:stop:step]
● subset = my_list[1:4]
● # [2, 3, 'a']
● every_second_element = my_list[::2]
● # [1, 3, 'b']
● reverse_list = my_list[::-1]
● # ['c', 'b', 'a', 3, 2, 1]
Modifying Lists
● # Changing an element
● my_list[0] = 10
● # Adding elements
● my_list.append(4)
● # Adds 4 at the end
● my_list.insert(2, 'x')
● # Inserts 'x' at index 2
Modifying Lists
● # Removing elements
● my_list.remove('a')
● # Removes the first occurrence of 'a'
● popped_element = my_list.pop(1)
● # Removes and returns the element at index 1
● del my_list[0]
● # Deletes the element at index 0
Other List Operations
● # Length of the list
● length = len(my_list)
● # Checking for existence
● exists = 3 in my_list # True if 3 is in the list
● # Concatenation
● new_list = my_list + [5, 6, 7]
● # Repetition
● repeated_list = my_list * 2
Tuples
● immutable, ordered collection of elements that can
contain elements of different data types.
● # Creating an empty tuple
● my_tuple = ()
● # Creating a tuple with elements
● my_tuple = (1, 2, 3, 'a', 'b', 'c')
Indexing
● # Accessing elements
● first_element = my_tuple[0]
● #1
● second_element = my_tuple[1]
● #2
● last_element = my_tuple[-1]
● # 'c'
Slicing
● # Slicing syntax: tuple[start:stop:step]
● subset = my_tuple[1:4]
● # (2, 3, 'a')
● every_second_element = my_tuple[::2]
● # (1, 3, 'b')
● reverse_tuple = my_tuple[::-1]
● # ('c', 'b', 'a', 3, 2, 1)
Immutability
● # Attempting to change an element will raise an
error
● # my_tuple[0] = 10
● # TypeError: 'tuple' object does not support item
assignment
Question
● Create a list with the elements 1, 2, 3, 4, and 5.
Then change the third element to 10.
● my_list = [1, 2, 3, 4, 5]
● my_list[2] = 10
● print(my_list)
● # Output: [1, 2, 10, 4, 5]
Question
● Given the list [10, 20, 30, 40, 50], print the first
three elements using slicing.
● my_list = [10, 20, 30, 40, 50]
● first_three = my_list[:3]
● print(first_three)
● # Output: [10, 20, 30]
Question
● Create an empty list and add the elements 'a', 'b',
and 'c' to it. Then insert 'd' at the second position.
● my_list = []
● my_list.append('a')
● my_list.append('b')
● my_list.append('c')
● my_list.insert(1, 'd')
● print(my_list)
● # Output: ['a', 'd', 'b', 'c']
Question
● Given the nested list [[1, 2, 3], [4, 5, 6], [7, 8, 9]],
access the element 5.
● nested_list = [[1, 2, 3], [4, 5, 6], [7, 8, 9]]
● element = nested_list[1][1]
● print(element)
● # Output: 5
Question
● Multiply the list ['a', 'b', 'c'] by 3 and print the result.
● my_list = ['a', 'b', 'c']
● multiplied_list = my_list * 3
● print(multiplied_list)
● # Output: ['a', 'b', 'c', 'a', 'b', 'c', 'a', 'b', 'c']
Question
● Given the nested list [['a', 'b', 'c'], ['d', 'e', 'f'], ['g', 'h',
'i']], replace 'f' with 'x' and print the result.
● nested_list = [['a', 'b', 'c'], ['d', 'e', 'f'], ['g', 'h', 'i']]
● nested_list[1][2] = 'x'
● print(nested_list)
● # Output: [['a', 'b', 'c'], ['d', 'e', 'x'], ['g', 'h', 'i']]
Indentation
● it defines the structure and flow of the code.
● Unlike many other programming languages that use
braces {} to define blocks of code, Python uses
indentation levels.
● Consistent indentation is required to group
statements together
Conditionals
● statements that run or skip code based on whether
a condition is true or false.
● if, elif, and else.
● age = 18
if age >= 18:
print("You are an adult.")
if Statement
● used to test a condition
● If the condition evaluates to True, the code block
under the if statement is executed.
● age = 18
if age >= 18:
print("You are an adult.")
elif Statement
● allows you to check multiple conditions, one after
the other.
● The first condition that evaluates to True will
execute its block of code, and the rest will be
skipped.
● age = 15
if age >= 18:
print("You are an adult.")
elif age >= 13:
print("You are a teenager.")
elif Statement
● allows you to check multiple conditions, one after
the other.
● The first condition that evaluates to True will
execute its block of code, and the rest will be
skipped.
● age = 15
if age >= 18:
print("You are an adult.")
elif age >= 13:
print("You are a teenager.")
else Statement
● catches anything that isn’t caught by the preceding
conditions.
● If none of the if or elif conditions are True, the else block
is executed.
● age = 10
if age >= 18:
print("You are an adult.")
elif age >= 13:
print("You are a teenager.")
else:
print("You are a child.")
Nested Conditionals
● You can nest conditionals within each other to check
more complex conditions.
● age = 25
if age >= 18:
if age >= 21:
print("Greater than 21")
else:
print("between 18-21")
else:
print("You are not an adult.")
Ternary Operator
● shorthand form of the if-else statement
● age = 18
status = "Adult" if age >= 18 else "Minor"
print(status)
Question
● Write a program that checks if a number is positive
and prints "Positive" if it is.
● number = 10
if number > 0:
print("Positive")
Question
● Write a program that checks if a number is even or
odd and prints "Even" or "Odd" accordingly.
● number = 4
if number % 2 == 0:
print("Even")
else:
print("Odd")
Question
● Write a program that categorizes a person's age into
"Child", "Teenager", "Adult", or "Senior".
● age = 45
if age < 13:
print("Child")
elif age < 18:
print("Teenager")
elif age < 65:
print("Adult")
else:
print("Senior")
Question
● Write a program that checks if a number is within
the range 1-10, 11-20, or greater than 20, and
prints the range.
● number = 15
if number >=0 and number <= 10:
print("1-10")
else:
if number <= 20:
print("11-20")
else:
print("Greater than 20")
Question
● Write a program that checks if a number is between
10 and 20 (inclusive) and prints "In range" if it is.
● number = 15
if number >= 10 and number <= 20:
print("In range")
Question
● Write a program that checks if a given string is
"Python" and prints "Correct" if it is, otherwise
"Incorrect".
● word = "Python"
if word == "Python":
print("Correct")
else:
print("Incorrect")
Question
● Write a program that checks if a number is either
less than 5 or greater than 15 and prints "Out of
range" if it is.
● number = 18
if number < 5 or number > 15:
print("Out of range")
Question
● Write a program that uses a ternary operator to
check if a number is positive and prints "Positive" or
"Non-positive".
● number = -3
result = "Positive" if number > 0 else "Non-positive"
print(result)
Looping
● allows you to execute a block of code repeatedly.
● for loops and while loops.
● while Loop
○ repeats a block of code as long as a condition is
true.
While loop
● count = 0
while count < 5:
print(count)
count += 1
# Output:
#0
#1
#2
#3
#4
for Loop
● used to iterate over a sequence (such as a list, tuple,
dictionary, set, or string).
fruits = ["apple", "banana", "cherry"]
for fruit in fruits:
print(fruit)
# Output:
# apple
# banana
# cherry
range Function
● generates a sequence of numbers, which is often
used in for loops.
for i in range(5):
print(i)
# Output:
#0
#1
#2
#3
#4
Iterating Over a String
● generates a sequence of numbers, which is often
used in for loops.
for char in "Python":
print(char)
# Output:
#P
#y
#t
#h
#o
#n
break
○ Exits the loop immediately, skipping the rest of the
code inside the loop.
for i in range(10):
if i == 5:
break
print(i)
# Output:
# 01234
continue
○ Skips the current iteration and moves to the next
iteration of the loop.
for i in range(10):
if i % 2 == 0:
continue
print(i)
# Output:
# 13579
Nested Loops
○ A loop inside another loop is called a nested loop.
for i in range(3):
for j in range(2):
print(f"i: {i}, j: {j}")
# Output:
# i: 0, j: 0
# i: 0, j: 1
# i: 1, j: 0
# i: 1, j: 1
# i: 2, j: 0
# i: 2, j: 1
Question
○ Write a `for` loop that prints the numbers from 1 to
10.
for i in range(1, 11):
print(i)
Question
○ Write a `for` loop that calculates the sum of all
numbers in the list [1, 2, 3, 4, 5].
numbers = [1, 2, 3, 4, 5]
total = 0
for num in numbers:
total += num
print(total)
# Output: 15
Question
○ Write a `while` loop that prints the numbers from
10 to 1 in descending order.
count = 10
while count > 0:
print(count)
count -= 1
Question
○ Write a `for` loop that prints numbers from 1 to 10,
but stops if the number is 7.
for i in range(1, 11):
if i == 7:
break
print(i)
Question
○ Write a `for` loop that prints all numbers from 1 to
10 except 5.
for i in range(1, 11):
if i == 5:
continue
print(i)
Functions
● allowing you to encapsulate code into reusable
blocks.
● help in organizing code,
● improving readability, and
● avoiding repetition.
Defining a Function
● defined using the def keyword followed by the
function name, parentheses (), and a colon :.
● The function body is indented.
def greet():
print("Hello, world!")
Calling a Function
● Once a function is defined, you can call it by using its
name followed by parentheses.
● greet() # Output: Hello, world!
Function Parameters & Arguments
● Functions can take parameters, which are specified
within the parentheses.
● When calling the function, you pass arguments to
these parameters.
def greet(name):
print(f"Hello, {name}!")
greet("Alice") # Output: Hello, Alice!
Default Parameters
● can provide default values for parameters.
● If an argument is not passed, the default value is
used.
def greet(name="world"):
print(f"Hello, {name}!")
greet() # Output: Hello, world!
greet("Alice") # Output: Hello, Alice!
Returning Values
● Functions can return values using the return
statement.
def add(a, b):
return a + b
result = add(3, 4)
print(result) # Output: 7
Question
● Define a function `check_even` that takes a number
and returns True if the number is even, and False
otherwise. Call the function with the argument 7
and print the result.
def check_even(num):
return num % 2 == 0
result = check_even(7)
print(result) # Output: False
Question
● Define a function `find_max` that takes three
numbers and returns the maximum of the three. Call
the function with the arguments 10, 20, and 15, and
print the result.
def find_max(a, b, c):
return max(a, b, c)
result = find_max(10, 20, 15)
print(result) # Output: 20
Question
● Define a function `sum_list` that takes a list of
numbers and returns their sum. Call the function
with the list [1, 2, 3, 4, 5] and print the result.
def sum_list(numbers):
return sum(numbers)
result = sum_list([1, 2, 3, 4, 5])
print(result) # Output: 15
Question
● Define a function `power` that takes two
parameters, `base` and `exp`, with `exp` defaulting
to 2, and returns `base` raised to the power of `exp`.
Call the function with only the argument 3 and print
the result.
def power(base, exp=2):
return base ** exp
result = power(3)
print(result) # Output: 9
Question
● Define a function `power` that takes two
parameters, `base` and `exp`, with `exp` defaulting
to 2, and returns `base` raised to the power of `exp`.
Call the function with only the argument 3 and print
the result.
def power(base, exp=2):
return base ** exp
result = power(3)
print(result) # Output: 9
Question
● Define a function `concat_strings` that takes two
strings and returns their concatenation. Call the
function with the arguments "Hello" and "World"
and print the result.
def concat_strings(str1, str2):
return str1 + str2
result = concat_strings("Hello", "World")
print(result) # Output: HelloWorld
Question
● Define a function `rectangle_perimeter` that takes
the length and width of a rectangle and returns the
perimeter. Call the function with the arguments 4
and 7 and print the result.
def rectangle_perimeter(length, width):
return 2 * (length + width)
result = rectangle_perimeter(4, 7)
print(result) # Output: 22
Modules
● files containing Python code (functions, classes,
variables, etc.) that can be imported and used in
other Python programs.
● They help in organizing code into manageable and
reusable components
● makes the development process more efficient and
organized.
Creating a Module
● A module is simply a Python file with a .py
extension.
# mymodule.py
def greet(name):
return f"Hello, {name}!"
def add(a, b):
return a + b
PI = 3.14159
Importing a Module
● using the import statement.
# Importing the entire module
import mymodule
print(mymodule.greet("Alice"))
# Output: Hello, Alice!
print(mymodule.add(3, 4))
# Output: 7
print(mymodule.PI)
# Output: 3.14159
Importing Specific Components
● You can import specific components (functions,
variables, classes) from a module using the from
keyword.
from mymodule import greet, add, PI
print(greet("Bob")) # Output: Hello, Bob!
print(add(5, 6)) # Output: 11
print(PI) # Output: 3.14159
Using Aliases
● You can give an imported module or component a
different name using the as keyword
● can help avoid naming conflicts or make the code
more readable.
Using Aliases
# Using an alias for the module
import mymodule as mm
print(mm.greet("Charlie")) # Output: Hello, Charlie!
print(mm.add(7, 8)) # Output: 15
print(mm.PI) # Output: 3.14159
Question
● Create a module called my_math that contains
functions add and sub that takes two numbers an
returns their sum and difference respectively.
● Import add function using default import
● Import sub function using from … import syntax
Built-in Modules
● Python comes with a standard library of built-in
modules that provide many useful functions and
utilities.
● math: Provides mathematical functions.
● os: Provides functions for interacting with the
operating system.
● random: Provides functions for generating random
numbers.
Built-in Modules
import math
print(math.sqrt(16)) # Output: 4.0
print(math.factorial(5)) # Output: 120
print(math.pi) # Output: 3.141592653589793
Installing External Modules
● using pip, which is the package installer for Python.
● pip install requests
● For mac,
pip3 install requests
Thank You
RAJAD SHAKYA