0% found this document useful (0 votes)
2 views

Copy of Day 1 Python

The document provides an introduction to Python, covering its key features, basic syntax, and data types including text, numeric, sequence, mapping, set, and boolean. It also discusses type casting, operators (arithmetic, comparison, logical), and the characteristics of lists, including indexing and slicing. Exercises and practice problems are included to reinforce learning concepts.

Uploaded by

emmanuelss236
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
2 views

Copy of Day 1 Python

The document provides an introduction to Python, covering its key features, basic syntax, and data types including text, numeric, sequence, mapping, set, and boolean. It also discusses type casting, operators (arithmetic, comparison, logical), and the characteristics of lists, including indexing and slicing. Exercises and practice problems are included to reinforce learning concepts.

Uploaded by

emmanuelss236
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 24

Copy of Day_1_Python

May 17, 2025

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.2 Basic Syntax


• Variables: No need for explicit type declaration. “‘python x = 5 # Integer y = 3.14 # Float
name = “John” # String is_active = True # Boolean

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

[2]: # My first python print


"""Python is easy to write
its like typing english,
lets see our firt ptint"""
print("Hello World!")

Hello World!

[3]: #example of variable


x= 2
y = "Hello World"

[7]: w = y*4
print(w)

Hello WorldHello WorldHello WorldHello World

1
[4]: print(x)
print(type(x))

2
<class 'int'>

[9]: income = float(input("Enter your monthly income: "))


z = income * 10
print("My take away fund every month is ",z)
print(type(income))

Enter your monthly income: 27.5


My take away fund every month is 275.0
<class 'float'>

[ ]: print(y)

Hello World

1.3.1 Exercise 1.1


1. Write a code to print your name inside the print function.
[10]: # Write a code to print your name in 'print' function
print("Chijioke Henry")

Chijioke Henry

2. Write a code to print the following code:


[ ]: # Write a code to assign your name in variable and print it.
# ---Your code in here---

2 Python Data Types


2.1 1. Text
• Type: str
• Example: "anusha" (inside quotes)

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

[11]: # different data types


name = "Anusha" # str data type
age = 23 #int
height = 5.3 # float
book = ["Game of Thrones", " The Alchemist"] #list
countries = ("Nepal", "India", "Bangladesh") #tuple
x= range(5) #range
my_info = {name: "John", age: "23"}
is_okay = True
print (my_info)
print(book)

{'Anusha': 'John', 23: '23'}


['Game of Thrones', ' The Alchemist']

[13]: countries = ("Nepal", "India", "Bangladesh")


countries.append("Nigeria")

---------------------------------------------------------------------------
AttributeError Traceback (most recent call last)
Cell In[13], line 2
1 countries = ("Nepal", "India", "Bangladesh")

3
----> 2 countries.append("Nigeria")

AttributeError: 'tuple' object has no attribute 'append'

[14]: print(countries[0])

Nepal

[ ]:

[12]: book = ["Game of Thrones", " The Alchemist"]


book.append("Things fall apart")
book

[12]: ['Game of Thrones', ' The Alchemist', 'Things fall apart']

[ ]: 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---

[ ]: #write code below to convert above int variable to float


# ---Your code in here---

[ ]: # write code below to convert the int variable to str


# ---Your code in here---

3.1.2 Python operator


Definition: Operators are special symbols or keywords in Python that perform operations on
values and variables.

3.2 Types of Operators


3.2.1 1. Arithmetic Operators
Used for mathematical operations. | Operator | Description | Example |
|———-|——————|—————|
| + | Addition | 5 + 3 -> 8 |
| - | Subtraction | 5 - 3 -> 2 |
| * | Multiplication | 5 * 3 -> 15 |
| / | Division | 5 / 3 -> 1.6667 |
| // | Floor Division | 5 // 3 -> 1 |
| % | Modulus | 5 % 3 -> 2 |
| ** | Exponentiation | 2 ** 3 -> 8 |

[5]: """ Creating a simple app that tells the amount of


tax they should pay when earning certain amount of
money"""
income = float(input("Please Enter your monthly income here: "))
tax_rate = income * 0.05
print("Your tax payment is: ",tax_rate)

Please Enter your monthly income here: 78000.56


Your tax payment is: 3900.0280000000002

[ ]: # Example code: performing operation in 'print' function


print(1+3)

[ ]: # Example code: assigning variable and printing output.


a = 5
b = 6
c = a + b
print(c)

5
11

3.2.2 2. Comparison Operators


Used to compare two values. | Operator | Description | Example | |———-|——————–|———
———| | == | Equal to | 5 == 3 -> False | | != | Not equal to | 5 != 3 -> True | | > | Greater
than | 5 > 3 -> True | | < | Less than | 5 < 3 -> False | | >= | Greater than or equal to | 5 >= 3
-> True | | <= | Less than or equal to | 5 <= 3 -> False |
Note: The output of comparision operator always have boolean output.

[ ]: # Example:

3.2.3 3. Logical Operators


Used to combine conditional statements. | Operator | Description | Example | |———-|————
———|—————————–| | and | Returns True if both conditions are True | (5 > 3) and (2
< 4) -> True | | or | Returns True if one of the conditions is True | (5 > 3) or (2 > 4) -> True
| | not | Reverses the result | not(5 > 3) -> False |

3.2.4 Logical Operators and Truth Table

Operator Description Example Result


not Reverses the truth value not True False
not False True
and True if both conditions are true True and True True
True and False False
False and False False
or True if at least one condition is True or False True
true
False or False False

3.2.5 Truth Table for Logical Operators


1. not

Input Output
True False
False True

2. and

Input 1 Input 2 Output


True True True
True False False

6
Input 1 Input 2 Output
False True False
False False False

Note: The output of comparision operator always have boolean output.

[6]: #assigning variable


a=2
b=3

[8]: a>=2 and b>2

[8]: True

[9]: a>2 or b>2

[9]: True

[10]: not a>2

[10]: True

3.2.6 Precedence of Logical Operators


Logical operators in Python are evaluated based on their precedence. Here is the order of precedence
with definitions and examples:

1. not (Highest Precedence)


• The not operator negates a condition, reversing its truth value.
• Example:
“‘python result = not True # Output: False result = not (5 > 3) # Output: False

[11]: # Example of the precedence of the condition. Same can be applied for normal␣
↪calculation as well.

False or False and True and not True

[11]: False

[ ]: # another combine example with the values in it


result = True and False
print(result)
result = (5 > 3) and (8 > 6)or (7 < 6) and not (5 > 6)
print(result)

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

3.2.8 Membership operator


Operator that shows association. ‘in’

[14]: "a" in "The nAme of the person"

[14]: False

3.3 Exercise 1.3


1. Perform the following operations and note the results:
• Add 10 and 5.
• Subtract 15 from 25.
• Find the modulus of 7 divided by 3.
• Check if 10 is greater than or equal to 8.
• Use and to combine two conditions: (10 > 5) and (8 < 12).

[ ]: # ---Your Code in here---

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.

[ ]: #Your code in here

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.

Syntax: “‘python list_name = [element1, element2, element3, …]

[ ]: # Example code for the list


my_book_list = ["The Alchemist", "The Kite Runner", "Eleven Minute", "Games of␣
↪throne"]

print(my_book_list)

['The Alchemist', 'The Kite Runner', 'Eleven Minute', 'Games of throne']

[ ]: #print the date types of the list


print(type(my_book_list))

<class 'list'>

[ ]: # check the number of items in the list


len(my_book_list)

[ ]: 4

4.0.2 Exercise 1.4


4.0.3 Practice question for list
1. Create a list.
2. Print the items in the list.
3. Check the data types of items in the list.
4. Check the length of the list.

[ ]: # Your code in here

4.1 Accessing List Elements


In Python, list elements can be accessed using positive indexing and negative indexing:

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.

[ ]: #concept for indexing


my_book_list = ["The Alchemist", "The Kite Runner", "Eleven Minute", "Games of␣
↪throne"]

print(my_book_list)

['The Alchemist', 'The Kite Runner', 'Eleven Minute', 'Games of throne']

[ ]: # Positive indexing
print(my_book_list[1])

The Kite Runner

[ ]: #negative indexing
print(my_book_list[-3])

The Kite Runner

4.1.2 Exercise 1.5


4.1.3 Practice Questions: Accessing List Elements
1. Accessing by Positive Indexing
Given the list fruits = ["apple", "banana", "cherry", "date", "elderberry"], ac-
cess and print:
• The third item in the list.
• The first item in the list.
2. Accessing by Negative Indexing
Given the list numbers = [10, 20, 30, 40, 50], access and print:
• The second-to-last item.
• The last item in the list.
3. List Slicing
Given the list colors = ["red", "green", "blue", "yellow", "purple", "orange"],
slice and print:
• All colors from index 1 to 3.
• Every third color from the list (use step in slicing).
Note: You can copy the list from here and paste it in your code cells.

[ ]: # Your code in here

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)

['The Kite Runner', 'Eleven Minute']

[ ]: #Example 2
list_of_book = my_book_list[1:-2]
print(list_of_book)

['The Kite Runner']

[ ]: # Example 3
my_book_list[:3] # return up to 3 data in list from frist data

[ ]: ['The Alchemist', 'The Kite Runner', 'Eleven Minute']

[ ]: # Example 4
my_book_list[1:] #return book list from index 1 to last

[ ]: ['The Kite Runner', 'Eleven Minute', 'Games of throne']

[ ]: # Example 5 : Check if the item is present in the list or not using membership␣
↪operator

'The Kite Runner' in my_book_list

[ ]: 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.

[ ]: # Replacing 3rd element with new one


my_book_list[2] = 'Harry Potter'
print(my_book_list)

['The Alchemist', 'The Kite Runner', 'Harry Potter', 'Games of throne']

[ ]: # Replace the list items for range of items


my_book_list[3:4] = ["The Witcher", "Friends"]
print(my_book_list)
len(my_book_list)

['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

[ ]: ['The Alchemist', 'Scavenger Hunt', 'The Witcher', 'Friends']

4.3.1 Note on Replacing and Deleting Elements in a List


In the example above, the element, we can see that two item is replaced by the new item. "Harry
Potter" is not removed from the list instead, the second (index 1) and third (index 2) elements
are replaced because we assigned a new value to the slice my_book_list[1:3].

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.

4.4 Insert Item in a List


In Python, you can insert an item at a desired position in a list using the insert() method. This
method adds a new element at the specified index without removing any existing elements, shifting
the rest of the list to the right.

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)

[ ]: # Example adding 7 in the list


my_list.append(7)
my_list

[ ]: [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)

[ ]: # Expanding element in my_list


my_list = ["one","two","three"]
my_list.extend("two")
my_list

[ ]: ['one', 'two', 'three', 't', 'w', 'o']

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.

Syntax: “‘python list_name.pop(index)

[ ]: # 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

[ ]: # Example for the del() in certain index


my_list = ["apple", "banana", "cherry"]

# Remove the item at index 1


del my_list[1]
print(my_list)

['apple', 'cherry']

[ ]: # Example of deleting entire list using del()


my_list = ["apple", "banana", "cherry"]

# Delete the entire list


del my_list
my_list # it will give error as we deleted 'my_list'

---------------------------------------------------------------------------
NameError Traceback (most recent call last)
Cell In[79], line 6
4 # Delete the entire list
5 del my_list

14
----> 6 my_list

NameError: name 'my_list' is not defined

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.

Syntax: “‘python list_name.clear()

[ ]: # Example of clearing the items in the list


my_list = ["apple", "banana", "cherry"]

# Clear the entire list


my_list.clear()
my_list

4.7.4 Example 1.5


4.7.5 Simple Practice Questions: List Modifications
1. Replacing Items
Given the list fruits = ["apple", "banana", "cherry"], replace:
• The second item with "orange".
2. Removing Items
Given the list numbers = [5, 10, 15, 20], remove:
• The item 15 using the remove() method.
3. Appending Items
Given the list colors = ["red", "blue"], append:
• "green" to the list.
4. Using pop() to Remove Item
Given the list animals = ["cat", "dog", "rabbit"], remove:
• The last item using the pop() method.
5. Using del() to Remove Item
Given the list fruits = ["apple", "banana", "cherry"], use:
• The del statement to remove the item at index 1.
6. Inserting Items
Given the list colors = ["red", "blue"], insert:
• "green" at index 1.
7. Clearing the List
Given the list numbers = [1, 2, 3], clear the list using the clear() method.
Note: You can copy the list from the question.

[ ]: # Your code in here

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.

[ ]: # Example for sorting the value.


my_list=['a', 'i', 'c', 'z','h']
my_list.sort()
my_list

[ ]: 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

my_list=['a', 'i', 'A', 'z','B']


my_list.sort()
my_list

4.7.8 Descending order


To sort a list in descending order in Python, you can use the sort() method with the reverse=True
parameter. This will arrange the elements in descending order (from largest to smallest).

4.7.9 Using reverse() to Reverse a List


The reverse() method is used to reverse the order of elements in a list. Unlike sort(), it does
not sort the elements but simply reverses their positions.

4.7.10 Syntax:
“‘python list_name.reverse()

[ ]: # Reverse the list in the descending order.


my_list=['a', 'i', 'A', 'z','B']
my_list.sort(reverse= True)
my_list

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()

[ ]: # Example for the copy list.


my_list= [1,2,3]
copy_list = my_list.copy()
copy_list

4.7.13 Join Lists


To join or concatenate two or more lists in Python, you can use the + operator or the extend()
method. This will combine the lists into a single list.

4.7.14 Method 1: Using the + Operator


You can use the + operator to join multiple lists into one. It combines the lists without modifying
the original ones.

Syntax:
joined_list = list1 + list2
We can use extend() for to add the items from one list to another.
list1.extend(list2)

[ ]: # Example using `+`


list1 = [1,2]
list2 = ["a","b"]
list3 = list1+list2+list1
list3

[ ]: # Example using `extent()`


list1 = [1,2]
list2 = ["a","b"]
list1.extend(list2)
list1

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.

Syntax: “‘python if condition: # Execute this block if condition is True

[ ]: #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.17 2. else Statement in Python


The else statement in Python is used to execute a block of code when the condition in the if
statement is False. The else block runs if none of the previous if or elif conditions evaluate to
True.

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")

4.7.19 3. elif Statement in Python


The elif (short for “else if”) statement allows us to check multiple conditions in a chain, after an
initial if statement. If the if condition evaluates to False, Python will then check the conditions

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

[ ]: #Example of elif conditition


# x = int(input()) # take input from user
age = 18
if age < 18:
print("You are a minor.")
elif age == 18:
print("You just became an adult.")
else:
print("You are an adult.")

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.21 Short Hand if Statement in Python


The short hand if statement, also known as a ternary operator, allows you to write simple
if-else conditions in a more concise form. It is particularly useful when you want to assign a
value based on a condition.

4.7.22 Syntax:
“‘python value_if_true if condition else value_if_false

[ ]: # Example for the short had `if` case


x=3
if x>1: print("X is greater")

[ ]: # Example for the short hand `if_else`


x=3
print("X is greater") if x>4 else print('x is smaller')

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

[ ]: # Example for the nested if


x = 35
if x>10:
print("x is greater than 10")
if x < 30:
print("but it is less than 30")
else:
print("and it is greater than 30 as well")

4.7.25 Exercise 1.6


4.7.26 Practice question related to the codition in here.
4.7.27 1. Condition Practice Questions

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

2: Write a program to check if a number is divisible by 5. - If the number is divisible by 5, print


“Divisible by 5”. - Otherwise, print “Not divisible by 5”.
Example Input: 10
Expected Output: Divisible by 5

4.7.28 2. Short-hand if Practice Questions

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

4.7.29 3. Nested Condition Practice Questions

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

[ ]: # Your code in here

4.7.30 Python Loop


A loop is used when we need to run a block of code multiple times until a condition becomes true.
There are two types of loops in Python:
• while loop
• for loop

4.7.31 1. while loop


In a while loop, the loop run as long as contition become true.

[ ]: # Example code of while loop


x= 0
while x<5:
print(x)

21
x+=1

4.7.32 break statement


The break statement is used to terminate the loop prematurely. It stops the execution of the loop
and exits out of it, regardless of whether the loop’s condition is still true.

[ ]: 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

4.7.33 continue statement


The continue statement is used to skip the current iteration of the loop and proceed to the next
iteration.

[ ]: # Example for the continue statement


x = 0
while x < 10:
x+=1
if x ==4:
continue
print(x)

4.7.34 Exercise 1.7


4.7.35 Practice question While loop
1. Print Numbers from 1 to 5: Write a while loop to print numbers from 1 to 5.
2. Sum of Numbers in a List: Given the list numbers = [1, 2, 3, 4, 5], use a while loop
to find the sum of the numbers and print it.
3. Use break to Exit the Loop: Write a while loop that prints numbers from 1 to 10, but
stops if the number is 6. Use the break statement to exit the loop.
4. Use continue to Skip Even Numbers: Write a while loop that prints numbers from 1
to 10, but skips even numbers using the continue statement.

[ ]: # Your code in here.

4.7.36 2. for loop


The for loop is one of the most commonly used loops in Python. It allows you to iterate over a
sequence of elements like a list, tuple, set, dictionary, or string, and execute a block of code for
each item in the sequence.

22
4.7.37 Syntax:
“‘python for variable in sequence: # Code to execute

[ ]: #iterate over a list


my_list = ["one","two","three"]
for num in my_list:
print(num)

[ ]: #iterate over a string


for i in "anusha":
print(i)

We can use break and while statement in for loop as well.

4.7.38 The range() function


The range() function returns a sequence of number starting with 0(by default) and increment by 1
(by default) up to the number less than one of number provided

[ ]: for i in range(6):
print(i)

[ ]: for i in range(2, 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.

4.7.39 Nested loop


We can put loop inside loop.

[ ]: colors = ['red','blue']
objects= ['chair', 'table', 'house']
for i in colors:
for j in objects:
print(i,j)

[ ]: #to print table of 1 to 5


for i in range(1,6):
print("Table of", i)
for j in range(1,11):
print(i,"*",j, "=",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.

[ ]: # Your code in here.

24

You might also like