Python Revision Tour-I

Python Revision Tour-I

Type Casting:

Type casting in Python means converting a variable from one data type to another. Type casting is the process of changing the data type of a value using built-in functions. It is also known as type conversion.

Since Python is a dynamically typed language, it usually handles types automatically, but there are many situations—like taking user input or performing specific math operations—where you need to manually intervene to ensure your data is in the correct format.

There are two ways of doing this:

1. Implicit Type Conversion

This happens automatically when Python converts one data type to another without any user involvement. Python does this to avoid data loss.

  • Example: Adding an integer to a float.

x = 10 # Integer
y = 5.5 # Float
z = x + y # z becomes 15.5 (Float)

2. Explicit Type Conversion (Type Casting)

This is where you manually convert the data type using built-in functions. This is the most common use of the term “type casting.”

Common Casting Functions:

FunctionDescriptionExample
int()Converts to an integer. It truncates floats (removes decimals).int(3.9) # 3
float()Converts to a floating-point number.float(5) # 5.0
str()Converts an object into a string representation.str(100) # "100"
list()Converts a sequence (like a tuple or string) into a list.list("Hi") # ['H', 'i']

Math Library Module:

Python’s math module is a built-in library that provides access to mathematical functions. To use these, you must first include import math at the top of your script.

math.ceil(): Always rounds up to the nearest whole integer.

  • Example: math.ceil(4.1) returns 5.

math.floor(): Always rounds down to the nearest whole integer.

  • Example: math.floor(4.9) returns 4.

math.fabs(): Removes the negative sign.

  • Example: math.fabs(-10.5) returns 10.5.

math.sqrt(16) # Output: 4.0 (square root)
math.pow(2, 3) # Output: 8.0 (2^3)
math.ceil(4.3) # Output: 5 (round up)
math.floor(4.7) # Output: 4 (round down)

math.pi # 3.141592…
math.e # 2.71828…

math.sin(0) # Output: 0.0
math.cos(0) # Output: 1.0
math.tan(0) # Output: 0.0

Statement Flow Control in Python:

Statement flow control refers to the order in which statements (instructions) are executed in a Python program.

By default, Python executes code line by line (top to bottom), but flow control statements allow us to change this order based on conditions or repetition.

It is controlled using selection statements (if), iteration statements (for, while), and jump statements (break, continue, pass).


🔹 Types of Flow Control Statements

1. Sequential Control

  • Default execution (step-by-step).
a = 5
b = 10
print(a + b)

2. Selection Control (Decision Making)

  • Executes code based on conditions.

Types:

  • if
  • if-else
  • if-elif-else

Example:

marks = 75

if marks >= 90:
    print("A grade")
elif marks >= 60:
    print("B grade")
else:
    print("C grade")

3. Iteration Control (Loops)

  • In Python, loops are used to repeat a block of code multiple times. There are two main types:

Types:

  • for loop
  • while loop

🔁 1. for loop

Used when you know how many times you want to loop or when iterating over a sequence (like a list, string, or range).

Example:

for i in range(5):
    print(i)

Output:

0
1
2
3
4

Looping through a list:

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

for fruit in fruits:
    print(fruit)

🔄 2. while loop

Repeats as long as a condition is True. A while loop repeats a block of code as long as a specified condition remains True. It is used when you don’t know exactly how many times you need to loop beforehand.

Example:

count = 0

while count < 5:
    print(count)
    count += 1

⏹️ Loop control statements

break → stops the loop completely

for i in range(5):
    if i == 3:
        break
    print(i)

continue → skips current iteration

for i in range(5):
    if i == 3:
        continue
    print(i)

pass → does nothing (placeholder)

for i in range(5):
    pass

🔁 Nested loops (loop inside another loop)

A nested loop is a loop inside another loop. The “inner” loop completes all its iterations for every single iteration of the “outer” loop.

for i in range(2):
    for j in range(3):
        print(i, j)

💡 Note:

  • Use for loops for sequences.
  • Use while loops when the number of iterations depends on a condition.


1. Nested if Statement

A nested if is simply an if statement placed inside another if statement. This is used when you need to check multiple conditions that depend on one another.

  • Example: Checking if a number is positive, and then if it is even.
num = 10
if num >= 0:
    if num % 2 == 0:
        print("Positive and Even")
    else:
        print("Positive and Odd")

2. range() Function

The range() function generates a sequence of numbers. It is commonly used for looping a specific number of times. It takes three parameters: start, stop (exclusive), and step.

  • Syntax: range(start, stop, step)
  • Example:

range(7) # 0 to 6
range(5, 12) # 5 to 11
range(10, 4) # no value
range(10, 4, -1) # 10 to 5

# Generates 0, 1, 2, 3, 4
for i in range(5):
    print(i)

# Generates 2, 4, 6, 8
for i in range(2, 10, 2):
    print(i)

3. break vs continue

These “loop control” statements change how a loop behaves mid-execution.

  • break: Terminates the loop entirely and moves to the next block of code outside the loop.
  • continue: Skips the rest of the code inside the current iteration and jumps back to the top of the loop for the next cycle.
  • Example:
for i in range(1, 6):
    if i == 3:
        continue # Skips printing 3
    if i == 5:
        break    # Stops the loop entirely at 5
    print(i) 
# Output: 
1
2
4


5. Loop else Statement

Python has a unique feature where you can add an else block to a loop. The else block executes only if the loop finished naturally (i.e., it didn’t hit a break statement).

  • Example:
for i in range(3):
    print(i)
else:
    print("Loop finished successfully!") 

# If you put a 'break' inside the for-loop, the 'else' won't run.

🔹 Role of Comments in Python

Definition:
Comments are lines in a program that are ignored by Python and are used to explain the code for better understanding.

Purpose:

  • Improve readability
  • Explain logic
  • Help in debugging

Types:

  1. Single-line comment (#)
# This is a comment
print("Hello")
  1. Multi-line comment (using triple quotes)
"""
This is a
multi-line comment
"""

🔹 Role of Indentation in Python

Definition:
Indentation means spaces at the beginning of a line to define blocks of code.

Purpose:

  • Defines structure of code (instead of {} like other languages)
  • Makes code readable
  • Mandatory in Python (syntax rule)

Example:

if True:
    print("Hello")   # indented block
print("Outside block")

❌ Without indentation (Error):

if True:
print("Hello")   # IndentationError

🔹 Notes:

  • Comments: Non-executable statements used to explain code.
  • Indentation: Spaces used to define code blocks and structure; it is mandatory in Python.

Important Questions:

Q1. Which of the following expressions in Python evaluates to True?

(A) 2 > 3 and 2 < 3

(B) 3 > 1 and 2

(C) 3 > 1 and 3 > 2

(D) 3 > 1 and 3 < 2

Q2. What will be the output of the following code?

def f1(a, b=1):
    print(a + b, end='-')

c = f1(1, 2)
print(c, sep='*')

(A) 3-2

(B) 3-2*

(C) 3-None

(D) 3*None-

Q3. Write the output of the following code:

def Exam2026(given):
    new = 0
    while given:
        if new % 2:
            new += given % 10
        else:
            new += given % 5
        print(new, end='-')
        given //= 10

Exam2026(123456)

(A) 1-4-5-4-

(B) 2-2-4-5-

(C) 4-3-3-5-

(D) 5-1-2-4-


Q4.
Assertion (A): [1, 2, 3] + '123' is an invalid expression in Python.
Reason (R): In Python, a List can not be concatenated with a string.

(A) Both Assertion (A) and Reason (R) are true and Reason is the correct explanation for Assertion (A).
(B) Both Assertion (A) and Reason (R) are true and Reason is not the correct explanation for Assertion (A).
(C) Assertion (A) is true, but Reason (R) is false.
(D) Assertion (A) is false, but Reason (R) is true.


25. What possible output(s) from the given options will NOT be displayed when the following code is executed? Also, mention for how many iterations the for loop in the given code will run.

import random
a = [1, 2, 3, 4, 5, 6]
for i in range(4):
    j = random.randrange(i, 5)
    print(a[j], end='-')
print()

(A) 1-2-3-4-

(B) 5-4-3-2-

(C) 1-3-5-6-

(D) 4-4-4-4-

26. The function given below is written to accept a string s as a parameter and return the number of vowels appearing in the string. The code has certain errors. Observe the code carefully and rewrite it after removing all the logical and syntax errors. Underline all the corrections made.

def CountVowels(s):
    c=0
    for ch in range(s):
        if 'aeiouAEIOU' in ch:
            c=+1
    return(ch)

Correct version of code:

def CountVowels(s):
    c=0
    for ch in s:
        if ch in 'aeiouAEIOU':
            c+=1
    return(c)

Explanation:

for ch in s: # Removed range(), we need to iterate the string directly
if ch in ‘aeiouAEIOU’: # Reversed the ‘in’ logic
c += 1 # Fixed the increment logic from =+ to +=
return c # Changed return from ch to the counter c

Leave a Comment

Your email address will not be published. Required fields are marked *

Scroll to Top