Unit 4: Control Structures in Python — Short Questions
10th Class Computer Science · Unit 4: Unit 4: Control Structures in Python
Decision Making
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. Python provides a variety of conditional statements to implement decision-making.
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.
The main types of decision-making structures in Python are given below:
1 if Statement
2. if-else Statement
3. Nested Conditions
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. Proper indentation is mandatory. Incorrect indentation may cause an error (Indentation Error).
Syntax
if condition:
code to run if the condition is true
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. It is also known as two-way decision-making structure.
Syntax
if condition:
code to run if the condition is true
else:
code to run if the condition is false
Nested conditions occur when one condition is placed inside another condition. They are used when you need to check multiple related conditions, allowing more precise control over the program's flow.
Looping Constructs
A looping structure in programming allows a set of instructions to be executed repeatedly until a specific condition is met. It helps reduce code repetition and is commonly used when performing repetitive tasks.
There are two types of loops, which are given below:
- while loop
- for 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.
while repeats as long as a condition is true (e.g., counting to 10), while 'for' iterates over a sequence (e.g., list items).
A for loop repeats a block of code for a specific number of times. It is commonly used to iterate over a sequence (like a list, tuple, or string).
In Python, the range() function is used to generate a sequence of numbers. It is commonly used in for loops to repeat actions for a specific number of times.
Syntax:
- range(stop)
- range(start, stop)
- range(start, stop, step)
Short Questions
In Python, the end statement is not a separate command, but rather an optional parameter of the print() function. By default, every print() ends with a newline character, but you can change what gets printed at the end using the end parameter.
Strings in Python are surrounded by either single quote ' ' or double quotes " " Both are treated the same. Example:
name1='Arshad'
name2="Faisal"
print(name1) # Output: Arshad
print(name2) # Output: Faisal
Nested loops are loops inside other loops. 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.
Libraries in Python
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 toolkits that you can use without having to write all the code yourself.
Example: Random library
import random
number=random.randint(1,10)
print("The random number is:", number)
When importing libraries in Python, you should only import what you need to avoid unnecessary memory usage and keep your code efficient. You can explore more Python libraries and their documentation at: https://docs.python.org/3/
Lists in Python
In Python, a list is a versatile data structure that can hold a collection of items. You can create, access, and modify lists easily.
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
fruits = ["Mango", "Apple", "Banana"]
print(fruits)
Output: ['Mango', 'Apple', 'Banana']
You can access items in a list by referring to their index, starting from 0.
Example
fruits = ["Mango", "Apple", "Banana"]
print(fruits[1])
You can modify list items by accessing them via their index and assigning a new value.
Example
fruits=["Mango","Apple","Banana"]
fruits[0]="Orange"
fruits.append("Pineapple")
print(fruits)
Output: ['Orange', 'Apple', 'Banana','Pineapple']
Methods and Operations on Lists
- append(item): Adds an item to the end of the list.
- remove(item): Deletes the first time that item appears in the list.
- sort(): Arranges the list in order, from smallest to biggest or ascending order.
- reverse(): Flips the list so the last item comes first.
students = ["Ahmed", "Sara", "Ali"]
students.append("Hina")
students.sort()
print(students)
Output: ['Ahmed','Ali','Hina', 'Sara']
students = ["Ahmed", "Sara", "Ali","Hina","Sara"]
students.remove("Sara")
print(students)
numbers=[34,12,89,5,23]
numbers.sort()
print(numbers)
Output: [5,12,23,34,89]
fruits = ["Apple", "Banana", "Orange", "Mango"]
fruits.reverse()
print(fruits)
Output: ['Mango', 'Orange', 'Banana', 'Apple']
Testing and Debugging in Python
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.
- Unit Testing: Tests individual parts of the code (like functions or classes) in isolation. Python's unittest module is commonly used.
- Integration Testing: Checks how different parts of the code work together.
- Functional Testing: Validates that the software behaves as expected from the user's perspective.
- Regression Testing: Ensures that new changes don't break existing functionality.
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.
- Print Statements: Adding print statements to check the values of variables at different stages of the code.
- Debugging Tools: Using tools like pdb (Python Debugger) to step through the code, inspect variables, and understand the flow of execution.
- Error Messages: Reading and interpreting error messages to locate the source of the problem.
Predict the Output
x=7
if x%2==0:
print("Even")
Output Even
x=3
if x>5:
print("Yes")
else:
print("No")
Output No
x=10
if x%2==0:
print("Even")
Output Even
x=9
if x%2==0:
print("Even")
else:
print("Odd")
Output Odd
x=4
y=6
if x<y:
print("X")
Output X
x=8
y=3
if x<y:
print("X")
else:
print("Y")
Output Y
x=5
if x>2:
if x<10:
print("In Range")
Output In Range
x=6
if x>5:
if x%2==0:
print("Even Big")
Output Even Big
x=7
if x>5:
if x%2==0:
print("Even Big")
else:
print("Odd Big")
Output Odd Big
x=3
if x>5:
print("A")
else:
if x>1:
print("B")
Output B
x=0
if x>=1:
print("True")
else:
print("False")
Output False
x=1
if x==1:
print("True")
Output True
x=-1
if x>0:
print("Positive")
else:
print("Not Positive")
Output Not Positive
x=5
if x==-5:
print("Equal")
Output Equal
x=4
if x!=5:
print("Not Equal")
Output Not Equal
x=10
if x>5:
if x>8:
print("High")
else:
print("Medium")
Output High
x=6
if x>5:
if x>8:
print("High")
else:
print("Medium")
Output Medium
Find the Errors
x=5
if x>3
print("A")
Syntax Error: Missing colon: after if
Fix:
x=5
if x>3:
print("A")
x=2:
if x>3:
print("A")
Indentation Error: print not indented
Fix:
x=2
if x>3:
print("A")
x=7
if x>5
print("Yes")
else:
print("No")
Syntax Error & Indentation Error: missing colon and wrong indentation
Fix:
x=7
if x>5:
print("Yes")
else:
print("No")
x=10
if x%2=0:
print("Even")
Syntax Error: used `=` instead of `==`
Fix:
x=10
if x%2==0:
print("Even")
x=4
if x<5
print("Less")
else
print("More")
Syntax Error: missing colons after if and else
Fix:
x=4
if x<5:
print("Less")
else:
print("More")
x=5
if x>2:
if x<10:
print("In Range")
Syntax Error: missing colon after inner if
Fix:
x=5
if x>2:
if x<10:
print("In Range")
x=7
if x>5
if x%2==0:
print("Even Big")
else:
print("Odd Big")
Syntax Error: missing colon after outer if
Fix:
x=7
if x>5:
if x%2==0:
print("Even Big")
else:
print("Odd Big")
x=0
if x
print("True")
else:
print("False")
Syntax Error: Missing colons after 'if'
Fix:
x=0
if x==0:
print("True")
else:
print("False")
x=-1
if x>0:
print("Positive")
else
print("Not Positive")
Syntax Error: missing colon after 'else'
Fix:
x=-1
if x>0:
print("Positive")
else:
print("Not Positive")
x=5
if x==5
print("Equal")
Syntax Error: missing colon and indentation error
Fix:
x=5
if x==5:
print("Equal")