Python Tutorials

Overview

Python uses the while loop to execute a set of statements as long as a condition is true.

The while Loop

i = 1 #define our indexing variable

while i < 4:
    print(i)
    i += 1 #increment the loop so that it will eventually end

Output:

1
2
3

The else Statement

The else statement will run a block of code once when the condition is no longer true.

i = 1

while i < 4:
    print(i)
    i += 1
else:
    print("i is no longer less than 4")

Output:

1
2
3
i is no longer less than 4

The break Statement

The break statement will stop a loop even if the while condition is true.

i = 1

while i < 6:
    print(i)
    if (i == 3):
        break
    i += 1

Output:

1
2
3

The continue Statement

The continue statement will stop the current iteration, and continue with the next iteration.

i = 0

while i < 6:
    i += 1
    if i == 3:
        continue
    print(i) #the number 3 will not be in the result

Output:

1
2
3
4
5
6

Python Notes:

  • The most recent major version of Python is Python 3; however, Python 2 is still in use and quite popular, although not being updated with anything other than security updates
  • Python uses new lines to complete a command, as opposed to other programming languages which often use semicolons or parentheses
  • Python relies on indentation, using whitespace to define scope, such as the scope of loops, functions, and classes; other programming languages often use curly-brackets for this purpose
  • Python string methods return new values, and DO NOT change the original string
  • Python tuples are unchangeable after created (their items CANNOT be changed or re-ordered at a later point)
  • Python sets are unordered (may appear in random orders when called), unchangeable (the value of individual items cannot be changed after creation), unindexed (items cannot be referred to by index or key), and duplicates are NOT ALLOWED
  • As of v3.7, Python dictionaries are ordered and duplicates ARE ALLOWED; in v3.6 and earlier, dictionaries were unordered (did not have a defined order and could not be referred to using an index)

We’d like to acknowledge that we learned a great deal of our coding from W3Schools and TutorialsPoint, borrowing heavily from their teaching process and excellent code examples. We highly recommend both sites to deepen your experience, and further your coding journey. We’re just hitting the basics here at 1SMARTchicken.