0% found this document useful (0 votes)
4 views

WEEK 02 - Variables and Types Control Statements

This document serves as a tutorial on the fundamentals of Python programming, focusing on variables, data types, and control statements. It covers basic syntax, including print statements, indentation, data types (numeric and string), lists, and operators. Additionally, it provides exercises for practical application of the concepts discussed.
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
4 views

WEEK 02 - Variables and Types Control Statements

This document serves as a tutorial on the fundamentals of Python programming, focusing on variables, data types, and control statements. It covers basic syntax, including print statements, indentation, data types (numeric and string), lists, and operators. Additionally, it provides exercises for practical application of the concepts discussed.
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 16

Fundamentals of Data Science

WEEK 2: Variables / Types / Control Statements

Prepared by: Krishna Devkota

Hello, World!
Python is a very simple language, and has a very straightforward syntax. It encourages programmers to program without boilerplate (prepared) code. The
simplest directive in Python is the "print" directive - it simply prints out a line (and also includes a newline, unlike in C).

print()
To print a string in Python 3, just write:

In [1]: 1 print("This line will be printed.")

This line will be printed.

In [2]: 1 print(1)

Indentation
Python uses indentation for blocks, instead of curly braces.

Both tabs and spaces are supported, but the standard indentation requires standard Python code to use four spaces. For example:

In [3]: 1 x = 1
2 if x == 2:
3 # indented four spaces
4 print("x is 1.")

Keywords
In [4]: 1 import keyword
2 print(keyword.kwlist)
3 print (len(keyword.kwlist))

['False', 'None', 'True', '__peg_parser__', 'and', 'as', 'assert', 'async', 'await', 'break', 'class', 'continue', 'def', 'de
l', 'elif', 'else', 'except', 'finally', 'for', 'from', 'global', 'if', 'import', 'in', 'is', 'lambda', 'nonlocal', 'not', 'o
r', 'pass', 'raise', 'return', 'try', 'while', 'with', 'yield']
36

input()
In [5]: 1 my_val = int(input("Enter a number: ") )

Enter a number: 5

In [6]: 1 type(my_val)

Out[6]: int

In [7]: 1 print(my_val)

5
Variables and Types
In [8]: 1 student_marks = 25
2 ​
3 print(student_marks)
4 print("student_marks")

25
student_marks

Python is completely object oriented, and not "statically typed". You do not need to declare variables before using them, or declare their type. Every variable in
Python is an object.

This tutorial will go over a few basic types of variables.

Native Data types:

1. Numeric - Integers / Floating point / Complex Numbers / Boolean (True / False )


2. Non numeric - String

Numbers

Python supports two types of numbers - integers and floating point numbers. (It also supports complex numbers, which will not be explained in this tutorial).

To define an integer, use the following syntax:

In [9]: 1 myint = 7
2 print(myint)
3 print(type(myint))

7
<class 'int'>

In [10]: 1 x = int(5.0)
2 print(x)

To define a floating point number, you may use one of the following notations:

In [11]: 1 myfloat = 7.5


2 print(type(myfloat))
3 print(myfloat)

<class 'float'>
7.5

In [12]: 1 myfloat = float(5)


2 print(myfloat)

5.0

In [13]: 1 myvar = '7'


2 print(myvar)
3 type(myvar)

Out[13]: str

In [14]: 1 y = int(myvar)
2 type(y)

Out[14]: int

In [15]: 1 a = 4
2 b = 2
3 c = a/b
4 int(c)

Out[15]: 2
In [16]: 1 my_value = 5
2 print(my_value)

Constants

In [17]: 1 NUM = 5
2 NUM

Out[17]: 5

Variables in Python are defined using snake case, whereas constants are defined using the uppercase!

Examples of Cases:

camelCase
snake_case
UPPERCASE
lowercase
Title Case

Strings

In [18]: 1 mystring = 'hello'


2 print(mystring)

hello

In [19]: 1 mystring = "hello"


2 mystring

Out[19]: 'hello'

The difference between the two is that using double quotes makes it easy to include apostrophes (whereas these would terminate the string if using single
quotes)

In [20]: 1 mystring = "Don't worry about apostrophes!"


2 print(mystring)

Don't worry about apostrophes!

There are additional variations on defining strings that make it easier to include things such as carriage returns, backslashes and Unicode characters. These
will be covered later.

Simple operators can be executed on numbers and strings:

In [21]: 1 one = 1
2 two = 2
3 three = one + two
4 print(three)

In [22]: 1 a = "hello "


2 b = "world"
3 c = a + b
4 print(c)

hello world

Assignments can be done on more than one variable "simultaneously" on the same line like this

In [23]: 1 a, b, c = 3, 4, 7
2 print(a,b)
3 print(c)

3 4
7

Mixing operators between numbers and strings is not supported:


In [ ]: 1 # This will not work!
2 one = 1
3 two = 2
4 hello = "hello"
5 ​
6 print(one + two + hello)

Exercise
The target of this exercise is to create a string, an integer, and a floating point number. The string should be named mystring and should contain the word
"hello". The floating point number should be named myfloat and should contain the number 10.0, and the integer should be named myint and should
contain the number 20.

In [25]: 1 # change this code


2 mystring = None
3 myfloat = None
4 myint = None
5 ​
6 # testing code
7 if mystring == "hello":
8 print("String: %s" % mystring)
9 if isinstance(myfloat, float) and myfloat == 10.0:
10 print("Float: %f" % myfloat)
11 if isinstance(myint, int) and myint == 20:
12 print("Integer: %d" % myint)

Lists

Lists are very similar to arrays. They can contain any type of variable, and they can contain as many variables as you wish. Lists can also be iterated over in a
very simple manner. Here is an example of how to build a list.

In [26]: 1 mylist = [1,3,4,6,7,9,"hi","hello"]


2 print(mylist)

[1, 3, 4, 6, 7, 9, 'hi', 'hello']

Lists in Python have the following properties:

1. Ordered
2. Supports Heterogeneous values (although recommended to use where values are Homogeneous)
3. Iterable
4. Sequential
5. Size Mutable

Accessing Items in a List


In [27]: 1 print(mylist[0])
2 print(mylist[1])
3 print(mylist[2])
4 print(mylist[3])
5 print(mylist[4])
6 print(mylist[5])

1
3
4
6
7
9

In [28]: 1 value = mylist[1]


2 print(value)

Some useful list methods

Here are some of the mostly used list methods. The remaining methods will be discussed in details in the upcoming sessions.
In [29]: 1 new_list = [21,33,45,75,91,99]
2 print(new_list)

[21, 33, 45, 75, 91, 99]

append

In [30]: 1 new_list.append(101)
2 print(new_list)

[21, 33, 45, 75, 91, 99, 101]

insert

In [31]: 1 new_list.insert(1,107)
2 print(new_list)

[21, 107, 33, 45, 75, 91, 99, 101]

extend

In [32]: 1 new_list.extend([200,201,202])
2 print(new_list)

[21, 107, 33, 45, 75, 91, 99, 101, 200, 201, 202]

pop

In [33]: 1 removed_value = new_list.pop()


2 print(new_list)
3 print(removed_value)

[21, 107, 33, 45, 75, 91, 99, 101, 200, 201]
202

In [34]: 1 new_list.pop(1)
2 print(new_list)

[21, 33, 45, 75, 91, 99, 101, 200, 201]

remove

In [35]: 1 new_list.remove(101)
2 print(new_list)

[21, 33, 45, 75, 91, 99, 200, 201]

del

In [36]: 1 del mylist[1]

In [37]: 1 print(mylist)

[1, 4, 6, 7, 9, 'hi', 'hello']

Indexing and Slicing


In [38]: 1 new_list = [21,33,45,75,91,99]

Indexing

In [39]: 1 new_list[2]

Out[39]: 45
In [40]: 1 new_list[-1]

Out[40]: 99

Slicing

In [41]: 1 new_list[:3]

Out[41]: [21, 33, 45]

In [42]: 1 new_list[1:]

Out[42]: [33, 45, 75, 91, 99]

In [43]: 1 new_list[2:4]

Out[43]: [45, 75]

In [44]: 1 new_list[1:5:2] # slicing with a step size of two

Out[44]: [33, 75]

In [45]: 1 new_list[-3:] # specifying position from the last

Out[45]: [75, 91, 99]

In [46]: 1 new_list[::-1] # reverse the list

Out[46]: [99, 91, 75, 45, 33, 21]

Exercise

Exercise A

In this exercise, you will need to add numbers and strings to the correct lists using the "append" list method. You must add the numbers 1,2, and 3 to the
"numbers" list, and the words 'hello' and 'world' to the strings list.

You will also have to fill in the variable second_name with the second name in the names list, using the brackets operator [] Note that the index is zero-
based, so if you want to access the second item in the list, its index will be 1.

In [47]: 1 numbers = []
2 strings = []
3 names = ["John", "Eric", "Jessica"]
4 ​
5 # write your code here
6 second_name = None
7 ​
8 # this code should write out the filled arrays and the second name in the names list (Eric).
9 print(numbers)
10 print(strings)
11 print("The second name on the names list is %s" % second_name)

[]
[]
The second name on the names list is None

Exercise B

1. Take input from keyboard (first input - Name, second input- Roll number)
2. Create a list, add the name and roll number to the list
3. Print the resulting list

Basic Operators
Arithmetic Operators

Just as any other programming languages, the addition, subtraction, multiplication, and division operators can be used with numbers.

Try to predict what the answer will be. Does python follow order of operations?

In [48]: 1 number = (1 + 2) * 3 / 4.0 - 2


2 print(number)

0.25

Another operator available is the modulo (%) operator, which returns the integer remainder of the division. dividend % divisor = remainder .

In [49]: 1 remainder = 11 % 3
2 print(remainder)

Another equally useful operator is the floor division (//) operator, which returns an integer value of the resulting operation. Remember, it just truncates the value
after the decimal point.

In [50]: 1 x = 11//4
2 x

Out[50]: 2

Using two multiplication symbols makes a power relationship.

In [51]: 1 squared = 7 ** 2
2 cubed = 2 ** 3

In [52]: 1 print(squared)
2 print(cubed)

49
8

Using Operators with Strings


Python supports concatenating strings using the addition operator:

In [53]: 1 x = "hello " + "world"


2 print(x)

hello world

Python also supports multiplying strings to form a string with a repeating sequence:

In [54]: 1 lotsofhellos = "hello " * 10


2 print(lotsofhellos)

hello hello hello hello hello hello hello hello hello hello

Using Operators with Lists


Lists can be joined with the addition operators:

In [55]: 1 even_numbers = [2,4,6,8]


2 odd_numbers = [1,3,5,7]
3 all_numbers = odd_numbers + even_numbers
4 print(all_numbers)

[1, 3, 5, 7, 2, 4, 6, 8]

Just as in strings, Python supports forming new lists with a repeating sequence using the multiplication operator:
In [56]: 1 print([1,2,3] * 3)

[1, 2, 3, 1, 2, 3, 1, 2, 3]

Exercise
The target of this exercise is to create two lists called x_list and y_list , which contain 10 instances of the variables x and y , respectively. You are
also required to create a list called big_list , which contains the variables x and y , 10 times each, by concatenating the two lists you have created.

In [57]: 1 x = 7
2 y = 5
3 ​
4 # TODO: change this code
5 x_list = []
6 y_list = []
7 big_list = []
8 ​
9 print("x_list contains %d objects" % len(x_list))
10 print("y_list contains %d objects" % len(y_list))
11 print("big_list contains %d objects" % len(big_list))
12 ​
13 # testing code
14 if x_list.count(x) == 10 and y_list.count(y) == 10:
15 print("Almost there...")
16 if big_list.count(x) == 10 and big_list.count(y) == 10:
17 print("Great!")

x_list contains 0 objects


y_list contains 0 objects
big_list contains 0 objects

String Formatting
Python uses C-style string formatting to create new, formatted strings. The "%" operator is used to format a set of variables enclosed in a "tuple" (a fixed size
list), together with a format string, which contains normal text together with "argument specifiers", special symbols like "%s" and "%d".

Let's say you have a variable called "name" with your user name in it, and you would then like to print(out a greeting to that user.)

In [58]: 1 # This prints out "Hello, John!"


2 name = "John"
3 print("Hello, %s!" % name)

Hello, John!

In [59]: 1 # This prints out "Hello, John!"


2 score = 7.8886564567
3 name = input("Enter your name: ")
4 print("Hello, %s! Welcome to TBC! You scored %.3f" %(name,score))

Enter your name: Joe


Hello, Joe! Welcome to TBC! You scored 7.889

To use two or more argument specifiers, use a tuple (parentheses):

In [60]: 1 # This prints out "John is 23 years old."


2 name = "John"
3 age = 23
4 print("%s is %d years old." % (name, age))

John is 23 years old.

Any object which is not a string can be formatted using the %s operator as well. The string which returns from the "repr" method of that object is formatted as
the string. For example:

In [61]: 1 # This prints out: A list: [1, 2, 3]


2 mylist = [1,2,3]
3 print("A list: %s" % mylist)

A list: [1, 2, 3]
Here are some basic argument specifiers you should know:

%s - String (or any object with a string representation, like numbers)

%d - Integers

%f - Floating point numbers

%.<number of digits>f - Floating point numbers with a fixed amount of digits to the right of the dot.

%x/%X - Integers in hex representation (lowercase/uppercase)

f-string literals and the format method

In addition to C-style formatting, Python supports its own ways to format strings. A quick example is shown below. The details of these methods will be
discussed in the later sessions.

In [62]: 1 name = "Daniel"


2 college = "The British College"
3 classtime = 1100
4 ​
5 # Older C-style formatting
6 print("Hello %s. Welcome to %s. The class starts at %d hrs."%(name,college,classtime))
7 ​
8 # Using Python's format method
9 print("Hello {}. Welcome to {}. The class starts at {} hrs.".format(name,college,classtime))
10 ​
11 # Using Python's f-string literal
12 print(f"Hello {name}. Welcome to {college}. The class starts at {classtime} hrs.")

Hello Daniel. Welcome to The British College. The class starts at 1100 hrs.
Hello Daniel. Welcome to The British College. The class starts at 1100 hrs.
Hello Daniel. Welcome to The British College. The class starts at 1100 hrs.

Exercise
You will need to write a format string which prints out the data using the following syntax: Hello John Doe. Your current balance is $53.44.

Option A

In [63]: 1 data = ("John", "Doe", 53.44)


2 ​
3 format_string = "Hello %s %s.Your current balance is $%.2f."%data
4 print(format_string)

Hello John Doe.Your current balance is $53.44.

Option B

In [64]: 1 data = ("John", "Doe", 53.44)


2 format_string = f"Hello {data[0]} {data[1]}. Your current balance is ${data[2]}."
3 print(format_string)

Hello John Doe. Your current balance is $53.44.

Option C

In [65]: 1 data = ("John", "Doe", 53.44)


2 ​
3 format_string = "Hello {} {}. Your current balance is ${}.".format(*data)
4 print(format_string)

Hello John Doe. Your current balance is $53.44.

Basic String Operations


Strings are bits of text. They can be defined as anything between quotes:
In [66]: 1 astring = "Hello world!"

In [67]: 1 type(astring)

Out[67]: str

As you can see, the first thing you learned was printing a simple sentence. This sentence was stored by Python as a string. However, instead of immediately
printing strings out, we will explore the various things you can do to them. You can also use single quotes to assign a string. However, you will face problems if
the value to be assigned itself contains single quotes.For example to assign the string in these bracket(single quotes are ' ') you need to use double quotes
only like this

In [68]: 1 print(len(astring))

12

That prints out 12, because "Hello world!" is 12 characters long, including punctuation and spaces.

In [69]: 1 astring = "hello world!"


2 print(astring.index("o"))

That prints out 4, because the location of the first occurrence of the letter "o" is 4 characters away from the first character. Notice how there are actually two o's
in the phrase - this method only recognizes the first.

But why didn't it print out 5? Isn't "o" the fifth character in the string? To make things more simple, Python (and most other programming languages) start things
at 0 instead of 1. So the index of "o" is 4.

In [70]: 1 astring = "Hello world!"


2 print(astring.count("l"))

For those of you using silly fonts, that is a lowercase L, not a number one. This counts the number of l's in the string. Therefore, it should print 3.

In [71]: 1 mystr = "This NAME!"


2 mystr.swapcase()

Out[71]: 'tHIS name!'

In [72]: 1 mystr.lower()

Out[72]: 'this name!'

In [73]: 1 astring = "Hello world!"


2 print(astring)
3 print(astring[3:7])

Hello world!
lo w

This prints a slice of the string, starting at index 3, and ending at index 6. But why 6 and not 7? Again, most programming languages do this - it makes doing
math inside those brackets easier.

If you just have one number in the brackets, it will give you the single character at that index. If you leave out the first number but keep the colon, it will give
you a slice from the start to the number you left in. If you leave out the second number, if will give you a slice from the first number to the end.

You can even put negative numbers inside the brackets. They are an easy way of starting at the end of the string instead of the beginning. This way, -3 means
"3rd character from the end".

In [74]: 1 astring = "Hello world!"


2 print(astring[-3::2])

l!

This prints the characters of string from 3 to 7 skipping one character. This is extended slice syntax. The general form is [start:stop:step].

In [75]: 1 astring = "Hello world!"


2 print(astring[::-1])

!dlrow olleH

There is no function like strrev in C to reverse a string. But with the above mentioned type of slice syntax you can easily reverse a string like this.
In [76]: 1 astring = "Hello world!"
2 print(astring.upper())
3 print(astring.lower())

HELLO WORLD!
hello world!

These make a new string with all letters converted to uppercase and lowercase, respectively.

In [77]: 1 astring = "Hello world!"


2 print(astring.startswith("Hello"))
3 print(astring.endswith("asdfasdfasdf"))

True
False

This is used to determine whether the string starts with something or ends with something, respectively. The first one will print True, as the string starts with
"Hello". The second one will print False, as the string certainly does not end with "asdfasdfasdf".

In [78]: 1 astring = "Hello world!"


2 afewwords = astring.split(" ")
3 print(afewwords)

['Hello', 'world!']

This splits the string into a bunch of strings grouped together in a list. Since this example splits at a space, the first item in the list will be "Hello", and the
second will be "world!".

Conditions
Python uses boolean variables to evaluate conditions. The boolean values True and False are returned when an expression is compared or evaluated. For
example:

1 if condition:
2 do sth
3 elif condition2:
4 do sth else
5 else:
6 do sth

In [79]: 1 x = 2
2 print(x == 2) # prints out True
3 print(x == 3) # prints out False
4 print(x < 3) # prints out True

True
False
True

In [80]: 1 if (x==2):
2 print("Yay!")

Yay!

Notice that variable assignment is done using a single equals operator "=", whereas comparison between two variables is done using the double equals
operator "==". The "not equals" operator is marked as "!=".

In [81]: 1 (1 >= 3) and (4>2)

Out[81]: False

Boolean operators / logical operators


The "and" and "or" boolean operators allow building complex boolean expressions, for example:
In [82]: 1 name = "John"
2 age = 23
3 if name == "John" and age == 23:
4 print("Your name is John, and you are also 23 years old.")
5 ​
6 if name == "John" or name == "Rick":
7 print("Your name is either John or Rick.")

Your name is John, and you are also 23 years old.


Your name is either John or Rick.

The "in" operator


The "in" operator could be used to check if a specified object exists within an iterable object container, such as a list:

In [83]: 1 x = "abc"
2 x in "abcdef"

Out[83]: True

In [84]: 1 name = "John"


2 if name in ["John", "Rick"]:
3 print("Your name is either John or Rick.")

Your name is either John or Rick.

Python uses indentation to define code blocks, instead of brackets. The standard Python indentation is 4 spaces, although tabs and any other space size will
work, as long as it is consistent. Notice that code blocks do not need any termination.

Here is an example for using Python's "if" statement using code blocks:

1 if <statement is="" true="">:


2 <do something="">
3 ....
4 ....
5 elif <another statement="" is="" true="">: # else if
6 <do something="" else="">
7 ....
8 ....
9 else:
10 <do another="" thing="">
11 ....
12 ....
13 </do></do></another></do></statement>

For example:

In [85]: 1 x = 4*0.5
2 ​
3 if x == 2:
4 print("x equals two!")
5 else:
6 print("x does not equal to two.")

x equals two!

A statement is evaulated as true if one of the following is correct:

1. The "True" boolean variable is given, or calculated using an expression, such as an arithmetic comparison.
2. An object which is not considered "empty" is passed.

Here are some examples for objects which are considered as empty:

1. An empty string: ""


2. An empty list: []
3. The number zero: 0
4. The false boolean variable: False
In [86]: 1 odd_list = [1,2,3,4,5]
2 even_list =[]
3 ​
4 if odd_list:
5 print(odd_list)
6 if even_list:
7 print(even_list)

[1, 2, 3, 4, 5]

Ternary Operator
In [87]: 1 number_type = 'odd' if x%2!=0 else 'even'
2 print(number_type)

even

In [88]: 1 number_type = 'odd' if x%2==0 else 'even'


2 print(number_type)

odd

The 'is' operator


Unlike the double equals operator "==", the "is" operator does not match the values of the variables, but the instances themselves. For example:

In [89]: 1 x = [1,2,3]
2 y = [1,2,3]
3 print(x == y) # Prints out True
4 print(x is y) # Prints out False

True
False

In [90]: 1 num = [1,2,3,5,7]


2 num_copy = num.copy()

In [91]: 1 num_copy

Out[91]: [1, 2, 3, 5, 7]

In [92]: 1 num_copy.sort(reverse=True)
2 num_copy

Out[92]: [7, 5, 3, 2, 1]

In [93]: 1 num

Out[93]: [1, 2, 3, 5, 7]

In [94]: 1 num is num_copy

Out[94]: False

The "not" operator


Using "not" before a boolean expression inverts it:

In [95]: 1 print(not False) # Prints out True


2 print((not False) == (False)) # Prints out False

True
False

Exercise
Change the variables in the first section, so that each if statement resolves as True.
In [96]: 1 # change this code
2 number = 1
3 second_number = 5
4 first_array = []
5 second_array = []
6 ​
7 if number > 15:
8 print("1")
9 ​
10 if first_array:
11 print("2")
12 ​
13 if len(second_array) == 2:
14 print("3")
15 ​
16 if len(first_array) + len(second_array) == 5:
17 print("4")
18 ​
19 if first_array and first_array[0] == 1:
20 print("5")
21 ​
22 if not second_number:
23 print("6")

Loops
There are two types of loops in Python, for and while.

The "for" loop

For loops iterate over a given sequence. Here is an example:

In [97]: 1 primes = [2, 3, 5, 7, 9]


2 ​
3 for x in primes:
4 print(x)

2
3
5
7
9

In [98]: 1 for x in range(len(primes)):


2 print(primes[x])

2
3
5
7
9

For loops can iterate over a sequence of numbers using the "range" functions. Note that the range function is zero based.

In [99]: 1 # Prints out the numbers 0,1,2,3,4


2 for x in range(5):
3 print(x)

0
1
2
3
4

In [100]: 1 # Prints out 3,4,5


2 for x in range(3, 6):
3 print(x)

3
4
5
In [101]: 1 # Prints out 3,5,7
2 for x in range(3, 8, 2):
3 print(x)

3
5
7

"while" loops

While loops repeat as long as a certain boolean condition is met. For example:

In [102]: 1 # Prints out 0,1,2,3,4


2 ​
3 marks = [30,25,28,35,32]
4 count = 0
5 while count < len(marks):
6 print(count)
7 count += 1 # This is the same as count = count + 1

0
1
2
3
4

In [103]: 1 # Prints out the actual marks


2 marks = [30,25,28,35,32]
3 count = 0
4 while True:
5 if count >= len(marks):
6 break
7 print(marks[count])
8 count += 1 # This is the same as count = count + 1

30
25
28
35
32

"break" and "continue" statements

break is used to exit a for loop or a while loop, whereas continue is used to skip the current block, and return to the "for" or "while" statement. A few
examples:

In [104]: 1 # Prints out 0,1,2,3,4


2 ​
3 count = 0
4 while True:
5 if count >= 5:
6 break
7 print(count)
8 count += 1

0
1
2
3
4

In [105]: 1 marks = [50,55,70,"F",33]


2 for i in marks:
3 if i == "F":
4 break
5 print(i)

50
55
70
In [106]: 1 for x in range(10):
2 # Check if x is even
3 if x % 2 == 0:
4 continue
5 print(x)

1
3
5
7
9

In [107]: 1 for x in range(1,11):


2 # Check if x is even
3 if x % 2 == 0:
4 print("Even")
5 continue
6 print(x)
7

1
Even
3
Even
5
Even
7
Even
9
Even

can we use "else" clause for loops?

Unlike languages like C,CPP.. we can use else for loops. When the loop condition of "for" or "while" statement fails then code part in "else" is executed. If
break statement is executed inside for loop then the "else" part is skipped. Note that "else" part is executed even if there is a continue statement.

Here are a few examples:

In [108]: 1 count=0
2 while(count<5):
3 print(count)
4 count +=1
5 ​
6 else:
7 print("count value reached %d" %(count))

0
1
2
3
4
count value reached 5

In [109]: 1 for i in range(1, 10):


2 # print("input: ",i)
3 if(i%5==0):
4 break
5 print(i)
6 else:
7 print("this is not printed because for loop is terminated because of break but not due to fail in condition")

1
2
3
4

You might also like