Unit 4: Control Structures in Python — Long Questions
10th Class Computer Science · Unit 4: Unit 4: Control Structures in Python
★ Key Points: Decision Making Statements | if | if-else | Nested Conditions
Decision-Making Structure
Decision making in programming allows the program to choose different actions based on conditions. This is similar to how we make decisions in real life. For example, deciding whether to take an umbrella based on the weather conditions. Python provide variety of conditional statements to implement decision-making.
Types of Decision-making structure
In Python, decision-making structures refer to control flow constructs that allow a program to make decisions based on conditions. These structures determine the execution path of the code. There are the three main types of decision-making structures in Python:
1. if Statement
The if statement lets us make decisions based on conditions. If the condition is true, it runs a block of code. In Python indentation defines the structure block or scope of your code. In Python proper indentation is mandatory. Incorrect indentation may cause error in your code (Indentation Error).
Syntax of if statement
if condition:
code to run if the condition is true
Example
If the temperature is above 30 degrees (e.g. It is hot today), we print a message.
temperature=35
if temperature>30:
print("It's a hot day")
Output It's a hot day
2. if-else Statement
The if-else statement allows us to execute one block of code if a condition is true and another block if the condition is false.
Syntax of if-else statement
if condition:
code to run if the conditionis true
else:
code to run if the condition is false
Example
temperature=15
if temperature>30:
print("It's a hot day")
else:
print("It's not a hot day")
Output It's not a hot day
3. Nested Conditions
Sometimes, we need to check multiple conditions inside another condition. This is called nesting.
Syntax of nested if statement:
if condition 1:
if condition 2:
code to run if both condition 1 and condition 2 are true
else:
code to run if condition 1 is true but condition 2 is false
else:
code to run if condition 1 is false
Example
If the weather is rainy and the temperature is below 15 degrees, we wear a rain coat. If it is only rainy, we take an umbrella. If the weather is not rainy, we just enjoy the day.
weather = "rainy"
temperature = 10
if weather == "rainy":
if temperature < 15:
print("Wear a raincoat")
else:
print("Take an umbrella")
else:
print("Enjoy your day!")
Output Wear a raincoat
Explanation In this example, the code checks if the weather is rainy. If it is, it then checks if the temperature is below 15 degrees. If both conditions are true, it prints "Wear a raincoat" If the weather is rainy but the temperature is not below 15 degrees, it prints "Take an umbrella" If the weather is not rainy, it prints "Enjoy your day!"
★ Key Points: Looping Structure | while loop | for loop
A looping structure in programming allows a set of instructions to be executed repeatedly until a specific condition is met. It helps the programmer to reduce the process of write similar code again and again.
Types of Looping Structure
There are two main types of loops in Python:
1. while loop
2. for loop
1. while loop
A while loop runs as long as a condition is true. It checks the condition before each iteration and stops running when the condition is no longer true.
Syntax of while loop
while condition:
code to run while the condition is true
Example 1
Print numbers from 1 to 9.
number=1
while number<10:
print(number)
number +=1
Output
1
2
3
4
5
6
7
8
9
Explanation The program prints numbers from 1 to 9. It starts with number = 1 and repeatedly prints the value and adds 1 until number reaches 10, then the loop stops.
Example 2
Write a Python program that print even and count the odd numbers from 1 to 20 using a while loop.
num=1
oddcount=0
while num<=20:
if num%2==0:
print(f"Even: {num}")
else:
oddcount +=1
num +=1
print("Total odd numbers:",oddcount)
Output
Even:2
Even:4
Even:6
Even:8
Even:10
Even:12
Even:14
Even:16
Even:18
Even:20
Total odd numbers:10
2. for Loop
A for loop repeats a block of code a specific number of times. It is commonly used to iterate over a sequence (like a list, tuple, or string).
Syntax of for loop
for variable in sequence:
code to run for each element in the sequence
SMART TIPS
List: A list is an ordered collection of items that can be of different data types. It always enclosed in square bracket. e.g. list[0] = 10
Tuple: A tuple is an ordered, immutable collection of items similar to a list but with a fix size. It enclosed in parenthesis ( ). e.g. (1,2,3)
String: A string is a sequence of characters used to represent text data. Always enclosed in single or double quotes. e.g. string = "FaisalZia"
Example 1
Say "Hello" to each friend in a list of friends.
friends=["Arshad","Ayaan","Areeda"]
for friend in friends:
print("Hello",friend)
Output
Hello Arshad
Hello Ayaan
Hello Areeda
Explanation In this example, the code goes through each friend in the list and prints a greeting message for each one.
★ Key Point: Comparison between while & for loop
Feature | While Loop | For Loop
Definition | Executes a block of code repeatedly as long as a condition is true. | Executes a block of code for a specific number of times or over each element in a sequence.
Control | Controlled by a condition (Boolean expression). | Controlled by a sequence (like range, list, string, or tuple).
Use Case | Used when the number of iterations is not known in advance. | Used when the number of iterations is known or you are iterating over a sequence.
Syntax Example | i=0
while i<5:
print(i)
i+=1 | for i in range(1,5):
print(i)
Risk | Can result in infinite loops if the condition never becomes False. | Less risk of infinite loops; iterates over a fixed range or sequence.
Increment/Step | Must be manually updated inside the loop (i += 1). | Automatically handled by the sequence or range() function.
Common Uses | Repeating until a condition changes, like waiting for user input. | Iterating over lists, strings, or generating sequences of numbers.
★ Key Points: Use of range() function | Syntax of range() function
In Python, the range() function is used to generate a sequence of numbers. It is commonly used in for loops to repeat actions to the specific number of times.
Syntax of range() function
• range(stop)
• range(start, stop)
• range(start, stop, step)
Example
Print the numbers from 0 to 4 OR (Print First 5 whole numbers)
for i in range(5):
print(i)
Output
0
1
2
3
4
Explanation The above code uses range(5), which generates a sequence of numbers starting from 0 up to (but not including) 5. Each number is printed using the for loop.
★ Key Points: Use of end statement | Example of end statement
In Python, the end statement is not a separate command, but rather an optional parameter of the print() function. By default, every print() in Python ends with a newline character, but you can change what gets printed at the end using the end parameter.
Example 1
Print two Strings on same line using "end" statement.
print("Ayaan",end="****")
print("Shah")
Output Ayaan****Shah
Code
print("Arshad Mehmood",end="")
print("Shah")
Output Arshad Mehmood Shah
Example 2
Print Numbers from 1 to 5 on the same line using "end" statement.
for i in range(1,6):
print(i,end=" ")
Output
1 2 3 4 5
Note
Using end="" prints the numbers without spaces. If you use end=" " it would print:
1 2 3 4 5 with spaces between numbers.
★ Key Points: Use of nested loops | Examples of nested loops
Nested loops are loops inside another loop. For each iteration of the outer loop, the inner loop runs completely. We use nested loops when we need to perform repetitive tasks within tasks.
Example 1
Nested loops for basic Number Pattern.
print("===Basic Number Pattern===")
for i in range(3):
for j in range(4):
print(f"i={i},j={j}")
print("--------")
Output
===Basic Number Pattern===
i=0,j=0
i=0,j=1
i=0,j=2
i=0,j=3
--------
i=1,j=0
i=1,j=1
i=1,j=2
i=1,j=3
--------
i=2,j=0
i=2,j=1
i=2,j=2
i=2,j=3
--------
Explanation
• The outer loop (i) controls the rows.
• The inner loop (j) controls the columns/iterations inside each row.
• print("") adds a blank line between each set of i values for clarity.
Example 2
Nested loops to print stars (asterisk) in Triangular Pattern
print("===Right - Angled Triangle===")
n=5
for i in range(1,n+1):
for j in range(i):
print("*",end="")
print()
Output
===Right - Angled Triangle===
*
**
***
****
*****
Explanation
• Outer loop (i) controls the number of rows.
• Inner loop (j) prints the * symbols for each row.
• end="" keeps the stars on the same line.
• print() moves to a new line after finishing each row.
★ Key Points: Use of Python Libraries | Examples of Python Libraries
Python libraries enhance programming efficiency by providing built in functions and modules that help perform tasks quickly. Python offers an extensive standard library that includes built-in modules and data structures.
Importing and Using Libraries
In Python, libraries are like toolboxes full of useful tools that help you solve different problems without having to build everything from scratch. Libraries are like pre-built tools that you can use without having to write all the code yourself. Let's explore how to import and use different libraries with some simple examples.
Example
Import the random library to generate random numbers.
import random
number=random.randint(1,10)
print("The random number is:",number)
Output The random number is:3
Explanation The random library helps you generate random numbers, which can be useful in games, simulations, or even to pick a winner in a lucky draw.
Example
Import the statistics library to perform statistical calculations.
import statistics
data=[23,45,67,89,12,44,56]
meanvalue=statistics.mean(data)
print("The mean value is:",meanvalue)
Output The mean value is:48.0
Explanation The statistics library is a great tool for performing basic statistical calculations, such as finding the mean, median, and mode of a set of data. This can be particularly useful in data analysis tasks. By using these libraries, you can save time and effort, allowing you to focus on solving the specific problem at hand rather than reinventing the wheel.
★ Key Points: Python Lists | Creation | Accessing | Modification
Lists In Python, a list is a versatile data structure that can hold a collection of items. You can create, access, and modify lists easily.
1. Creating List
A list is created by placing items inside square brackets [ ], separated by commas. Lists can contain items of different types, such as numbers, strings, or even other lists.
Example
Create a list of your favorite fruits.
fruits=["Mango","Apple","Banana"]
print(fruits)
Output ['Mango','Apple','Banana']
Explanation This code creates a list named fruits , containing three elements and then prints the list.
2. Accessing List Items
You can access items in a list by referring to their index, starting from 0.
Example
Access and print the second item from the list of fruits.
fruits=["Mango","Apple","Banana"]
print(fruits[1])
Output Apple
Explanation The code initializes a list 'fruit' containing 'Mango', 'Apple', and 'Banana', then prints the second item, 'Apple', using the index ' 1 '.
3. Modifying a List
You can modify list items by accessing them via their index and assigning a new value.
Example
Change the first item in the list to "Orange" and add a new fruit "Pineapple".
fruits=["Mango","Apple","Banana"]
fruits[0]="Orange"
fruits.append("Pineapple")
print(fruits)
Output ['Orange','Apple','Banana','Pineapple']
Explanation The code modifies the first element of the fruits list to 'Orange', appends Pineapple at the end, and prints the updated list.
★ Key Points: Operations on Lists | append() | remove() | sort() | reverse() | Examples
Operations on Lists
Python provides several built-in methods to work with lists:
1. append(item): Adds an item to the end of.the list.
Example: mylist.append(5) adds 5 to the end of the list.
2. remove(item): Deletes the first time that item appears in the list.
Example: mylist.remove(3) removes the first 3 it finds.
3. sort(): Arranges the list in order, from smallest to biggest or ascending order.
Example: mylist.sort() sorts numbers like 1, 2, 3, etc.
4. reverse(): Flips the list so the last item comes first.
Example: mylist.reverse() turns [1, 2, 3] into [3, 2, 1].
Example 1
Add a new student to the list and print it
students=["Ahmed","Sara","Ali"]
students.append("Hina")#Add"Hina"to the list
students.sort()#Sort the list alphabetically
print(students)
Output ['Ahmed','Ali','Hina','Sara']
Explanation
• A list students is created.
• .append("Hina") adds the new student to the end of the list.
• .sort() arranges the names alphabetically.
Example 2
Remove a student from the list and print it
students=["Ahmed","Sara","Ali","Hina","Sara"]
students.remove("Sara")#Removes the first occurrence of "Sara"
print(students)
Output ['Ahmed','Ali','Hina','Sara']
Explanation
• .remove("Sara") deletes the first occurrence of "Sara" in the list.
• The remaining elements stay in their order.
Example 3
Sort a list of numbers in ascending order
numbers=[34,12,89,5,23]
numbers.sort()#Sort numbers in ascending order
print(numbers)
Output [5,12,23,34,89]
Explanation • .sort() arranges the numbers from smallest to largest.
Example 4
Reverse the order of fruits in a list
fruits=["Apple","Banana","Orange","Mango"]
fruits.reverse()#Reverse the order of elements in the list
print(fruits)
Output ['Mango','Orange','Banana','Apple']
Explanation
• The list fruits are created with four elements.
• The reverse() method reverses the order of the list in place.
• print(fruits) displays the reversed list
★ Key Points: Use of Testing | Types of Testing | Use of Debugging | Types of Debugging
In Python programming, testing and debugging are essential practices to ensure that your code works correctly and efficiently.
1. Testing
Testing is the process of running your code with various inputs to check if it behaves as expected. The goal is to find and fix any issues before the code is used in real-world applications.
a. Types of Testing
i. Unit Testing: Tests individual parts of the code (like functions or classes) in isolation. Python's unittest module is commonly used for this.
ii. Integration Testing: Checks how different parts of the code work together.
iii. Functional Testing: Validates that the software behaves as expected from the user's perspective.
iv. Regression Testing: Ensures that new changes don't break existing functionality.
b. Importance
• Helps identify and fix issues before the code is used in real-world applications.
• Ensures that the software functions reliably and as intended.
2. Debugging
Debugging is the process of finding and fixing errors (bugs) in your code. It involves identifying the root cause of problems and making the necessary changes.
a. Common Debugging Techniques
i. Print Statements: Adding print statements to check the values of variables at different stages of the code.
ii. Debugging Tools: Using tools like pdb (Python Debugger) to step through the code, inspect variables, and understand the flow of execution.
iii. Error Messages: Reading and interpreting error messages to locate the source of the problem.
b. Importance
• Helps to identify the root cause of problems.
• Ensures that the program runs correctly and avoids unexpected crashes.