Part3: Loops and Conditional Functions
Topic 1: Loops
Basic Structure of a "for" loop:
- for (dummy variable) in Object:
- Do thing here
Basic Structure of a "while" loop:
- while Condition:
- Do thing here
We need to have at least one condition to implement the loop and make sure we don't get an infinite (or endless) loop. Be sure to indent the statements to repeat in the loop.
Sometimes while loops are more necessary and sometimes for loops are more necessary. In general, for loops are used when you know exactly how many times you plan to run a loop; a while loop is used when the number of iterations is uncertain.
Topic 2: Conditional Statements
An if statement is a conditional statement that does something if the condition you set is met.
Basic Structure of a conditional statment:
if Condition:
do thing here
elif Condition
do thing here
else
do thing here
An if/else statement can have many parts. If the first condition isn’t met Python moves on to the elif(else if) statement and if no statement works. Indents are still required to use if statements.
Topic 3: Functions
Basic Structure of a function:
def functionName(parameter1, parameter2, ...):
do things here
return(output)
The parentheses contain what are called parameters. These are the variables that are input into the function that contribute to the final output. Parameters are not always required; depending on the function, they can include anything from integers and strings to other functions. Let us create a simple area calculating function to get used to the syntax.