CHEAT SHEET 7

 For Loop Over a Function

Note that using loops, you can call any function multiple times, even your own functions. Let's suppose we defined this function:

That is a function that gets a number as input, adds 273.15 to it and returns the result. A for loop allows us to execute that function over a list of numbers:

The output of that would be:

282.25
281.95
3.0

So, in the first iteration celsius_to_kelvin(9.1) was executed, in the second celsius_to_kelvin(8.8) and in the third celsius_to_kelvin(-270.15).

That's just something to keep in mind.


Bonus Code: Dictionary Loop and String Formatting

You can combine a dictionary for loop with string formatting to create text containing information from the dictionary:


Another (better) way to do it::

In both cases the output is:

Output:

John Smith has as phone number +37682929928

Marry Simpons has as phone number +423998200919  


Cheatsheet (Loops)

In this section, you learned that:

  • For loops are useful for executing a command over a large number of items.

  • You can create a for loop like so:

Output:

A
B
C

  • The name after for (e.g. letter) is just a variable name


  • You can loop over dictionary keys:

Output:

John Smith
Marry Simpsons

  • You can loop over dictionary values:

Output:

+37682929928
+423998200919

  • You can loop over dictionary items:

    Output: 

    ('John Smith', '+37682929928')

    ('Marry Simpons', '+423998200919')


  • While loops will run as long as a condition is true:

    The loop above will print out the string inside print() over and over again until the 20th of August, 2090.

PYTHON PROGRAM SYNTAX SERIES

Comments

Popular Posts