ML0_Python
ML0_Python
RAJAD SHAKYA
Why Python?
● Readability
● Versatility
● 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).
● 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):
○ name = "Bob"
○ age = 25
○ print(f"{name} is {age} years old.")
input():
● allows you to get user input during program
execution.
Subtraction (-)
Multiplication (*)
Division (/)
Arithmetic Operators
Floor Division (//)
Modulus (%)
Exponentiation (**)
Question
a = 10
b=3
result = a // b + a
print(result)
Comparison Operators
Equal (==)
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.
● 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.
● 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
● 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.
● 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.
● age = 18
if age >= 18:
print("You are an adult.")
if Statement
● used to test a condition
● 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.
● while 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.
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.
● avoiding repetition.
Defining a Function
● defined using the def keyword followed by the
function name, parentheses (), and a colon :.
def greet():
print("Hello, world!")
Calling a Function
● Once a function is defined, you can call it by using its
name followed by parentheses.
def greet(name):
print(f"Hello, {name}!")
def greet(name="world"):
print(f"Hello, {name}!")
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 sum_list(numbers):
return sum(numbers)
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.
● For mac,
pip3 install requests
Thank You
RAJAD SHAKYA