Python Basics

Here are my Python essentials for anyone wanting to learn this programming language. This post will be continually updated.

This is my favorite Python book on Amazon, if you are interested in learning Python I highly recommend it

 

Table of Contents

Getting Started With Python

 

Python is one of the most popular programming languages. It is used for a lot of different fields including, science, data analysis, and application development. 

Its commands are processed by an interpreter. 

Most of Python’s keywords are English words that make it easy for beginners to understand. It uses indentation liberally to group statements into blocks of code. This helps in reading and comprehending the code. 

 

Installing Python

For the Windows operating system, you just go to Python’s website and download the executable.

https://python.org/downloads

Follow the instructions and you will soon have a functional Python interpreter installed and working. 

For Linux systems, Python usually comes with the distribution. So, there will usually be nothing to do except update your version. To update your version, just use your package manager to do this. Linux users will understand what this means immediately. If it is not installed, you can use your package manager to install it. Search python3 to find it.

 

Using The Interpreter

The Python interpreter processes text. You type this text in the shell of your operating system or in a text editor.  

You can interact with the Python interpreter a few different ways.

  • In Windows, open CMD and type python
  • In Linux, open a terminal window and type python
  • From the start menu, you can choose Python
  • From the start menu, you can choose the IDLE program 

You can use the interpreter as a calculator with parentheses as needed. 

 

Your First Program

You can type commands and write your first program from this window. A Python program is just a text file with commands in it and saved with the .py extension. It is also a good idea to create a python folder somewhere to save your programs. 

In your interpreter window, we can print some text. That is technically a program but it is what most languages start with. Type:

print(‘I am learning Python’)

Use the menu to save this to your computer. Call it something like ‘learn.py’. Name it whatever you want though, it does not matter. 

You can navigate to the file through your gui and double click it.

You can also navigate to it through your command line. If you do it this way, once you are in the directory where the file is located, just type ‘python learn.py’ to run it.

 

Using Variables

All programming languages have variables. Python is no exception. Variables let you store data. You can then run operations on the variables as needed. Name your variables something meaningful.

life_counter=0

temperature=55

The first part is the variable name followed by an equals sign. After that contains the value of the variable. All variables must be initialized when created. This means they must be assigned a value when they are first created. 

You do not have to specify a data type when creating variables. This is called dynamic typing.

 

Comments

Comments are a universal way for programming languages to document code. They are meant to explain the thoughts behind a statement, the purpose of a block of code, and to make it easier on anyone reading the code at a later date.

You use the # symbol in front of a line of text to make it a comment. 

# The purpose of this variable is to be a counter and keep track of the iterations in a loop

You can do multi-line comments by enclosing text within triple quote marks(“””).

 

User Input

To capture user input, we use the input() function. It will accept a string inside its parentheses. Afterwards, it will prompt the user for input. User input is read as a text string. The text string is then assigned to a variable. 

fav_team=input(‘What is your favorite baseball team? : ‘)

print(fav_team)

 

Errors

There are three types of errors that can occur. They are:

  • Syntax
  • Runtime
  • Semantic

Syntax errors are when you use the Python language incorrectly. An example of this is misspelling a keyword. Runtime errors can happen when you run a program. This can be a lot of different things but generally means something was misused. Semantic errors are not technically errors. The program can still run but you get unexpected results.

 

Overview

The Python language is processed by the interpreter. It is a high level language because it uses English wording. Indentation is used to group statements into blocks. A Python program is just a text file that uses the .py file extension. The print() function outputs the string enclosed within its parentheses. String values are enclosed within quote marks. 

A variable is a container with a name. It stores values and can be used by referencing that variable’s name. Variables can be any data type but they all have to be initialized first with some value. The input() function accepts user input. You can assign this input to a variable to increase your program usefulness. 

 

Python Operations

 

Let us get familiar with python operations and how they are used.

If you have not already, make a new folder at the base of your drive and call it python.

We will store our scripts here in case we need them to expand on a subject.

As in other programming languages, use parentheses to direct the order of operations.

Values in our expressions are called operands.

All the different python operations have an order in which they are performed.

 

Arithmetic

Define some variables:

a=5
b=10

print( a, '+', b, '=', a + b )
5 + 10 = 15

print( a, '-', b, '=', a - b )
5 - 10 = -5

print( a, '*', b, '=', a * b )
5 * 10 = 50

print( b, '/', a, '=', b / a )
10 / 5 = 2.0

print( a, '%', b, '=', a / b )
5 % 10 = 0.5

print( a, '^2 =', a*a, sep = '')
5^2 = 25

The sep character sequence specifies space in the output. We will use it more later.



Assigning Values

There are many ways to assign values in python. There are several ways to assign values because these are shortcuts and save time once you learn them.

 

=

a=b

a=b

+=

a+=b

a=(a+b)

-=

a-=b

a=(a-b)

*=

a*=b

a=(a*b)

/=

a/=b

a=(a/b)

%=

a%=b

a=(a%b)

//=

a//b

a=(a//b)

**=

a**b

a=(a**b)



These operations are efficient to use. It will save you time by learning these shortcuts slowly.

Also, the ‘=’ operator assigns a value to a variable. It does not test equality between two different variables or values.

 

Let us practice these shortcuts with some simple examples.

 

a=10
b=20

print(‘Initializing Variables:\t\t’, ‘a =’ a, ‘\tb =’, b)
a += b

print(‘Addition:\t\t’, ‘a =’, a, ‘(10+20)’)
a -= b

print(‘Subtraction:\t’, ‘a =’, a, ‘(20-10)’)
a *= b

print(‘Multiplication:\t’, ‘a =’, ‘(10*20)’)
a /= b

print(‘’Division:\t’, ‘a =’, a, ‘(20 / 10)’)
a %= b

print(‘Modulo:\t’, ‘a =’, a, ‘(20 % 10)’)

 

Comparing Values

As in math and other languages, there are several operators for comparing values in python. The most commonly used are:



==

Equality

!=

Inequality

>

Greater Than

<

Less Than

>=

Greater Than or Equal To

<=

Less Than or Equal To

  

 

This is logic math. For example, the ‘==’ will compare two operands and return true if both are equal in value. The ‘!=’ operator returns true if two operands are not equal. The ‘>’ operator returns true if the first operator is greater than the second. The ‘<’ operator returns true if the first operator is less than the second.

 

The ‘>=’ operator returns true if the operand is greater than or equal to the second. The ‘<=’ returns true if the operand is less than or equal to the second. 

 

nothing=0
zero=0
one=1
upper= 'A'
lower= 'a'

print('Equality :\t', nothing, '==', zero, nothing == zero)
print('Equality :\t', upper, '==', lower, upper == lower)
print('Inequality :\t', nothing, '!=', one, nothing != one)
print('Greater :\t', nothing, '>', one, nothing > one)
print('Lesser :\t', nothing, '<', one, nothing < one)
print('Greater or Equal To :\t', nothing, '>=', zero, nothing >= zero)
print('Less Than or Equal To :\t', one, '<=', zero, one <= zero)

 

Logic

Logic operators are used a lot in python. They include:

 

and

Logical And

or

Logical Or

not

Logical Not



Logical And will look at two operators and return true if both operands are true.

Logical Or will look at two operators and return true if one of the operands is true.

Logical Not is used with another operand and returns the inverse value of it.

This is called boolean logic.

 

t=True
f=False

print('And Logic:')
print('t and t =', t and t)
print('t and f =', t and f)
print('f and f =', f and f)

print('\nOr Logic:')
print('t or t =', t or t)
print('t or f =', t or f)
print('f or f =', f or f)

print('\nNot Logic:')
print('t =', t, '\tnot t =', not t)
print('f =', f, '\tnot f =', not f)

 

Conditions

Every programming language I have heard of has a way to test conditions to see if they are true or false. Python is no different. You have an expression and if it is true you do a certain action. However, if it is false , you do a different action. It is called the conditional expression. You can use several different operators with the conditional expression.

 

An expression will return a value of some kind. In Python, this is the test expression and up to two actions afterwards. 

 

a=1
b=2

print('\nVariable a is :', 'One' if(a==1) else 'Not One')
print('Variable a is : :', 'Even' if(a%2==0) else 'Odd')

print('\nVariable b is :', 'One' if (b==1) else 'Not One')
print('Variable b is :', 'Even' if (b%2==0) else 'Odd')

max = a if (a>b) else b

print('\nGreater Value Is :', max)

 

Precedence

Operator precedence determines the order in which the interpreter evaluates expressions. You can dictate precedence with certain operators. 

 

a=2
b=4
c=8

print('\nDefault Order :\t', a, '*', c,'+', b, '=', a*c+b)
print('Forced Order :\t', a, '* (',c,'+',b,') =', a*(c+b))

print('\nDefault Order :\t', c, '//', b, '-', a, '=', c//b-a)
print('Forced Order :\t', c,'// (',b,'-', a,')=', c//(b-a))

print('\nDefault Order :\t', c, '%', a, '+', b, '=', c%a+b)
print('Forced Order :\t', c, '% (',a,'+',b,')=', c%(a+b))

print('\nDefault Order :\t', c, '**', a, '+', b, '=', c**a+b)
print('Forced Order :\t', c, '** (',a, '+', b,')=', c**(a+b))

 

Casting Data Types

The most popular data types are string, integer, and float. Data type recognition is especially important when assigning numeric data to variables from user input as it is stored by default as a string data type. The data type of stored values can be easily converted into a different data type using built-in functions. The built-in data type conversion functions return a new object representing the converted value. 

  • int(x) - converts x to an integer whole number
  • float(x) - converts x to a floating-point number
  • str(x) - converts x to a string representation
  • chr(x) - converts x to a character
  • unichr(x) - converts x to a unicode character
  • ord(x) - converts x to its integer value
  • hex(x) - converts x to its hexadecimal value
  • oct(x) - converts integer x to an octal string

The Python built-in type() function can be used  to determine which data type class the value contained in a variable. 

 

a=input('Enter A Number:')
b=input('Now Enter Another Number:')

sum=a+b
print('\nData type sum:', sum, type(sum))

sum=int(a)+int(b)
print('Data type sum:', sum, type(sum))

sum=float(sum)
print('Data type sum:', sum, type(sum))

sum=chr(int(sum))
print('Data type sum:', sum, type(sum))



Manipulating Bits

In computer terms, each byte comprises 8 bits that can each contain a 1 or a 0 to store a binary number, representing decimal values from 0 to 255. It is possible to manipulate individual parts of a byte using the Python bitwise operators listed below:

  • | Or
  • & And
  • ~ Not
  • ^ Xor
  • << Shift left
  • >> Shift right

Unless programming for a device with limited resources, there is seldom a need to utilize bitwise operators, but they can be useful.

 

a=10
b=5
print('a=', a, '\tb=', b)

# 1010 ^ 0101 = 1111 (decimal 15)
a=a^b

# 1111 ^ 0101 = 1010 (decimal10)
b=a^b

# 1111 ^ 1010 = 0101 (decimal 5)
a=a^b

print('a=', a, '\tb=', b)



Arithmetic operators can form expressions with two operands for addition, subtraction, multiplication, division, floor division, modulo, and exponent.

The assignment operator (=) can be combined with an arithmetic operator to perform an arithmetic calculation then assign its result.

Comparison operators can form expressions comparing two operands for equality, inequality, greater, lesser, greater or equal, and lesser or equal values.

Logical (and) and (or) operators  form expressions evaluating two operands  to return a boolean value of true or false.

The logical not operator returns the inverse boolean value of a single operand.

A conditional if-else expression evaluates a given expression for a boolean True or False value, then returns one of two operands depending on the result.

Expressions containing multiple operators will execute their operations in accordance with the default precedence rules unless explicitly determined by the addition of parentheses.

The data type of a variable value can be converted to a different data type by the built-in Python functions int(), float(), and str() to return a new converted object.

Python’s built-in type() function determines to which data type class a specified variable belongs.

Bitwise operators OR, And, Not, and Xor each return a value after comparison of the values within two bits whereas the Shift left and Shift right operators move the bit values a specified number of bits in their direction. 




Statements in Python

 

In Python, a variable must be initialized before it can be used. This is usually done in the statement that uses it. 

More than one variable can be initialized  with the same value using a single statement. 

A = b = d = e = 10

More than one variable can also be initialized to different values using commas in a statement.

A, b, c, = 15, 25, 35

Unlike regular variables, which can only store a single item of data, Python can use a list which can store multiple items of data. The data is stored sequentially in list elements that are index numbered starting at zero. The first value is stored in element zero and goes up from there.

A list is created much like any other variable, but it is initialized by assigning values as a comma-separated list between square brackets.

num=[0,1,2,3,4,5]

An individual list element can be referenced using the list name followed by square brackets containing that element’s index number. This means that num[1] references the second element in the example above, since the first element starts at zero.

Lists can have more than one index to represent multiple dimensions, rather than the single dimension of a regular list. Multi-dimensional lists of three indices and more are uncommon but two-dimensional lists are useful to store grid-based information such as [x,y] coordinates.

A list of string values can even be considered to be a multi-dimensional list, as each is itself a list of characters. Each character can be referenced by its index number within its particular string.

 

quarter=[‘January’, ‘February’, ‘March’]

print(‘First Month:’, quarter[0])

print(‘Second Month:’, quarter[1])

print(‘Third Month:’, quarter[2])

coordinates=[ [1,2,3] , [4,5,6] ]

print(‘\nTop Left 0,0:’, coordinates[0][0] )

print(‘Bottom Right 1,2:’, coordinates[1][2] )

print(‘\nSecond Month First Letter:’, quarter[1][0] )

 

String indices may also be negative numbers. To start counting from the right where -1 references the last letter.

 

Manipulating Lists

List variables can contain multiple items of data. They are widely used in Python and have a number of methods and options.



list.append(x)

Adds item x to the end of the list

list.extend(L)

Adds all items in list L to the end of the list

list.insert(i,x)

Inserts item x at index position i

list.remove(x)

Removes first item x from the list

list.pop(i)

Removes item at index i and returns it 

list.index(x)

Returns the index in the list of first item x

list.count(x)

Returns the number of times x appears in list

list.sort()

Sort all list items, in place

list.reverse()

Reverse all list items, in place

 

Python also has a useful len(L) function that returns the length of the list L as the total number of elements it contains. Like the index() and count() methods, the returned value is numeric so cannot be directly concatenated to a text string for output.

String representation of numeric values can be produced by Python’s str(n) function for concatenation to other strings, which returns a string version of the numeric n value. A string representation of an entire list can be returned by the str(L) function for concatenation to other strings. Remember that the original version remains unchanged as the returned versions are merely copies of the original version.

Individual list elements can be deleted by specifying their index number to the Python del(i) function. This can remove a single element at a specified i index position, or a slice of elements can be removed using slice notation i1:i2 to specify the index number of the first and last element. In this case, i1 is the index number of the first element to be removed and all elements up to, but not including, the element at the i2 index number will be removed.

 

basket=['Apple', 'Bun', 'Cola']

crate=['Egg', 'Fig', 'Grape']




print('Basket List:', basket)

print('Basket Elements:', len(basket))




basket.append('Damson')

print('Appended:', basket)

print('Last Item Removed:', basket.pop())

print('Basket List:', basket)




basket.extend(crate)

print('Extended:', basket)

del basket[1]

print('Item Removed:', basket)

del basket[1:3]

print('Slice Removed:', basket)

 

The last index number in the slice denotes at what point to stop removing elements, but the element at that position does not get removed.

 

Restricting Lists

For a tuple, the values in a regular list can be changed as the program proceeds, but a list can be created with fixed immutable values that cannot be changed by the program. A restrictive immutable Python list is known as a tuple and is created by assigning values as a comma-separated list between parentheses in a process known as tuple packing.

colors-tuple=(‘Red’, ‘Green’, ‘Red’, ‘Blue’, ‘Red’)

An individual tuple element can be referenced using the tuple name followed by square brackets containing that element’s index number. Usefully, all values stored inside a tuple can be assigned to individual variables in a process known as sequence unpacking.

A,b,c,d,e = colors-tuple

For a set, the values in a regular list can be repeated in its elements, as in the tuple above, but a list of unique values can be created where duplication is not allowed. A restrictive Python list of unique values is known as a set and is created by assigning values as a comma-separated list between curly brackets.

phonetic-set={‘Alpha’, ‘Bravo’, ‘Charlie’)

Individual set elements cannot be referenced using the set name followed by square brackets containing an index number, but instead sets have methods that can be dot-suffixed to the set  name for manipulation and comparison. 



set.add(x)

Adds item x to the set

set.update(x,y,z)

Adds multiple items to the set

set.copy()

Returns a copy of the set

set.pop()

Removes one random item from the set

set.discard(x)

Removes item x if found in the set

set1.intersection(set2)

Returns items that appear in both sets

set1.difference(set2)

Returns items in set1 but not in set2

  



zoo=('Kangaroo', 'Leopard', 'Moose',)

print('Tuple:', zoo, '\tLength:', len(zoo))

print(type(zoo))




bag={'Red', 'Green', 'Blue'}

bag.add('Yellow')

print('\nSet:', bag, '\tLength', len(bag))

print(type(bag))




print('\nIs Green in bag Set?:', 'Green' in bag)

print('Is Orange in bag Set?:', 'Orange' in bag)




box={'Red', 'Purple', 'Yellow'}

print('\nSet:', box, '\t\tLength', len(box))

print('Common to both Sets:', bag.intersection(box))



In Python programming a dictionary is a data container that can store multiple items of data as a list of key:value pairs. Unlike regular list container values, which are referenced by their index number, values stored in dictionaries are referenced by their associated key. The key must be unique within that dictionary, and is typically a string name although numbers may be used.

Creating a dictionary is simply a matter of assigning the key:value pairs as a comma-separated list between curly brackets to a name of your choice. Strings must be enclosed within quotes, as usual, and a : colon character must come between the key and its associated value.

A key:value pair can be deleted from a dictionary by specifying the dictionary name and the pair’s key to the del keyword. Conversely, a key:value pair can be added to a dictionary by assigning a value to the dictionary’s name and a new key.

Python dictionaries have a keys() method that can be dot-suffixed to the dictionary name to return a list, in random order, of all the keys in that dictionary. If you prefer the keys to be sorted into alphanumeric order, simply enclose the statement within the parentheses of the Python sorted() function.

A dictionary can be searched to see if it contains a particular key with the Python in operator, using the syntax key “in” dictionary. The search will return a boolean True value when the key is found in the specified dictionary, otherwise it will return false.

Two dictionaries can be merged into one single dictionary using the | merge operator, where dict3=dict1 | dict2. Alternatively, a dictionary can be merged with a second dictionary using the |= update operator, where dict1 |= dict2.

Dictionaries are the final type of data container available in Python. Here are the types again:



Variable

A single value

List

Multiple values in an ordered index

Tuple

Multiple fixed values in a sequence

Set

Unique values in an unordered collection

Dictionary

Multiple unordered key:value pairs

 

user_sys={'name': 'Bob', 'sys': 'Win'}

user_lang={'name': 'Bob', 'lang': 'Python'}




dict=user_sys|user_lang

print('\nDictionary:', dict)




print('\nLanguage:', dict['lang'])




print('\nKeys:', dict.keys())




del dict['name']

dict['user']='Tom'

print('\nDictionary:', dict)




print('\nIs There A Name Key?:', 'name' in dict)

 

Notice the quotes must be preceded by a backslash character within a string to prevent the string being prematurely terminated.

 

Branching in Python

 

The Python if keyword performs the basic conditional test that evaluates a given expression for a boolean value of True or False. This allows a program to proceed in different directions according to the result of a test and it is known as conditional branching.

 

The tested expression must be followed by a :, then statements to be executed when the test succeeds should follow below on separate lines, and each line must be indented from the if test line. The size of the indentation is not important, but it must be the same for each line.

 

If expression

Do this

 

An if test can offer alternative statements to execute when the test fails by appending an else keyword after the statements to be executed when the test succeeds.

 

If expression

Do this

Else:

Alternative expression

 

An if test block can also be followed by an alternative test using the elif keyword (else if) that offers statements to be executed when the alternative test succeeds.

 

If expression

Do this

Elif another expression

Do this instead

Else:

Do this when the above are false

 

Conditional branching can also be performed using a match case block. A value to be evaluated is specified after the match keyword and this is compared to a pattern specified to one or more case statements. Only when the specified value matches a pattern will the statements inside that case block be executed, otherwise the program will simply proceed. A match case block has this syntax:

 

Match value:

Case 1:

Do this

Case 2:

Do this

Case 3:

Do this

 

Indentation of code is very important in Python as it identifies code blocks to the interpreter. The match case block in Python is similar to the switch case block found in other languages.

 

num = int(input(' Please enter a number: '))




if num > 5:

    print(' Number is greater than 5\n ')

elif num < 5:

    print(' Number is less than 5\n ')

else:

    print(' Number is 5\n ')




    cmd = input(' Enter STOP or GO: ').upper()




    match cmd:

        case 'GO':

            print(' Started ')

        case 'STOP':

            print(' Stopped ')

 

The user input is read as a string value by default, so must be cast as an int data type with int() for arithmetical comparison. The match comparison is case-sensitive so the user input is forced to uppercase by the upper() string method before comparison.



Looping

A loop is a piece of code in a program that automatically repeats. One complete execution of all statements within a loop is called an iteration. The length of the loop is controlled by a conditional test made within the loop. While the tested expression is found to be true, the loop will continue. When the tested expression is found to be false the loop ends.

 

In Python programming, the while keyword created a loop. It is followed by the test expression then a : character. Statements to be executed when the test succeeds should follow below on separate lines, and each line must be indented the same space from the while test line. This statement block must include a statement that will at some point change the result of the expression evaluation, otherwise an infinite loop is created. 

 

Indentation of code blocks must also be observed in Python’s interactive mode. Loops can be nested, one within another, to allow complete execution of all iterations of an inner nested loop on each iteration of the outer loop. A counter variable can be initialized with a starting value immediately before each loop definition, included in the test expression, and incremented on each iteration until the test fails, then the loop ends. 

 

Unlike other Python keywords, the keywords True and False begin with uppercase letters. Hit return to move to the next line and see the interpreter automatically indent the new line as it expects further statements. Hit return again to execute the entered code.

 

i = 1

while i <4:

    print( '\nOuter loop iteration: ', i)

    i+=1

    j = 1

    while j <4:

        print( '\nInner loop iteration: ',j)

        j+=1

 

The output printed from the inner loop is indented from that of the outer loop by the \t tab character. The += assignment statement i +=1 is simply a shorthand way to say i=i+1. 

 

Looping Over Items

 

In Python programming, the for keyword loops over all items in any list specified to the in keyword. This statement must end with a : colon character, and statements to be executed on each iteration of the loop must be indented.

 

For each item inlist

Statements to be executed on each iteration

Statements to be executed on each iteration

 

As a string is simply a list of characters, the for in statement can loop over each character. Similarly, a for in statement can loop over each element in a list, each item in a tuple, each member of a set, or each key in a dictionary.

 

A for in loop iterates over the items of any list or string in the order that they appear in the sequence, but you cannot directly specify the number of iterations to make, a halting condition, or the size of iteration step. You can, however, use the Python range() function to iterate over a sequence of numbers by specifying a numeric end value within its parameters. This will generate a sequence that starts at zero and continues up to, but not including, the specified end value. For example, range(5) generates 0,1,2,3,4. 

 

Optionally, you can specify both a start and end value within the parentheses of the range() function, separated by a comma. For example, range(1,5) generates 1,2,3,4. Also, you can specify a start value, end value, and a step value to the range() function as a comma-separated list within its parentheses. For example, range(1,14,4) generates 1,5,9,13. 

 

You can specify the list’s name within the parentheses of Python’s enumerate() function to display each element’s index number and its associated value. 

 

When looping through multiple lists simultaneously, the element values of the same index number in each list can be displayed together by specifying the list names as a comma-separated list within the parentheses of Python’s zip() function. To ensure lists are of equal length, this can include a final strict=true argument. 

 

When looping through a dictionary you can display each key and its associated value using the dictionary items() method and specify two comma-separated variable names to the for keyword, one for the key name and the other for its value. 

 

The range() function can generate  a sequence that decreases, counting down, as well as those that count upward. The for loop in Python is unlike that in other languages, as it does not allow step size and end value to be specified. 

 

chars=[ 'A', 'B', 'C' ]

fruit=( 'Apple', 'Banana', 'Cherry' )

dict={ 'name': 'Mike', 'ref': 'Python', 'sys': 'Win' }




print( '\nElements:\t', end='')

for item in chars:

    print( item, end='')




print( '\nEnumerated:\t', end='')

for item in enumerate( chars ):

    print( item, end='' )




print( '\nZipped:\t', end='' )

for item in zip( chars, fruit, strict=True ):

       print( item, end='' )




print( '\nPaired:' )

for key, value in dict.items():

       print( key, '=', value )

 

In Python programming, anything that contains multiple items that can be looped over is called iterable.

 

Breaking Out of Loops

The Python break keyword can be used to prematurely terminate a loop when a specified condition is met. The break statement is situated inside the loop statement block and is preceded by a test expression. When the test returns True, the loop ends immediately and the program proceeds on to the next task. For example, in a nested inner loop it proceeds to the next iteration of the outer loop.

 

for i in range(1,4):

    for j in range(1,4):

        print( 'Running i=' , i , 'j=' , j )

 

Now, once you see how that runs, we will add a break statement to see how it will affect the previous code.

 

for i in range(1,4):

    for j in range(1,4):

        print( 'Running i=' , i , 'j=' , j )

        if i == 2 and j == 1:

                 print( 'Breaks inner loop at i=2 j=1' )

                 break 

 

The Python continue keyword can be used to skip a single iteration of a loop when a specified condition is met. The continue statement is situated inside the loop statement block and is preceded by a test expression. When the test returns true, that one iteration ends and the program proceeds to the next iteration. 

 

for i in range(1,4):

    for j in range(1,4):

        print( 'Running i=' , i , 'j=' , j )

        if i==1 and j==1:

                    print( 'Continue inner loop at i=1 and j=1' )

                    continue

        if i == 2 and j == 1:

                 print( 'Breaks inner loop at i=2 j=1' )

                 break

 

Here, the break statement halts all three iterations of the inner loop when the outer loop tries to run it the second time. The continue statement just skips the first iteration of the inner loop when the outer loop tries to run it for the first time.