Unit 3

Download as pdf or txt
Download as pdf or txt
You are on page 1of 27

3.

Boolean Values, Conditional


Execution, Loops, Lists and List
Processing, Logical and Bitwise
Operations.
By
M. Bhavani
M-Tech
UGC-NET qualified
Conditional/Relational Operators in Python
The comparison operators are used to compare values. The table below
illustrates how the comparison operators work, assuming that x = 0, y = 1, and z = 0:
LAB 6

Using one of the comparison operators in Python, write a simple


two-line program that takes the parameter n as input, which is an
integer, and prints False if n is less than 100, and True if n is
greater than or equal to 100.
Conditional Statements
● When you want to execute some code only if a certain condition is met,
you can use a conditional statement:
● a single if statement
if Condition: ● The if-elif-else statement
if Condition:
do_this_if_true
do_this_if_true

● an if-else statement elif Condition:

if Condition: do_this_if_true

do_this_if_true else:

else: do_this_if_false

do_this_if_false
LAB 7
1. Imagine that your computer program loves these plants. Whenever it
receives an input in the form of the word Rose, it involuntarily shouts to
the console the following string: "Rose is the best plant ever!"
2. Write a program that utilizes the concept of conditional execution, takes a
string as input, and:
a. prints the sentence "Yes - Rose is the best plant ever!" to the screen if
the inputted string is "Rose" (upper-case)
b. prints "No, I want a big Rose!" if the inputted string is "Rose"
(lower-case)
c. prints "Rose! Not [input]!" otherwise. Note: [input] is the string taken
as input.
3. Test your code using the data we've provided for you. And get yourself a
Rose, too!
LAB 8
● As you surely know, due to some astronomical reasons, years may be leap or
common. The former are 366 days long, while the latter are 365 days long.
● Since the introduction of the Gregorian calendar (in 1582), the following rule
is used to determine the kind of year:
● if the year number isn't divisible by four, it's a common year;
● otherwise, if the year number isn't divisible by 100, it's a leap year;
● otherwise, if the year number isn't divisible by 400, it's a common year;
● otherwise, it's a leap year.
● Look at the code in the editor – it only reads a year number, and needs to be
completed with the instructions implementing the test we've just described.
● The code should output one of two possible messages, which are Leap year
or Common year, depending on the value entered.
Solution for LAB 8
Loops in Python
1. There are two types of loops in Python: while and for:

● The while loop executes a statement or a set of statements as long as a


specified boolean condition is true.
Syntax of while loop ● if you want to execute more than one
statement inside one while loop, you
must (as with if) indent all the
instructions in the same way;
● an instruction or set of instructions
executed inside the while loop is called
the loop's body;
● if the condition is False (equal to zero) as
early as when it is tested for the first
time, the body is not executed even once
(note the analogy of not having to do
anything if there is nothing to do);
Continued

● the body should be able Infinite loop Using a counter variable to exit a loop
to change the condition's
value, because if the
condition is True at the
beginning, the body might
run continuously to
infinity – notice that Using a counter variable to exit a loop
doing a thing usually
decreases the number of
things to do).
Continued

● The for loop executes a set of statements many times; it's used to iterate
over a sequence (e.g., a list, a dictionary, a tuple, or a set – you will learn
about them soon) or other iterable objects (e.g., strings). You can use the
for loop to iterate over a sequence of numbers using the built-in range
function.
● the for keyword opens the for loop;
Syntax of for loop
note – there's no condition after it; you
don't have to think about conditions, as
they're checked internally, without any
intervention;
● any variable after the for keyword is the
control variable of the loop; it counts
the loop's turns, and does it
automatically;
Continued
● the in keyword introduces a syntax element describing the range of possible
values being assigned to the control variable;
● the range() function (this is a very special function) is responsible for generating
all the desired values of the control variable; in our example, the function will
create (we can even say that it will feed the loop with) subsequent values from
the following set: 0, 1, 2 .. 97, 98, 99; note: in this case, the range() function starts
its job from 0 and finishes it one step (one integer number) before the value of its
argument;
● note the pass keyword inside the loop body – it does nothing at all; it's an empty
instruction – we put it here because the for loop's syntax demands at least one
instruction inside the body (by the way – if, elif, else and while express the same
thing) Write a program to print 5 table using
● Example of for loop both for and while loop
The range() function

1. The range() function (this is a very special function) is responsible for


generating all the desired values in the given range
2. The range() function starts its job from 0 and finishes it one step (one integer
number) before the value of its argument;
3. The range() function may also accept three arguments
● The first argument passed to the range() function tells us what the
starting number of the sequence is (hence 2 in the output).
● The second argument tells the function where to stop the sequence (the
function generates numbers up to the number indicated by the second
argument, but does not include it).
● Finally, the third argument indicates the step, which actually means the
difference between each number in the sequence of numbers generated
by the function. (try range(0,6,2))
The break and continue statements

Both these words are keywords.

● break – exits the loop immediately, and unconditionally ends the loop's
operation; the program begins to execute the nearest instruction after
the loop's body;
● continue – behaves as if the program has suddenly reached the end of
the body; the next turn is started and the condition expression is tested
immediately.
● Execute the beside code that
shows the functionality of
break
● Replace break with continue
and see what happens
The else branch

The loop's else branch is always executed once, regardless of whether the loop
has entered its body or not.

Example
LAB 9
● Listen to this story: a boy and his father, a
computer programmer, are playing with
wooden blocks. They are building a pyramid.
● Their pyramid is a bit weird, as it is actually a
pyramid-shaped wall – it's flat. The pyramid is
stacked according to one simple principle: each
lower layer contains one block more than the
layer above.
● The figure illustrates the rule used by the
builders:

● Your task is to write a program which reads the number of blocks the builders
have, and outputs the height of the pyramid that can be built using these blocks.
● Note: the height is measured by the number of fully completed layers – if the
builders don't have a sufficient number of blocks and cannot complete the next
layer, they finish their work immediately.
Solution of LAB 9

Sample Input:

1000

Expected output:

The height of the pyramid: 44


Logic and bit operations in Python
1. Python supports the following logical operators:
a. and → if both operands are true, the condition is true, e.g., (True and
True) is True,
b. or → if any of the operands are true, the condition is true, e.g., (True
or False) is True,
c. not → returns false if the result is true, and returns true if the result
is false, e.g., not True is False.
2. You can use bitwise operators to manipulate single bits of data. The
following sample data:
a. x = 15, which is 0000 1111 in binary,
b. y = 16, which is 0001 0000 in binary.

will be used to illustrate the meaning of bitwise operators in


Python.
Continued

Analyze the examples below:

1. & does a bitwise and, e.g., x & y = 0, which is 0000 0000 in binary,
2. | does a bitwise or, e.g., x | y = 31, which is 0001 1111 in binary,
3. ˜ does a bitwise not, e.g., ˜ x = 240*, which is 1111 0000 in binary,
4. ^ does a bitwise xor, e.g., x ^ y = 31, which is 0001 1111 in binary,
5. >> does a bitwise right shift, e.g., y >> 1 = 8, which is 0000 1000 in binary,
6. << does a bitwise left shift, e.g., y << 3 = 128, which is 1000 0000 in
binary.
LAB 10
Write the code for leap year program defined in LAB 8 using logical operators
(single line condition)
Lists
● The list is a type of data in Python used to store multiple objects. It is an
ordered and mutable collection of comma-separated items between
square brackets

Eg: my_list = [1, None, True, "I am a string", 256, 0]

● Lists can be indexed and updated

Eg:
Continued
● Lists can be iterated through using the for loop,

Eg:

● The len() function may be used to check the list's length,


Eg:
LAB 11
Write a program using details mentioned below and this lets you practice
with the concept of lists. Your task is to:

● step 1: create an empty list named beatles;


● step 2: use the append() method to add the following members of the
band to the list: John Lennon, Paul McCartney, and George Harrison;
● step 3: use the for loop and the append() method to prompt the user to
add the following members of the band to the list: Stu Sutcliffe, and Pete
Best;
● step 4: use the del instruction to remove Stu Sutcliffe and Pete Best from
the list;
● step 5: use the insert() method to add Ringo Starr to the beginning of the
list.
Operations on Lists
1. You can use the sort() method to sort elements of a list Eg: lst.sort()
where lst is a list
2. There is also a list method called reverse(), which you can use to reverse
the list, Eg: lst.reverse()
3. If you have a list list_1, then the following assignment: list_2 = list_1 does
not make a copy of the list_1 list, but makes the variables list_1 and list_2
point to one and the same list in memory
4. If you want to copy a list or part of the list, you can do it by performing
slicing Eg: list_2= list_1[:]
5. You can use negative indices to perform slices, too.
Continued
6. The start and end parameters are optional when performing a slice:
list[start:end], e.g.:
Continued

7. You can delete slices using the del instruction Eg: del my_list[0:2]
8. You can test if some items exist in a list or not using the keywords in and
not in
Lists in Advance Applications
1. List comprehension allows you to create new lists from existing ones in a
concise and elegant way. The syntax of a list comprehension looks as
follows:

[expression for element in list if conditional]

which is actually an equivalent of the following code:

for element in list:

if conditional:

expression
Continued
2. You can use nested lists in Python to create matrices (i.e.,
two-dimensional lists). For example:

You might also like