0% found this document useful (0 votes)
1 views

Python Chap4

Chapter 4 covers control structures in Python, including if...else statements, logical operators, and looping constructs like while and for loops. It explains the use of break, continue, and else statements in loops, as well as the range() function for iteration. Chapter 5 introduces functions, their definitions, arguments, and recursion, along with lambda functions for creating small anonymous functions.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
1 views

Python Chap4

Chapter 4 covers control structures in Python, including if...else statements, logical operators, and looping constructs like while and for loops. It explains the use of break, continue, and else statements in loops, as well as the range() function for iteration. Chapter 5 introduces functions, their definitions, arguments, and recursion, along with lambda functions for creating small anonymous functions.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 25

Chapter – 4 -

Control Structure
If ... Else
• An "if statement" is written by using the if keyword.

• Indentation
• Python relies on indentation (whitespace at the beginning of a line) to define scope
in the code. Other programming languages often use curly-brackets for this purpose.
If ... Else
• Elif
• The elif keyword is Python's way of saying "if the previous conditions were not true,
then try this condition".

• Else
• The else keyword catches anything which isn't caught by the preceding conditions.
If ... Else
• Short Hand If
• If you have only one statement to execute, you can put it on the same line as the if
statement.

• Short Hand If ... Else


• If you have only one statement to execute, one for if, and one for else, you can put it
all on the same line:

• You can also have multiple else statements on the same line:
If ... Else
• And
• The and keyword is a logical operator, and is used to combine conditional statements:

• Or
• The or keyword is a logical operator, and is used to combine conditional statements:
If ... Else
• Not
• The not keyword is a logical operator, and is used to reverse the result of the
conditional statement:

• Nested If
• You can have if statements inside if statements, this is called nested if statements.

• The pass Statement


• if statements cannot be empty, but if you for some reason have an if statement
with no content, put in the pass statement to avoid getting an error.
Looping
While Loops
• With the while loop we can execute a set of statements as long as a condition is true.

• Note: remember to increment i, or else the loop will continue forever.


• The while loop requires relevant variables to be ready, in this example we need to define
an indexing variable, i, which we set to 1.
• The break Statement
• With the break statement we can stop the loop even if the while condition is true:
While Loops
• The continue Statement
• With the continue statement we can stop the current iteration, and continue with the
next:

• The else Statement


• With the else statement we can run a block of code once when the condition no
longer is true:
For Loops
• A for loop is used for iterating over a sequence (that is either a list, a tuple, a dictionary,
a set, or a string).

• This is less like the for keyword in other programming languages, and works more like
an iterator method as found in other object-orientated programming languages.

• With the for loop we can execute a set of statements, once for each item in a list, tuple,
set etc.

• The for loop does not require an indexing variable to set beforehand.
• Looping Through a String
• Even strings are iterable objects, they contain a sequence of characters:
For Loops
• The break Statement
• With the break statement we can stop the loop before it has looped through all the
items:

• The continue Statement


• With the continue statement we can stop the current iteration of the loop, and
continue with the next:
For Loops
• The range() Function
• To loop through a set of code a specified number of times, we can use the range() function,
• The range() function returns a sequence of numbers, starting from 0 by default, and
increments by 1 (by default), and ends at a specified number.

• Note that range(6) is not the values of 0 to 6, but the values 0 to 5.


• The range() function defaults to 0 as a starting value, however it is possible to specify the
starting value by adding a parameter: range(2, 6), which means values from 2 to 6 (but not
including 6):
For Loops
• The range() function defaults to increment the sequence by 1, however it is possible to
specify the increment value by adding a third parameter: range(2, 30, 3):

• Else in For Loop


• The else keyword in a for loop specifies a block of code to be executed when the
loop is finished:

• Note: The else block will NOT be executed if the loop is stopped by a break
statement.
For Loops
• Nested Loops
• A nested loop is a loop inside a loop.
• The "inner loop" will be executed one time for each iteration of the "outer loop":

• The pass Statement


• for loops cannot be empty, but if you for some reason have a for loop with no
content, put in the pass statement to avoid getting an error.
Chapter – 5

• Functions and Optimization


Functions
• A function is a block of code which only runs when it is called.
• You can pass data, known as parameters, into a function.
• A function can return data as a result.
• Creating a Function
• In Python a function is defined using the def keyword:

• Calling a Function
• To call a function, use the function name followed by parenthesis:

• Arguments
• Information can be passed into functions as arguments.
• Arguments are specified after the function name, inside the parentheses. You can add
as many arguments as you want, just separate them with a comma.
Functions
• Arguments

• Parameters or Arguments?
• The terms parameter and argument can be used for the same thing: information that are
passed into a function.
• From a function's perspective:
• A parameter is the variable listed inside the parentheses in the function definition.
• An argument is the value that is sent to the function when it is called.
• Number of Arguments
• By default, a function must be called with the correct number of arguments. Meaning that if your
function expects 2 arguments, you have to call the function with 2 arguments, not more, and not less.
Functions
• Arbitrary Arguments, *args
• If you do not know how many arguments that will be passed into your function, add
a * before the parameter name in the function definition.
• This way the function will receive a tuple of arguments, and can access the items
accordingly:

• Keyword Arguments
• You can also send arguments with the key = value syntax.
• This way the order of the arguments does not matter.

• The phrase Keyword Arguments are often shortened to kwargs in Python


documentations.
Functions
• Arbitrary Keyword Arguments, **kwargs
• If you do not know how many keyword arguments that will be passed into your
function, add two asterisk: ** before the parameter name in the function definition.
• This way the function will receive a dictionary of arguments, and can access the
items accordingly:

• Default Parameter Value


• The following example shows how to use a default parameter value.
• If we call the function without argument, it uses the default value:
Functions
• Passing a List as an Argument
• You can send any data types of argument to a function (string, number, list,
dictionary etc.), and it will be treated as the same data type inside the function.
• E.g. if you send a List as an argument, it will still be a List when it reaches the
function:

• Return Values
• To let a function return a value, use the return statement:
Functions
• The pass Statement
• function definitions cannot be empty, but if you for some reason have a function
definition with no content, put in the pass statement to avoid getting an error.

• Positional-Only Arguments
• You can specify that a function can have ONLY positional arguments, or ONLY
keyword arguments.
• To specify that a function can have only positional arguments, add , / after the
arguments:

• Without the , / you are actually allowed to use keyword arguments even if the
function expects positional arguments:
Functions
• But when adding the , / you will get an error if you try to send a keyword argument:

• Keyword-Only Arguments
• To specify that a function can have only keyword arguments, add *, before the
arguments:

• Without the *, you are allowed to use positional arguments even if the function
expects keyword arguments:

• But when adding the *, / you will get an error if you try to send a positional
argument:
Functions
• Combine Positional-Only and Keyword-Only
• You can combine the two argument types in the same function.
• Any argument before the / , are positional-only, and any argument after the *, are
keyword-only.

• Recursion
• Recursion is a common mathematical and programming concept. It means that a
function calls itself. This has the benefit of meaning that you can loop through data
to reach a result.
Lambda
• A lambda function is a small anonymous function.
• A lambda function can take any number of arguments, but can only have one
expression.
• Syntax:

• Lambda functions can take any number of arguments:


Lambda
• Why Use Lambda Functions?
• The power of lambda is better shown when you use them as an anonymous function
inside another function.
• Say you have a function definition that takes one argument, and that argument will
be multiplied with an unknown number:

• Use that function definition to make a function that always doubles the number you
send in:

• Or, use the same function definition to make a function that always triples the
number you send in:

You might also like