CodeGym /Java Course /Python SELF EN /A bit more about loops and if's

A bit more about loops and if's

Python SELF EN
Level 4 , Lesson 5
Available

11.1 Ternary Operator

In Python, there's this thing called a ternary operator, which is basically a tweaked version of the operator if else.

Let's say you have this code:


if a < b:
   min = a
else:
   min = b

To make such simple code take up less space, a compact way of writing it was invented. It looks like this:


min = a if a < b else b

The general form of a ternary operator can be described as:


variable = value1 if condition else value2

If the condition is true, value1 is assigned to the variable, if false — value2.

Note that a colon is not placed after the condition here.

11.2 The else Operator in Loops

In Python, the else operator is often associated with conditional operators like if. However, its use isn't limited to that, and you can also use else in loops such as for and while.

This less obvious aspect of else within the context of loops can be confusing for newbies, but it opens up interesting opportunities for controlling the program's execution flow.

How else Works in Loops

In loops, else runs after the loop completes, but only if the loop finished normally (i.e., wasn't interrupted by a break statement). This feature makes else useful for scenarios where you need to check if the loop was terminated early.

Example of use in a for loop:


for i in range(3):
    password = input('Enter password: ')
    if password == 'secret':
        print('Password accepted.')
        break
else:
    print('No input attempts left or all entered passwords are wrong.')               

Here, else is triggered if the user enters the wrong password three times. If the user enters the correct password, the loop is broken with break, and the else block isn't executed.

Example of use in a while loop:


n = 5
while n > 0:
    print(n)
    n -= 1
else:
    print('The loop finished normally.')               

In this case, else is executed after the loop finishes naturally, as the condition became false.

Practical Significance

Using else in loops can be particularly useful in search algorithms where it's necessary to determine whether the search was successful. For instance, when searching for an element in a list that doesn't exist, you can use else to print a failure message after the loop ends.

Use else in loops clearly and consistently so as not to confuse those who will read your code. Remember, else in loops isn't always intuitive, so it's worth adding comments or choosing other ways to implement logic if it makes the code more understandable.

11.3 Nested Loops

In Python, you can write very complex logic in a very compact way. For some cases, you'll need nested if's, and for others — nested loops. Let's talk about some of the nuances of their operation:

A nested loop means having one loop inside another. This allows you to process multidimensional arrays, lists of lists, or other nested data structures.

Nested loops consist of an outer loop and one or more inner loops. Each time the outer loop performs one iteration, the inner loop runs completely:


for i in range(3):  # Outer loop
    for j in range(3):  # Inner loop
        print(f"({i}, {j})")               

From the perspective of the outer loop, the inner loop and its contents are just a block of commands executed for each iteration of the outer loop. The outer loop doesn't really care what's inside, how many loops are there, and so on. It simply executes its internal command block every time for a variable in its list.

Let's print a multiplication table — nested loops are perfect for this task. Creating a multiplication table using nested loops, where one loop is responsible for the multiplier and the other for the multiplicand:


n = 5
for i in range(1, n + 1):
    for j in range(1, n + 1):
        print(f"{i} * {j} = {i * j}", end='\t')
    print()  # Move to a new line for the next multiplier               

This example will print the table:


1 * 1 = 1	1 * 2 = 2	1 * 3 = 3	1 * 4 = 4	1 * 5 = 5	
2 * 1 = 2	2 * 2 = 4	2 * 3 = 6	2 * 4 = 8	2 * 5 = 10	
3 * 1 = 3	3 * 2 = 6	3 * 3 = 9	3 * 4 = 12	3 * 5 = 15	
4 * 1 = 4	4 * 2 = 8	4 * 3 = 12	4 * 4 = 16	4 * 5 = 20	
5 * 1 = 5	5 * 2 = 10	5 * 3 = 15	5 * 4 = 20	5 * 5 = 25

To better understand nested loops, you just need to practice more — it's the quickest way to master almost any non-obvious thing in programming.

2
Task
Python SELF EN, level 4, lesson 5
Locked
Write a program that asks the user for a number and uses the ternary operator to check whether it is even or odd.
Write a program that asks the user for a number and uses the ternary operator to check whether it is even or odd.
2
Task
Python SELF EN, level 4, lesson 5
Locked
Pythagorean Multiplication Table
Pythagorean Multiplication Table
1
Опрос
Loops and Branching,  4 уровень,  5 лекция
недоступен
Loops and Branching
Loops and Branching
Comments (1)
TO VIEW ALL COMMENTS OR TO MAKE A COMMENT,
GO TO FULL VERSION
Strik3ria Level 8, Saint Louis, United States
29 December 2024
Just my two cents, the questions in the survey/quiz need to be better vetted. For instance, "What happens if the condition in the if operator is false?" seems to expect you to assume there is an else block after the if, but in reality if the if condition is false, it will do nothing, unless there is an else which was not made clear by the question.