Python Logo

Week 3: Control structures

Introduction

This week we will be exploring control structures, their importance and how they help us create more dynamic and capable code

Theory

What is a control structure?

Control structured are ways to control the direction of a program based of a given condition. A useful analogy to keep in mind is the way that conditions may make you choose one route over another when driving, be it the amount of traffic or the overall distance of the path. Now there is significantly less variability in the nature of the conditions used in programming, however we can highlight a few of the condition types:

What are the scopes of control structures

Variables initialized in a control structure are only applicable in that given control structure. If you wish to use a variable initialized in a control structure you have to return the given variable(s) so that it can be used in the global scope.

If statements

What is an if statement?
An if statement is a conditional structure that checks if a given condition is true and executes the applicable block of code if true.

When do we use an if statement?
We use if statements if some form of verification is required, and if dynamic execution is required in the program.

What is the scope of variables in an if statement?
You are capable of using if statements almost everywhere in you program, you are even capable of using an if statement in the executable for your if statement.

General syntax

It follows the general syntax:


            if  condition:
                block of code
        

Here indentation is important to denote that the block of code is in the scope of the if statement. Here is a more complete example:


                a =3
                b = 4
                if b>a
                  print(a is larger)   
            

If the described condition is not met you can use the else keyword to allocate an alternative block of code for execution. E.g.:


                a=4
                if a < 0:
                    print(a is negative)
                else:
                    print(a is not negative)
                   
            

In this case the code checks if the variable is less than 0 and if so it is negative if not(else) it is not negative.

Elif is pythons way of adding more options to if statements. Elif is a contraction of elseif, which informs the program to do something else if a new condition is met. That something else being a new block of code.


            if b>a
	            print(a is less than b)
            elif a>b
	            print(a is greater than b)
        

Else else can also be used along elif statements e.g.:


            a = 1
            if a>0:
                    print(a is positive)
            elif a=0:
                    print( a is neither positive or negative)
            else:
                    print(a is negative) 
        

Python also has a ternary operator this acts as a useful shorthand syntax:


                expression if condition else do else
            

E.g.:

		    
		a=1
		print(positive) if a>0 else print(not positive)
	    

Switch statements

What is a switch statement
A switch statement is a common feature of most programming languages acting as an if statement that allows a much greater range of options for a given input.

When do we use a switch statement
We use one when the number of options may make it so that they would affect legibility and efficiency if formatted as if statements. This feature isn't available for older versions of python so please do make sure that your version is up to date.

What is their scope
They follow the same scope as if statements

General syntax
This is where python differs from other programming languages, where switch and case aren't the keywords but rather it uses match and case. Here is the syntax.


    match variable:
	case 1:
			code to be executed
	case 2:
			code to be executed
	 case default:
			code to be executed

The block of code check if the given variable matches a particular case in order to the execute it. Here is an example:


    month = 1
    match month:
        case  1:
            print(The first month is January)
        case  2:
            print(The second month is February)
        case  3:
            print(The third month is March)
        case  4:
            print(The fourth month is April)
        case  5:
            print(The fifth month is May)
        case  6:
            print(The sixth month is June)
        case  7:
            print(The seventh month is July)
        case  8:
            print(The eighth month is August)
        case  9:
            print(The ninth month is September)
        case  10:
            print(The tenth month is October)
        case  11:
            print(The eleventh month is November)
        case  12:
            print(The twelfth month is December)
        case  default:
            print(Invalid input)
      

This code uses a match-case statement to match a number to a month with its corresponding numerical position. In this code block the default case is sed for error handling to manage invalid inputs.

Practical Lab Exercises

Now that you have a basic understanding of conditional structures, it's time to apply this knowledge in practical scenarios. The following exercises will help reinforce your learning.

Q&A and Review

As you complete these exercises, it's important to review and clarify any concepts that are unclear. Use this section to revisit key ideas and ask questions.

If you're uncertain about any topics or need further explanation, don't hesitate to reach out through the discussion forum or during the Q&A sessions.