Module 3 Boolean Values, Conditional Execution, Loops, Lists and List Processing, Logical and Bitwise Operations
Module 3 Boolean Values, Conditional Execution, Loops, Lists and List Processing, Logical and Bitwise Operations
Bitwise Operations
1. Comparison
Contoh :
a = 100
b = float(input("Enter a number"))
print(a<=b)
Hasii : Input = 55 -> False, Input 101-> True
2. If-else- statement
if the_weather_is_good: if the_weather_is_good:
go_for_a_walk() go_for_a_walk()
else: elif tickets_are_available:
go_to_a_theater() go_to_the_theater()
have_lunch()
elif table_is_available:
go_for_lunch()
else:
play_chess_at_home()
5. While
counter = 5
while counter != 0:
print("Inside the loop.",
counter)
counter -= 1
print("Outside the loop.",
counter)
6. For loop
step = 0
while angka != 1:
if angka % 2 == 0:
angka = angka / 2
else:
angka = 3*angka+1
print ("\n",angka)
step +=1
else :
print ("Steps = ", step)
numbers[0] = 111
print("New list content: ", numbers) # Current list content.
print("\nList length:", len(numbers))
del numbers[1]
print("\nNew List length:", len(numbers))
Hasil :
for i in range(5):
my_list.append(i + 1)
print(my_list)
Hasil :
[1, 2, 3, 4, 5]
for i in range(len(my_list)):
total += my_list[i]
print(total)
Hasil : 27
16. Swap
variable_1 = 1
variable_2 = 2
while swapped:
swapped = False # no swaps so far
for i in range(len(my_list) - 1):
if my_list[i] > my_list[i + 1]:
swapped = True # a swap occurred!
my_list[i], my_list[i + 1] = my_list[i +
1], my_list[i]
print(my_list)
Hasil : 2,4,6,8,10
19. Sort()
my_list = [8, 10, 6, 2, 4]
my_list.sort()
print(my_list)
20. Reverse()
lst = [5, 3, 1, 2, 4]
print(lst)
lst.reverse()
print(lst) # outputs: [4, 2, 1, 3, 5]
Key takeaways
1. The comparison (or the so-called relational) operators are used to compare values. The table
below illustrates how the comparison operators work, assuming that x = 0 , y = 1 , and z =
0:
x == y # False
x != y # True
x > y # False
True if the left operand's value is greater than the right y > z # True
>
operand's value, and False otherwise
x < y # True
True if the left operand's value is less than the right y < z # False
<
operand's value, and False otherwise
x >= y # False
x >= z # True
True if the left operand's value is greater than or equal to
≥ y >= z # True
the right operand's value, and False otherwise
x <= y # True
x <= z # True
True if the left operand's value is less than or equal to
≤ y <= z # False
the right operand's value, and False otherwise
2. When you want to execute some code only if a certain condition is met, you can use
a conditional statement:
x = 10
if x == 10: # condition
x = 10
else:
print("x is greater than or equal to 10") # Executed if the
condition is False.
x = 10
if x > 5: # True
print("x > 5")
if x > 8: # True
print("x > 8")
else:
print("else will be executed")
Each if is tested separately. The body of else is executed if the last if is False .
x = 10
if x == 10: # True
print("x == 10")
If the condition for if is False , the program checks the conditions of the subsequent elif blocks -
the first elif block that is True is executed. If all the conditions are False , the else block will
be executed.
x = 10
if x > 5: # True
if x == 6: # False
print("nested: x == 6")
elif x == 10: # True
print("nested: x == 10")
else:
print("nested: else")
else:
print("else")
Imagine that a loop's body needs to be executed exactly one hundred times. If you would like to
use the while loop to do it, it may look like this:
i = 0
# do_something()
i += 1
It would be nice if somebody could do this boring counting for you. Is that possible?
Of course it is - there's a special loop for these kinds of tasks, and it is named for .
Actually, the for loop is designed to do more complicated tasks - it can "browse" large
collections of data item by item. We'll show you how to do that soon, but right now we're
going to present a simpler variant of its application.
for i in range(100):
# do_something()
pass
There are some new elements. Let us tell you about them:
the for keyword opens the 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;
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)
Our next examples will be a bit more modest in the number of loop repetitions.
Take a look at the snippet below. Can you predict its output?
for i in range(10):
print("The value of i is currently", i)
Run the code to check if you were right.
Note:
the loop has been executed ten times (it's the range() function's argument)
the last control variable's value is 9 (not 10 , as it starts from 0 , not from 1 )
The range() function invocation may be equipped with two arguments, not just one:
In this case, the first argument determines the initial (first) value of the control variable.
The last argument shows the first value the control variable will not be assigned.
Note: the range() function accepts only integers as its arguments, and generates
sequences of integers.
Can you guess the output of the program? Run it to check if you were right now, too.
The first value shown is 2 (taken from the range() 's first argument.)
The last is 7 (although the range() 's second argument is 8 ).
Key takeaways
# Example 1
while True:
# Example 2
counter = 5
print(counter)
counter -= 1
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 objects that are iterable (e.g., strings). You can use the for loop to iterate over a
sequence of numbers using the built-in range function. Look at the examples below:
# Example 1
word = "Python"
print(letter, end="*")
# Example 2
if i % 2 == 0:
print(i)
2. You can use the break and continue statements to change the flow of a loop:
if letter == "P":
break
print(letter, end="")
You use continue to skip the current iteration, and continue with the next iteration,
e.g.:
text = "pyxpyxpyx"
if letter == "x":
continue
print(letter, end="")
3. The while and for loops can also have an else clause in Python. The else clause executes
after the loop finishes its execution as long as it has not been terminated by break , e.g.:
n = 0
while n != 3:
print(n)
n += 1
else:
print(n, "else")
print()
4. The range() function generates a sequence of numbers. It accepts integers and returns
range objects. The syntax of range() looks as follows: range(start, stop, step) , where:
start is an optional parameter specifying the starting number of the sequence (0 by
default)
stop is an optional parameter specifying the end of the sequence generated (it is not
included),
and step is an optional parameter specifying the difference between the numbers in
the sequence (1 by default.)
Example code:
for i in range(3):
print(i, end=" ") # Outputs: 0 1 2
Exercise 1
Create a for loop that counts from 0 to 10, and prints odd numbers to the screen. Use the
skeleton below:
Exercise 2
Create a while loop that counts from 0 to 10, and prints odd numbers to the screen. Use the
skeleton below:
x = 1
while x < 11:
if x % 2 != 0:
print(x)
x += 1
Exercise 3
Create a program with a for loop and a break statement. The program should iterate over
characters in an email address, exit the loop when it reaches the @ symbol, and print the part
before @ on one line. Use the skeleton below:
for ch in "[email protected]":
if ch == "@":
break
print(ch, end="")
Exercise 4
Create a program with a for loop and a continue statement. The program should iterate over
a string of digits, replace each 0 with x , and print the modified string to the screen. Use the
skeleton below:
Key takeaways
and → if both operands are true, the condition is true, e.g., (True and True) is True ,
or → if any of the operands are true, the condition is true, e.g., (True or
False) is True ,
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:
will be used to illustrate the meaning of bitwise operators in Python. Analyze the examples
below:
& does a bitwise and, e.g., x & y = 0 , which is 0000 0000 in binary,
| does a bitwise or, e.g., x | y = 31 , which is 0001 1111 in binary,
˜ does a bitwise not, e.g., ˜x = 240 *, which is 1111 0000 in binary,
^ does a bitwise xor, e.g., x ^ y = 31 , which is 0001 1111 in binary,
>> does a bitwise right shift, e.g., y >> 1 = 8 , which is 0000 1000 in binary,
<< does a bitwise left shift, e.g., y << 3 = , which is 1000 0000 in binary,
* -16 (decimal from signed 2's complement) -- read more about the Two's
complement operation.
x = 1
y = 0
x = 4
y = 1
a = x & y
b = x | y
c = ~x # tricky!
d = x ^ 5
e = x >> 2
f = x << 2
print(a, b, c, d, e, f)
Hasil : 0 5 -5 1 1 16
Key takeaways
1. 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, e.g.:
print(my_list[-1]) # outputs: 0
my_list[1] = '?'
my_list.insert(0, "first")
my_list.append("last")
print(my_list) # outputs: ['first', 1, '?', True, 'I am a string', 256,
0, 'last']
You will learn more about nesting in module 3.1.7 - for the time being, we just want you to be
aware that something like this is possible, too.
my_list = [1, 2, 3, 4]
del my_list[2]
Again, you will learn more about this in module 3.1.6 - don't worry. For the time being just try to
experiment with the above code and check how changing it affects the output.
print(color)
6. The len() function may be used to check the list's length, e.g.:
my_list = ["white", "purple", "blue", "yellow", "green"]
print(len(my_list)) # outputs 5
del my_list[2]
print(len(my_list)) # outputs 4