Copy of Day 1 Python
Copy of Day 1 Python
1 Python Notes
1.1 Introduction
• Python: High-level, interpreted, general-purpose programming language.
• Key Features:
– Easy to learn and read.
– Dynamically typed (no need to declare variable types).
– Supports multiple programming paradigms (procedural, object-oriented, functional).
1.3 Comments:
• Single-line: # This is a comment
• Multi-line: “ “ ” This is a multi-line comment “ “ ”
Let’s check an example of simple basic syntax
Hello World!
[7]: w = y*4
print(w)
1
[4]: print(x)
print(type(x))
2
<class 'int'>
[ ]: print(y)
Hello World
Chijioke Henry
2.2 2. Numeric
• Types:
– int (e.g., 10)
– float (e.g., 3.14)
– complex (e.g., 2 + 3j)
2
2.3 3. Sequence
• Types:
– list (e.g., [1, 2, 3])
– tuple (e.g., (1, 2, 3))
– range (e.g., range(5))
2.4 4. Mapping
• Type: dict (dictionary)
• Example: {"name": "anusha", "age": 25}
2.5 5. Set
• Types:
– set (e.g., {1, 2, 3})
– frozenset (immutable set)
2.6 6. Boolean
• Type: bool
• Example: True, False
---------------------------------------------------------------------------
AttributeError Traceback (most recent call last)
Cell In[13], line 2
1 countries = ("Nepal", "India", "Bangladesh")
3
----> 2 countries.append("Nigeria")
[14]: print(countries[0])
Nepal
[ ]:
[ ]: print(type(my_info))
print(type(book))
print(type(is_okay))
<class 'dict'>
<class 'list'>
<class 'bool'>
3 Type Casting
Definition: Changing from one data type to another data type.
3.1 Example
• Converting a float (2.5) to an integer: “‘python a = int(2.5) print(a) # Output: 2
[1]: a = 2.5
b = int(a)
print(b)
[2]: x=(3,5.7)
print(type(x))
<class 'tuple'>
[4]: y = list(x)
y.append(9)
print(y)
[3, 5.7, 9]
4
3.1.1 Exercise 1.2
[ ]: # Write code below to create a muliple variable of different date type.
# ---Your code in here---
5
11
[ ]: # Example:
Input Output
True False
False True
2. and
6
Input 1 Input 2 Output
False True False
False False False
[8]: True
[9]: True
[10]: True
[11]: # Example of the precedence of the condition. Same can be applied for normal␣
↪calculation as well.
[11]: False
False
True
7
3.2.7 Identity operator
Operator that identify the operator. ‘is’
[ ]: x= 3
[ ]: type(x) is int
[ ]: True
[ ]: type(x) is float
[ ]: False
[ ]: type(x) is str
[ ]: False
[14]: False
4 Practice Problems
1. Evaluate the following expressions step by step:
• not (5 > 3) or (2 < 4 and 3 > 1)
• not True or False) and (5 == 5)
• not (False and True) or (True and not False) Instruction: You can copy the question
from here and run it in the cells down below.
8
4.0.1 Python List
A list is a collection data type in Python that is used to store multiple elements in a single variable.
Lists can hold items of different data types, but for optimized processing, it is recommended to
store elements of the same data type.
Characteristics of Lists:
• Ordered: Elements maintain their insertion order.
• Mutable: Elements can be changed after the list is created.
• Allows Duplicate Items: Lists can contain multiple elements with the same value.
• Can Store Mixed Data Types: Though it’s more efficient to use the same data type for faster
processing.
print(my_book_list)
<class 'list'>
[ ]: 4
9
4.1.1 1. Positive Indexing
• Positive indexing starts from 0 for the first element and increments by 1 for each subsequent
element. It accesses elements from left to right. ### 2. Negative Indexing
• Negative indexing starts from -1 for the last element and decrements by 1 as you move
towards the start of the list. It accesses elements from right to left.
print(my_book_list)
[ ]: # Positive indexing
print(my_book_list[1])
[ ]: #negative indexing
print(my_book_list[-3])
10
4.2 Range in List
The range in a list allows you to access a subset of elements from the list using slicing. You can
specify the start, stop, and optional step values to define the range.
4.2.1 Syntax:
list_name[start:stop:step]
where: - start: The index to begin slicing (inclusive). - stop: The index to stop slicing (exclusive).
- step: The increment value (optional). Default is 1.
[ ]: # Example 1
list_of_book = my_book_list[1:3]
print(list_of_book)
[ ]: #Example 2
list_of_book = my_book_list[1:-2]
print(list_of_book)
[ ]: # Example 3
my_book_list[:3] # return up to 3 data in list from frist data
[ ]: # Example 4
my_book_list[1:] #return book list from index 1 to last
[ ]: # Example 5 : Check if the item is present in the list or not using membership␣
↪operator
[ ]: True
[ ]: # Example 6
'Harry Potter' in my_book_list
[ ]: False
11
4.3 Replacing Values in a List
In Python, the value of a list element can be changed by assigning a new value to a specific index.
The new value replaces the old value at that index.
['The Alchemist', 'The Kite Runner', 'Harry Potter', 'The Witcher', 'Friends']
[ ]: 5
[ ]: # replacing the index 1 element and delete second one as it won't find index 2
my_book_list[1:3] = ["Scavenger Hunt"]
my_book_list
Key Explanation:
• Slicing allows you to specify a range of indices (start:stop).
• When assigning a new value to a slice, all elements within the range are replaced.
• If the new value contains fewer elements than the original slice, the extra elements in the slice
are removed from the list.
• This behavior explains why "The Hobbit" and "1984" were replaced by "Scavenger Hunt",
and the size of the list was adjusted.
12
4.4.1 Syntax:
“‘python list_name.insert(index, element)
[ ]: # Example
my_list = [1,2,3]
my_list.insert(1,5)
my_list
[ ]: [1, 5, 2, 3]
4.5 Append
The append() method in Python is used to add a single item to the end of a list. Unlike insert(),
it does not allow you to specify the position; the new element is always added to the list’s end.
4.5.1 Syntax:
“‘python list_name.append(element)
[ ]: [1, 5, 2, 3, 7]
4.6 Extend
The extend() method in Python adds all elements from an iterable (e.g., list, tuple, set) to the
end of the current list. It differs from append() because it does not add the iterable as a single
element but instead adds each element from the iterable individually.
4.6.1 Syntax:
“‘python list_name.extend(iterable)
It is adding the each element of item two individually i.e. t, w, o one by one.
13
4.7 Remove Items from List
There are several methods to remove items from a list in Python. Here’s a breakdown of each:
4.7.1 1. pop()
The pop() method removes and returns an item at a specified index. If no index is provided, it
removes and returns the last item.
[ ]: # Example of pop()
my_list = [1,2,3]
my_list.pop(1)
my_list
[ ]: [1, 3]
4.7.2 2. del()
The del statement is used to remove an item at a specified index or delete the entire list. Unlike
pop(), del does not return the removed item.
Syntax: “‘python del list_name[index] # Remove item at index del list_name # Delete the
entire list
['apple', 'cherry']
---------------------------------------------------------------------------
NameError Traceback (most recent call last)
Cell In[79], line 6
4 # Delete the entire list
5 del my_list
14
----> 6 my_list
4.7.3 3. clear()
The clear() method is used to remove all items from a list, leaving the list empty. It modifies the
original list in place and does not return any value.
15
4.7.6 Sort List
The sort() method is used to sort the elements of a list in ascending order by default. The list is
sorted in place, meaning the original list is modified, and no new list is returned.
4.7.7 Syntax:
list_name.sort()
Note: - By default, sort() function will sort the value in ascending order. - Also, if we use mix
alphabet, it will order the value according to ASCII value.
[ ]: my_list=[1,5,7,8]
my_list.sort()
my_list
[ ]: #as sort() function sort data in ascending order so, caps letter come first and␣
↪small letter
4.7.10 Syntax:
“‘python list_name.reverse()
16
4.7.11 Make a Copy of a List
To make a copy of a list in Python, you can use the copy() method. This creates a shallow copy
of the list, meaning that it creates a new list with the same elements, but the two lists are separate
and modifications to one won’t affect the other.
4.7.12 Syntax:
“‘python new_list = original_list.copy()
Syntax:
joined_list = list1 + list2
We can use extend() for to add the items from one list to another.
list1.extend(list2)
17
4.7.15 Python Conditions
Conditions in Python allow us to execute certain blocks of code based on specific conditions. The
primary way to implement conditions in Python is through if, elif, and else statements.
4.7.16 1. if statement
The if statement is used to check if a condition is true. If the condition is true, the code inside
the if block will execute.
[ ]: #example of if condition
x= 7
if x>5 :
print("x is greater than 5")
[ ]: #example of if condition
x= 7
if x>5 :
print("x is greater than 5")
When condition of if meet, then it return print if condition is false, it give nothing but code will
run.
To deal with this we use “else” i.e. else condition
4.7.18 Syntax:
“‘python if condition: # Execute this block if condition is True else: # Execute this block if
condition is False
[ ]: #example of if condition
x= 7
if x>9 :
print("x is greater")
else:
print("x is smaller")
18
in the elif blocks. If any elif condition evaluates to True, the corresponding block of code will
be executed.
4.7.20 Syntax:
“‘python if condition1: # Execute this block if condition1 is True elif condition2: # Execute this
block if condition2 is True else: # Execute this block if none of the conditions are True
Note: elif is used when you have several distinct conditions to check and you want to perform
different actions depending on which one is true.
4.7.22 Syntax:
“‘python value_if_true if condition else value_if_false
4.7.23 Nested if
In python programming, you can use if condition inside the condition which is known as Nested
Loop. You can put if condition inside another if, if_else condition using nested if.
19
4.7.24 Syntax:
if condition:
if condition:
#your code in here
else condition:
#your code in here
1: Write a program to check if a number is positive, negative, or zero. - If the number is positive,
print “Positive”. - If the number is negative, print “Negative”. - If the number is zero, print “Zero”.
Example Input: 0
Expected Output: Zero
1: Write a program that prints “Adult” if the age is greater than or equal to 18.
Example Input: 20
Expected Output: Adult
2: Write a program that prints “Eligible” if the age is greater than or equal to 18, otherwise prints
“Not Eligible”.
20
Example Input: 17
Expected Output: Not Eligible
1: Write a program to check if a number is positive, negative, or zero, and further check if it is
even or odd. - If the number is positive, print “Positive Even” or “Positive Odd”. - If the number
is negative, print “Negative Even” or “Negative Odd”. - If the number is zero, print “Zero”.
Example Input: -4
Expected Output: Negative Even
2: Write a program that checks if a person is eligible to vote. - If the person is 18 or older, check if
they are a citizen: - If they are a citizen, print “Eligible to vote”. - If they are not a citizen, print
“Not eligible to vote”. - If the person is younger than 18, print “Not eligible to vote”.
Example Input: 16, Citizen: True
Expected Output: Not eligible to vote
3: Write a program that checks if a number is within the range of 1 to 100. - If it is within the
range, check if it is divisible by 3: - If divisible by 3, print “Divisible by 3”. - Otherwise, print “Not
divisible by 3”. - If it is outside the range, print “Out of range”.
Example Input: 15
Expected Output: Divisible by 3
21
x+=1
[ ]: x = 0
while x < 10:
print(x)
x+=1
if x ==4:
break #once if condition meet, break statement break loop and exist the␣
↪loop
22
4.7.37 Syntax:
“‘python for variable in sequence: # Code to execute
[ ]: for i in range(6):
print(i)
[ ]: for i in range(1,10,2):
print(i)
Here last digit from range is the number of time loop break and continue after that number of
elements.
[ ]: colors = ['red','blue']
objects= ['chair', 'table', 'house']
for i in colors:
for j in objects:
print(i,j)
23
4.7.40 Exercise 1.8
4.7.41 Practice question For loop
1. Print Elements of a List: Given the list fruits = ["apple", "banana", "cherry"],
use a for loop to print each fruit.
2. Print Numbers in a Range: Use a for loop to print numbers from 1 to 5.
3. Sum of Numbers: Given the list numbers = [1, 2, 3], use a for loop to find the sum of
the numbers and print it.
4. Print Each Character of a String: Given the string "hello", use a for loop to print
each character.
24