💻Introduction to Python

Python Variables

A variable is a named location used to store data in the memory. It is helpful to think of variables as a container that holds data that can be changed later in the program.

Creating Variables

Python has no command for declaring a variable.

A variable is created the moment you first assign a value to it.

1 number = 10
2 name = "John"

Here, we have created 2 variables named number and name . We have assigned the values 10 and John to the variables.

Variable Names

A variable can have a short name (like x and y) or a more descriptive name (age, carname, totalvolume). Rules for Python variables:

  • A variable name must start with a letter or the underscore character

  • A variable name cannot start with a number

  • A variable name can only contain alpha-numeric characters and underscores (A-z, 0-9, and )

  • Variable names are case-sensitive (age, Age and AGE are three different variables)

Example

Legal variable names:

1 myvar = "John"
2 my_var = "John"
3 _my_var = "John"
4 myVar = "John"
5 MYVAR = "John"
6 myvar2 = "John"

Example

Illegal variable names:

1 2myvar = "John"
2 my-var = "John"
3 my var = "John"

Multi Words Variable Names

Variable names with more than one word can be difficult to read.

There are several techniques you can use to make them more readable:

Camel Case

Each word, except the first, starts with a capital letter:

myVariableName = "John"

Pascal Case

Each word starts with a capital letter:

MyVariableName = "John"

Snake Case

Each word is separated by an underscore character:

my_variable_name = "John"

! The Style Guide for Python Code, also known as PEP 8, contains Naming Conventions that list suggested standards for names of different object types. PEP 8 includes the following recommendations:

  • Snake Case should be used for functions and variable names.

  • Pascal Case should be used for class names. (PEP 8 refers to this as the “CapWords” convention.)

Reserved Words (Keywords)

There is one more restriction on identifier names. The Python language reserves a small set of keywords that designate special language functionality. No object can have the same name as a reserved word.

In Python 3.6, there are 33 reserved keywords:

Changing the value of a variable

You can think of variables as a bag to store books in it and that book can be replaced at any time.

1 number = 10
2 number = 1.1

Initially, the value of number was 10 . Later, it was changed to 1.1 .

1 website = "apple.com"
2 print(website)
3
4 # assigning a new value to website
5 website = "pycoders.nl"
6
7 print(website)

In the above program, we have assigned apple.com to the website variable initially. Then, the value is changed to pycoders.nl .

1 apple.com
2 pycoders.nl

Assigning multiple values to multiple variables

Python allows you to assign values to multiple variables in one line:

1 a, b, c = 5, 3.2, "Hello"
2
3 print (a)
4 print (b)
5 print (c)
1 5
2 3.2
3 Hello

Note: Make sure the number of variables matches the number of values, or else you will get an error.

If we want to assign the same value to multiple variables at once, we can do this as:

1 x = y = z = "same"
2
3 print (x)
4 print (y)
5 print (z)

In the above program assigns the same string to all the three variables x , y and z .

1 same
2 same
3 same

Output Variables

The Python print statement is often used to output variables.

To combine both text and a variable, Python uses the + character:

1 x = "awesome"
2 print("Python is " + x)
Python is awesome

You can also use the + character to add a variable to another variable:

1 x = "Python is "
2 y = "awesome"
3 z = x + y
4 print(z)
Python is awesome

For numbers, the + character works as a mathematical operator:

1 x = 5
2 y = 10
3 print(x + y)
15

If you try to combine a string and a number, Python will give you an error:

1 x = 5
2 y = "John"
3 print(x + y)
TypeError: unsupported operand type(s) for +: 'int' and 'str'

Click the links below for some python variable exercises.

Exercise 1

Exercise 2

Click for further reading on python variables.

Data Types

In programming, data type is an important concept. Variables can store data of different types, and different types can do different things.

In any assignment, the assigned value must always be a valid data type.

Python has the following data types built-in by default, in these categories:

data type

description

bool

True or False values

int

an integer (1, 2, 3)

str

(string) a sequence of Unicode characters, e.g. "PyCoders" or "程序设计"

list

an ordered sequence of values of other data types, e.g. [1, 2, 3] or ["a", "b", "c"]

dict

a collection of key: values, e.g. { "first_name": "Py", "last_name": "Coders" }

Dynamic Typing

Python is highly flexible about reassigning variables to different types:

1 awesomeness = True
2 print(awesomeness) # True
3
4 awesomeness = "a dog"
5 print(awesomeness) # a dog
6
7 awesomeness = None
8 print(awesomeness) # None
9
10 awesomeness = 22 / 7
11 print(awesomeness) # 3.142857142857143

We call this dynamic typing, since variables can change types readily

Getting the Data Type

You can get the data type of any object by using the type() function:

1 x = 5
2 print(type(x))
<class 'int'>

Setting the Data Type

In Python, the data type is set when you assign a value to a variable:

Setting the Specific Data Type

If you want to specify the data type, you can use the following constructor functions:

Python Numbers and Type Conversion

Number Data Type in Python

Python supports integers, floating-point numbers and complex numbers. They are defined as int , float , and complex classes in Python.

Integers and floating points are separated by the presence or absence of a decimal point. For instance, 5 is an integer whereas 5.0 is a floating-point number.

Complex numbers are written in the form, x + yj , where x is the real part and y is the imaginary part.

1 a = 5
2
3 print(type(a))
4
5 print(type(5.0))
6
7 c = 5 + 3j
8 print(c + 3)

Type Conversion

We can convert one type of number into another. This is also known as coercion.

Operations like addition, subtraction coerce integer to float implicitly (automatically), if one of the operands is float.

We can see above that 1 (integer) is coerced into 1.0 (float) for addition and the result is also a floating point number.

1 + 2.0
3.0

We can also use built-in functions like int() , float() and complex() to convert between types explicitly. These functions can even convert from strings.

1 >>> int(2.3)
2 2
3 >>> int(-2.8)
4 -2
5 >>> float(5)
6 5.0
7 >>> complex('3+5j')
8 (3+5j)

When converting from float to integer, the number gets truncated (decimal parts are removed).

Strings

How to create a string in Python?

Strings can be created by enclosing characters inside a single quote or double-quotes. Even triple quotes can be used in Python but generally used to represent multiline strings and docstrings.

1 strings in Python
2 # all of the following are equivalent
3 my_string = 'Hello'
4 print(my_string)
5
6 my_string = "Hello"
7 print(my_string)
8
9 my_string = '''Hello'''
10 print(my_string)
11
12 # triple quotes string can extend multiple lines
13 my_string = """Hello, welcome to
14 the world of Python"""
15 print(my_string)

How to access characters in a string?

We can access individual characters using indexing and a range of characters using slicing. Index starts from 0. Trying to access a character out of index range will raise an IndexError . The index must be an integer. We can't use floats or other types, this will result into TypeError .

Python allows negative indexing for its sequences.

The index of -1 refers to the last item, -2 to the second last item and so on. We can access a range of items in a string by using the slicing operator : (colon).

1 in Python
2 str = 'PyCoders'
3 print('str = ', str)
4
5 #first character
6 print('str[0] = ', str[0])
7
8 #last character
9 print('str[-1] = ', str[-1])
10
11 #slicing 2nd to 5th character
12 print('str[1:5] = ', str[1:5])
13
14 #slicing 6th to 2nd last character
15 print('str[5:-2] = ', str[5:-2])

If we try to access an index out of the range or use numbers other than an integer, we will get errors.

1 # index must be in range
2 >>> my_string[15]
3 ...
4 IndexError: string index out of range
5
6 # index must be an integer
7 >>> my_string[1.5]
8 ...
9 TypeError: string indices must be integers

String Length

To get the length of a string, use the len() function.

1 a = "Hello, World!"
2 print(len(a))

How to change or delete a string?

Strings are immutable. This means that elements of a string cannot be changed once they have been assigned. We can simply reassign different strings to the same name.

1 >>> my_string = 'PyCoders'
2 >>> my_string[5] = 'a'
3 ...
4 TypeError: 'str' object does not support item assignment
5 >>> my_string = 'Python'
6 >>> my_string
7 'Python'

We cannot delete or remove characters from a string. But deleting the string entirely is possible using the del keyword.

1 >>> del my_string[1]
2 ...
3 TypeError: 'str' object doesn't support item deletion
4 >>> del my_string
5 >>> my_string
6 ...
7 NameError: name 'my_string' is not defined

Concatenation of Two or More Strings

Joining of two or more strings into a single one is called concatenation.

The + operator does this in Python. Simply writing two string literals together also concatenates them.

The * operator can be used to repeat the string for a given number of times.

1 # Python String Operations
2 str1 = 'Hello'
3 str2 ='World!'
4
5 # using +
6 print('str1 + str2 = ', str1 + str2)
7
8 # using *
9 print('str1 * 3 =', str1 * 3)

String Membership Test

We can test if a substring exists within a string or not, using the keyword in .

1 >>> 'a' in 'program'
2 True
3 >>> 'at' not in 'battle'
4 False

Python String Formatting

Escape Sequence

If we want to print a text like He said, "What's there?", we can neither use single quotes nor double quotes. This will result in a SyntaxError as the text itself contains both single and double quotes

1 >>> print("He said, "What's there?"")
2 ...
3 SyntaxError: invalid syntax
4 >>> print('He said, "What's there?"')
5 ...
6 SyntaxError: invalid syntax

One way to get around this problem is to use triple quotes. Alternatively, we can use escape sequences.

An escape sequence starts with a backslash and is interpreted differently. If we use a single quote to represent a string, all the single quotes inside the string must be escaped. Similar is the case with double quotes. Here is how it can be done to represent the above text.

1 using triple quotes
2 print('''He said, "What's there?"''')
3
4 # escaping single quotes
5 print('He said, "What\'s there?"')
6
7 # escaping double quotes
8 print("He said, \"What's there?\"")

Here is a list of all the escape sequences supported by Python.

Example

1 escape sequence
2 print("I will go\tHome")
3
4 # A string with a unrecognized escape sequence
5 print("See you\jtommorow")
6

As seen in the above output, the first print statement produced an output where the \t got resolved into a vertical tab and is omitted in the output. On the other hand, in the second print statement, the \j persists, as no legal resolution for that sequence exists.

Raw String to ignore escape sequence

Method 1:

Consistently doubling the backslashes, also allows us to overcome such issues. In this method, we manually find every single backslash in the string and concatenate another backslash to it (at its immediate position). Generally, a tedious method, and only advised if the string size is less

1 # sample string
2 s = "I love to use \t instead of using 4 spaces"
3
4 # normal output
5 print(s)
6
7 # doubling lone backslashes
8 s = "I love to use \\t instead of using 4 spaces"
9
10 # output after doubling
11 print(s)

Method 2:

Sometimes we may wish to ignore the escape sequences inside a string. To do this we can place r or R in front of the string. This will imply that it is a raw string and any escape sequence inside it will be ignored.

s = "C:\Program 1 Files\norton\appx"
2
3 # normal output
4 print(s)
5
6 # changing the string into a raw string
7 s = r"C:\Program Files\norton\appx"
8
9 # Outputting the raw versio of the string
10 print(s)

The format() Method for Formatting Strings

str.format()

The format() method that is available with the string object is very versatile and powerful in formatting strings. Format strings contain curly braces {} as placeholders or replacement fields which get replaced. We can use positional arguments or keyword arguments to specify the order.

# Python string 1 format() method
2
3 # default(implicit) order
4 default_order = "{}, {} and {}".format('John','Bill','Sean')
5 print('\n--- Default Order ---')
6 print(default_order)
7
8 # order using positional argument
9 positional_order = "{1}, {0} and {2}".format('John','Bill','Sean')
10 print('\n--- Positional Order ---')
11 print(positional_order)
12
13 # order using keyword argument
14 keyword_order = "{s}, {b} and {j}".format(j='John',b='Bill',s='Sean')
15 print('\n--- Keyword Order ---')
16 print(keyword_order)

Another Example

1 quantity = 3
2 itemno = 567
3 price = 49.95
4 myorder = "I want {} pieces of item {} for {} dollars."
5 print(myorder.format(quantity, itemno, price))

f-Strings

The syntax is similar to the one you used with str.format() but less verbose. Look at how easily readable this is:

1 name = "Eric"
2 age = 74
3 print(f"Hello, {name}. You are {age}.")

You can have multiline strings:

1 name = "Eric"
2 profession = "comedian"
3 affiliation = "Monty Python"
4 message = (
5 f"Hi {name}. "
6 f"You are a {profession}. "
7 f"You were in {affiliation}."
8 )
9 print(message)

But remember that you need to place an f in front of each line of a multiline string.

Common Python String Methods

There are numerous methods available with the string object. The format() method that we mentioned above is one of them. Some of the commonly used methods are lower() , upper() , join() , split() , find() , replace() etc.

Here is a complete list of all the built-in methods to work with strings in Python.

1 "PyCoders".lower()
2 'pycoders'
3 >>> "PyCoders".upper()
4 'PYCODERS'
5 >>> "This will split all words into a list".split()
6 ['This', 'will', 'split', 'all', 'words', 'into', 'a', 'list']
7 >>> ' '.join(['This', 'will', 'join', 'all', 'words', 'into', 'a', 'string'])
8 'This will join all words into a string'
9 >>> 'Happy New Year'.find('ew')
10 7
11 >>> 'Happy New Year'.replace('Happy','Brilliant')
12 'Brilliant New Year'

The print() function prints the given object to the standard output device (screen) or to the text stream file.

Syntax

print(*objects, sep=' ', end='\n', file=sys.stdout, flush=False)

1 a = 5
2 print("a =", a, sep='00000', end='\n\n\n')
3 print("a =", a, sep='0', end='')

Click for further reading on print function

Input Function

The input() method reads a line from input, converts into a string and returns it.

The syntax of input() method is:

input([prompt])

The input() method takes a single optional argument:

  • prompt (Optional) - a string that is written to standard output (usually screen) without trailing newline

x = input('1 Enter your name:')
2 print('Hello, ' + x)

Boolean Values

In programming you often need to know if an expression is True or False .

You can evaluate any expression in Python, and get one of two answers, True or False .

When you compare two values, the expression is evaluated and Python returns the Boolean answer:

1 print(10 > 9)
2 print(10 == 9)
3 print(10 < 9)

Evaluate Values and Variables

The bool() function allows you to evaluate any value, and give you True or False in return,

1 print(bool("Hello"))
2 print(bool(15))
1 x = "Hello"
2 y = 15
3
4 print(bool(x))
5 print(bool(y))

In fact, there are not many values that evaluates to False , except empty values, such as () , [] , {} , "" , the number 0 , and the value None . And of course the value False evaluates to False .

Python Operators

Comparison Operators

Comparison operators are used to compare values. It returns either True or False according to the condition.

1 x = 10
2 y = 12
3
4 # Output: x > y is False
5 print('x > y is',x>y)
6
7 # Output: x < y is True
8 print('x < y is',x<y)
9
10 # Output: x == y is False
11 print('x == y is',x==y)
12
13 # Output: x != y is True
14 print('x != y is',x!=y)
15
16 # Output: x >= y is False
17 print('x >= y is',x>=y)
18
19 # Output: x <= y is True
20 print('x <= y is',x<=y)

Arithmetic operators

Arithmetic operators are used to perform mathematical operations like addition, subtraction, multiplication, etc.

1 x = 15
2 y = 4
3
4 # Output: x + y = 19
5 print('x + y =',x+y)
6
7 # Output: x - y = 11
8 print('x - y =',x-y)
9
10 # Output: x * y = 60
11 print('x * y =',x*y)
12
13 # Output: x / y = 3.75
14 print('x / y =',x/y)
15
16 # Output: x // y = 3
17 print('x // y =',x//y)
18
19 # Output: x ** y = 50625
20 print('x ** y =',x**y)

Assignment operators

Assignment operators are used in Python to assign values to variables.

a = 5 is a simple assignment operator that assigns the value 5 on the right to the variable a on the left.

There are various compound operators in Python like a += 5 that adds to the variable and later assigns the same. It is equivalent to a = a + 5 .

Logical operators

1 x = True
2 y = False
3
4 print('x and y is',x and y)
5
6 print('x or y is',x or y)
7
8 print('not x is',not x)

Identity operators

is and is not are the identity operators in Python. They are used to check if two values (or variables) are located on the same part of the memory. Two variables that are equal does not imply that they are identical

1 x1 = 5
2 y1 = 5
3 x2 = 'Hello'
4 y2 = 'Hello'
5 x3 = [1,2,3]
6 y3 = [1,2,3]
7
8 # Output: False
9 print(x1 is not y1)
10
11 # Output: True
12 print(x2 is y2)
13
14 # Output: False
15 print(x3 is y3)

is vs. "=="

In python, "==" and "is" are very similar comparators, however they are not the same

1 a = 1
2 a == 1 # True
3 a is 1 # True

"is" is only true if the variables reference the same item in memory

a = [1, 2, 3] # 1 a list of numbers
2 b = [1, 2, 3]
3 a == b # True
4 a is b # False
1 c = b
2 b is c # True

Membership operators

Membership operators are used to test if a sequence is presented in an object:

1 x = 'Hello world'
2 y = {1:'a',2:'b'}
3
4 # Output: True
5 print('H' in x)
6
7 # Output: True
8 print('hello' not in x)
9
10 # Output: True
11 print(1 in y)
12
13 # Output: False
14 print('a' in y)

Here, 'H' is in x but 'hello' is not present in x (remember, Python is case sensitive). Similarly, 1 is key and 'a' is the value in dictionary y. Hence, 'a' in y returns False .

Bitwise operators

Bitwise operators act on operands as if they were strings of binary digits. They operate bit by bit, hence the name.

For example, 2 is 10 in binary and 7 is 111 .

In the table below: Let x = 10 ( 0000 1010 in binary) and y = 4 ( 0000 0100 in binary)

Python If ... Else

Decision making is required when we want to execute a code only if a certain condition is satisfied.

The if…elif…else statement is used in Python for decision making.

1 if test expression:

2 statement(s)

Here, the program evaluates the test expression and will execute statement(s) only if the test expression is True .

If the test expression is False , the statement(s) is not executed.

In Python, the body of the if statement is indicated by the indentation. The body starts with an indentation and the first unindented line marks the end.

Python interprets non-zero values as True . None and 0 are interpreted as False .

# If the number is positive, we print an 1 appropriate message
2
3 num = 3
4 if num > 0:
5 print(num, "is a positive number.")
6 print("This is always printed.")
7
8 num = -1
9 if num > 0:
10 print(num, "is a positive number.")
11 print("This is also always printed.")

In the above example, num > 0 is the test expression.

The body of if is executed only if this evaluates to True .

When the variable num is equal to 3, test expression is true and statements inside the body of if are executed.

If the variable num is equal to -1, test expression is false and statements inside the body of if are skipped.

The print() statement falls outside of the if block (unindented). Hence, it is executed regardless of the test expression.

1 if test expression:
2 Body of if
3 else:
4 Body of else

The if..else statement evaluates test expression and will execute the body of if only when the test condition is True .

If the condition is False , the body of else is executed. Indentation is used to separate the blocks.

# Program checks if the number is positive 1 or negative
2 # And displays an appropriate message
3
4 num = 3
5
6 # Try these two variations as well.
7 # num = -5
8 # num = 0
9
10 if num >= 0:
11 print("Positive or Zero")
12 else:
13 print("Negative number")

In the above example, when num is equal to 3, the test expression is true and the body of if is executed and the body of else is skipped.

If num is equal to -5, the test expression is false and the body of else is executed and the body of if is skipped.

If num is equal to 0, the test expression is true and body of if is executed and body of else is skipped.

1 if test expression:
2     Body of if
3 elif test expression:
4     Body of elif
5 else:
6     Body of else

The elif is short for else if. It allows us to check for multiple expressions.

If the condition for if is False , it checks the condition of the next elif block and so on.

If all the conditions are False , the body of else is executed. Only one block among the several if...elif...else blocks is executed according to the condition.

The if block can have only one else block. But it can have multiple elif blocks.

1 num = 3.4
2
3 # Try these two variations as well:
4 # num = 0
5 # num = -4.5
6
7 if num > 0:
8 print("Positive number")
9 elif num == 0:
10 print("Zero")
11 else:
12 print("Negative number")

When variable num is positive, Positive number is printed.

If num is equal to 0, Zero is printed.

If num is negative, Negative number is printed.

We can have a if...elif...else statement inside another if...elif...else statement. This is called nesting in computer programming.

Any number of these statements can be nested inside one another. Indentation is the only way to figure out the level of nesting. They can get confusing, so they must be avoided unless necessary

'''In this program, 1 we input a number
2 check if the number is positive or
3 negative or zero and display
4 an appropriate message
5 This time we use nested if statement'''
6 num = float(input("Enter a number: "))
7 if num >= 0:
8 if num == 0:
9 print("Zero")
10 else:
11 print("Positive number")
12 else:
13 print("Negative number")

Loop and Iterations

Loops are used in programming to repeat a specific block of code. In this article, you will learn to create a while loop in Python.

While Loops

The while loop in Python is used to iterate over a block of code as long as the test expression (condition) is true.

We generally use this loop when we don't know the number of times to iterate beforehand.

while  test_expression:
      Body of while

In the while loop, test expression is checked first. The body of the loop is entered only if the test_expression evaluates to True . After one iteration, the test expression is checked again.

This process continues until the test_expression evaluates to False . In Python, the body of the while loop is determined through indentation.

The body starts with indentation and the first unindented line marks the end.

Python interprets any non-zero value as True . None and 0 are interpreted as False .

# Program 1 to add natural
2 # numbers up to
3 # sum = 1+2+3+...+n
4
5 # To take input from the user,
6 # n = int(input("Enter n: "))
7
8 n = 10
9
10 # initialize sum and counter
11 sum = 0
12 i = 1
13
14 while i <= n:
15     sum = sum + i
16     i = i+1 # update counter
17
18 # print the sum
19 print("The sum is", sum)

In the above program, the test expression will be True as long as our counter variable i is less than or equal to n (10 in our program).

We need to increase the value of the counter variable in the body of the loop. This is very important (and mostly forgotten). Failing to do so will result in an infinite loop (never-ending loop).

Finally, the result is displayed.

While loop with else

The else part is executed if the condition in the while loop evaluates to False .

1 counter = 0
2
3 while counter < 3:
4     print("Inside loop")
5     counter = counter + 1
6 else:
7     print("Inside else")

Here, we use a counter variable to print the string Inside loop three times.

On the fourth iteration, the condition in while becomes False . Hence, the else part is executed.

For Loops

The for loop in Python is used to iterate over a sequence (list, tuple, string) or other iterable objects. Iterating over a sequence is called traversal

1 for val in sequence:
2     Body of for

Here, val is the variable that takes the value of the item inside the sequence on each iteration.

Loop continues until we reach the last item in the sequence. The body of for loop is separated from the rest of the code using indentation.

1 for x in "banana":
2     print(x)

for loop with else

A for loop can have an optional else block as well. The else part is executed if the items in the sequence used in for loop exhausts.

The break keyword can be used to stop a for loop. In such cases, the else part is ignored.

Hence, a for loop's else part runs if no break occurs.

Here is an example to illustrate this.

1 digits = [0, 1, 5]
2
3 for i in digits:
4     print(i)
5 else:
6     print("No items left.")

Here, the for loop prints items of the list until the loop exhausts. When the for loop exhausts, it executes the block of code in the else and prints No items left.

Nested for Loops

A nested loop is a loop inside a loop.

The "inner loop" will be executed one time for each iteration of the "outer loop":

adj = ["red",  "big", "tasty"]
2 fruits = ["apple", "banana", "cherry"]
3
4 for x in adj:
5     for y in fruits:
6         print(x, y)

The range() function

We can generate a sequence of numbers using range() function. range(10) will generate numbers from 0 to 9 (10 numbers).

We can also define the start, stop and step size as range(start, stop,step_size) . step_size defaults to 1 if not provided.

To force this function to output all the items, we can use the function list() .

The following example will clarify this.

1 print(range(10))
2
3 print(list(range(10)))
4
5 print(list(range(2, 8)))
6
7 print(list(range(2, 20, 3)))

We can use the range() function in for loops to iterate through a sequence of numbers. It can be combined with the len() function to iterate through a sequence using indexing. Here is an example.

1 # Program to iterate through a list using indexing
2
3 genre = ['pop', 'rock', 'jazz']
4
5 # iterate over the list using index
6 for i in range(len(genre)):
7     print("I like", genre[i])

Python break and continue

In Python, break and continue statements can alter the flow of a normal loop.

Loops iterate over a block of code until the test expression is false, but sometimes we wish to terminate the current iteration or even the whole loop without checking test expression.

The break and continue statements are used in these cases.

Python break statement

The break statement terminates the loop containing it. Control of the program flows to the statement immediately after the body of the loop.

If the break statement is inside a nested loop (loop inside another loop), the break statement will terminate the innermost loop.

1 for val in "string":
2     if val == "i":
3         break
4     print(val)
5
6 print("The end")

In this program, we iterate through the "string" sequence. We check if the letter is i, upon which we break from the loop. Hence, we see in our output that all the letters up till i gets printed. After that, the loop terminates.

Python continue statement

The continue statement is used to skip the rest of the code inside a loop for the current iteration only. Loop does not terminate but continues on with the next iteration.

1 for val in "string":
2     if val == "i":
3         continue
4     print(val)
5
6 print("The end")

This program is same as the above example except the break statement has been replaced with continue .

We continue with the loop, if the string is i, not executing the rest of the block. Hence, we see in our output that all the letters except i gets printed.

Python pass statement

In Python programming, the pass statement is a null statement. The difference between a comment and a pass statement in Python is that while the interpreter ignores a comment entirely, pass is not ignored.

However, nothing happens when the pass is executed. It results in no operation (NOP).

Suppose we have a loop or a function that is not implemented yet, but we want to implement it in the future. They cannot have an empty body. The interpreter would give an error. So, we use the pass statement to construct a body that does nothing.

1 sequence = {'p', 'a', 's', 's'}
2 for val in sequence:
3     pass

END OF THE LECTURE

Last updated

Change request #338: