Unit II Conditional statements and Iterative statements | Cse 108 Python Programming |B.tech cse



Conditional statements and Iterative statements 

Conditional Operators (Comparison Operators)

What they do: Conditional operators are used to compare two values and return a Boolean value (True or False). They help in evaluating conditions in control structures like if statements.

Common Conditional Operators:

Equal to (==): Checks if two values are equal.

  • Example:
    • x = 5
    • print(x == 5) # Output: True
  • Easy Explanation: "Is x equal to 5?"

Not equal to (!=): Checks if two values are not equal.

  • Example:
    • y = 10
    • print(y != 5) # Output: True
  • Easy Explanation: "Is y not equal to 5?"

Greater than (>): Checks if the left value is greater than the right value.

  • Example:
    • print(7 > 5) # Output: True
  • Easy Explanation: "Is 7 greater than 5?"

Less than (<): Checks if the left value is less than the right value.

  • Example:
    • print(3 < 5) # Output: True
  • Easy Explanation: "Is 3 less than 5?"

Greater than or equal to (>=): Checks if the left value is greater than or equal to the right value.

  • Example:
    • print(5 >= 5) e # Output: True
  • Easy Explanation: "Is 5 greater than or equal to 5?"

Less than or equal to (<=): Checks if the left value is less than or equal to the right value.

  • Example:
    • print(3 <= 5) # Output: True
  • Easy Explanation: "Is 3 less than or equal to 5?"

.

Summary of Conditional Statements in Programming

Here’s a comprehensive overview of key concepts related to conditional statements, including conditional operators:

Concept Description Example
Modulus Operator Returns the remainder of a division 10 % 3 gives 1
Random Numbers Generates a random number random.randint(1, 10)
Boolean Expressions Evaluates to True or False age >= 18
Logic Operators Combine boolean expressions a and b, a or b, not a
Conditional Statements Make decisions based on conditions if score >= 90: ...
Nested Conditionals Conditionals within conditionals if age >= 18: ... else: if age >= 16: ...
Conditional (Ternary) Operator Shortened if-else statement can_vote = "Yes" if age >= 18 else "No"
Conditional Operators Compare values and return True or False x == 5, y != 10, 7 > 5

Using Conditional Operators

Here's an example of using conditional operators in conditional statements:

age = 20
if age >= 18:
    print("You are an adult.")
else:
    print("You are a minor.")

In this example, age >= 18 checks if the age qualifies as an adult.

Conditional Statements

1. Modulus Operator (%)

  • What it does: Returns the remainder of a division.
  • Example:
    • remainder = 10 % 3 # 10 divided by 3 leaves a remainder of 1
    • print(remainder) # Output: 1
  • Easy Explanation: If you have 10 cookies and want to put them in boxes that hold 3 each, you’ll have 1 cookie left over.

2. Random Numbers

  • What it does: Generates a random number within a specified range.
  • Example:
    • import random
    • number = random.randint(1, 10) # Random number between 1 and 10
    • print(number) # Output could be any number from 1 to 10
  • Easy Explanation: Imagine rolling a 10-sided die; you don’t know which number will show up until you roll it.

3. Boolean Expressions

  • What it does: An expression that evaluates to either True or False.

  • Example:
    • age = 21
    • is_adult = age >= 18 # This evaluates to True
    • print(is_adult) # Output: True
  • Easy Explanation: It’s like asking, "Is my age greater than or equal to 18?" The answer is either "yes" (True) or "no" (False).

4. Logic Operators

  • What they do: Combine multiple Boolean expressions.
  • AND:
    • a = True
    • b = False
    • result = a and b # Evaluates to False
    • print(result) # Output: False
  • OR:
    • a = True
    • b = False
    • result = a or b # Evaluates to True
    • print(result) # Output: True
  • NOT:
    • a = True
    • b = False
    • result = not a # Evaluates to False
    • print(result) # Output: False
  • Easy Explanation:
    • AND: "I’ll go out if it’s sunny and warm." Both must be true.
    • OR: "I’ll go out if it’s sunny or warm." At least one must be true.
    • NOT: "If it’s not sunny, I’ll stay in." It flips the condition.

5. Conditional Statements

What they do: Allow your program to make decisions based on conditions.

  • Example:

    • score = 85
  • if score >= 90:
    • print("Grade: A")
  • elif score >= 80:
    • print("Grade: B")
  • else:
    • print("Grade: C")
  • Easy Explanation: It’s like saying, "If I score 90 or above, I get an A; if I score 80 or above, I get a B; otherwise, I get a C."

6. Nested Conditionals

What they do: Conditionals inside other conditionals for more complex decision-making.

  • Example:
    • age = 16
  • if age >= 18:
    • print("You can vote.")
  • else:
    • if age >= 16:
      • print("You can drive.")
    • else:
      • print("You are too young.")
  • Easy Explanation: "If I’m 18 or older, I can vote. If I’m at least 16 but not 18, I can drive. Otherwise, I’m too young for both."

7. Conditional (Ternary) Operator

What it does: A shorthand way to write an if-else statement in a single line.

  • Example:
    • age = 20
    • can_vote = "Yes" if age >= 18 else "No"
    • print(can_vote) # Output: Yes

Working Steps:

  • Define a condition (e.g., age >= 18).
  • If True, the result is the first value ("Yes").
  • If False, the result is the second value ("No").
  • Easy Explanation: It’s like saying, "If I’m 18 or older, I can vote; otherwise, I cannot.
Concept Description Example
Modulus Operator Returns the remainder of a division 10 % 3 gives 1
Random Numbers Generates a random number random.randint(1, 10)
Boolean Expressions Evaluates to True or False age >= 18
Logic Operators Combine boolean expressions a and b, a or b, not a
Conditional Statements Make decisions based on conditions if score >= 90: ...
Nested Conditionals Conditionals within conditionals if age >= 18: ... else: if age >= 16: ...
Conditional (Ternary) Operator Shortened if-else statement can_vote = "Yes" if age >= 18 else "No"
Conditional Operators Compare values and return True or False x == 5, y != 10, 7 > 5

Iterative statements 

1. While Statements

What it does: Executes a block of code repeatedly as long as a specified condition is True.

Example

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

Working Steps:

  • Initialize a variable (e.g., count = 0).
  • Check the condition (count < 5). If True, execute the loop.
  • Print the value of count.
  • Increment count by 1.
  • Repeat until the condition is False.

Easy Explanation: This loop prints numbers from 0 to 4. It keeps counting up until it reaches 5.

2. For Loop Statement

What it does: Iterates over a sequence (like a list or a range) a specific number of times.

Example

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

Working Steps:

  • Use range(5) to generate numbers from 0 to 4.
  • Assign each number to i in each iteration.
  • Print the value of i.

Easy Explanation: This loop prints numbers from 0 to 4, similar to the while loop but in a more compact way.

3. Nested For Loops

What it does: A loop inside another loop, allowing for multi-dimensional iterations.

Example

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

Working Steps:

  • Outer loop runs 3 times (for i = 0, 1, 2).
  • Inner loop runs 2 times for each iteration of the outer loop (for j = 0, 1).
  • Prints the combination of i and j.

Easy Explanation: This prints pairs of numbers, like (0,0), (0,1), (1,0), (1,1), etc.

4. Nested While Loops

What it does: A while loop inside another while loop, allowing for complex iterations.

Example

i = 0
while i < 3:
    j = 0
    while j < 2:
        print(i, j)
        j += 1
    i += 1

Working Steps:

  • Outer loop checks if i < 3.
  • For each i, inner loop checks if j < 2.
  • Prints the combination of i and j.

Easy Explanation: Similar to nested for loops, but using while loops. It also prints pairs like (0,0), (0,1), (1,0), etc.

5. Random Numbers in Loops

What it does: Generates random numbers during each iteration of a loop.

Example

import random
for _ in range(5):
    print(random.randint(1, 10))

Working Steps:

  • Import the random module.
  • Loop 5 times.
  • Generate a random number in each iteration.
  • Print the random number.

Easy Explanation: This prints five random numbers between 1 and 10.

6. Encapsulation

What it does: Bundles data and methods that operate on that data within one unit (usually a class).

Example

class Counter:
    def __init__(self):
        self.count = 0

    def increment(self):
        self.count += 1

    def get_count(self):
        return self.count

counter = Counter()
counter.increment()
print(counter.get_count())

Working Steps:

  • Define a class (Counter).
  • Initialize count to 0.
  • Create methods to increment and get the count.

Easy Explanation: This class keeps track of a count, allowing you to increase it and check its value, while hiding the internal workings.

7. Generalization

What it does: Creates a more abstract version of a function or class to handle a wider range of cases.

Example

def add_numbers(a, b):
    return a + b

print(add_numbers(5, 3))
print(add_numbers(2.5, 3.5))

Working Steps:

  • Define a function that can take any two numbers.
  • Return the sum of those numbers.

Easy Explanation: This function can add any two numbers together, whether they are integers or floats.

Post a Comment

If you have any doubt, Please let me know.

Previous Post Next Post