Basic Python Loops
   1 min read


Common loops

For loop

Indent statements in loop

Example:

def Fahrenheit2Celcius(degrees):
  print('Celsius -> Fahrenheit')
  for celsius in degrees:
    fahrenheit = (celsius * 9/5) + 32
    print(celsius, '->', fahrenheit)


Fahrenheit2Celcius([0,5,10,15,20, 25, 30, 35, 40])

Celsius -> Fahrenheit
0 -> 32.0
5 -> 41.0
10 -> 50.0
15 -> 59.0
20 -> 68.0
25 -> 77.0
30 -> 86.0
35 -> 95.0
40 -> 104.0

Range

range()
Parameters include start of range, end of range (upto but not including the end value), and optionally the increment.
To return a sequence of integers from 0 to n, specify n-1 as a single parameter.

Example:

def Celsius2Fahrenheit():
  print('Celsius -> Fahrenheit')
  for celcius in range(10, 35, 5): # Specify start, end, & increment.
    fahrenheit = (celcius * 9/5) + 32
    print(celcius, '->', fahrenheit)


Celsius2Fahrenheit()

Celsius -> Fahrenheit
10 -> 50.0
15 -> 59.0
20 -> 68.0
25 -> 77.0
30 -> 86.0

What's on this Page