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

Module 3 Boolean Values, Conditional Execution, Loops, Lists and List Processing, Logical and Bitwise Operations

Uploaded by

karbela shop
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
355 views

Module 3 Boolean Values, Conditional Execution, Loops, Lists and List Processing, Logical and Bitwise Operations

Uploaded by

karbela shop
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 19

Boolean Values, Conditional Execution, Loops, Lists and List Processing, Logical and

Bitwise Operations

1. Comparison

=  is an assignment operator, e.g.,  a = b  assigns  a  with the value of  b ;


==  is the question are these values equal?;  a == b  compares  a  and  b .

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()

3. Pseudocode and Introduction to loops word = "Aku"


Test Data
plants = input("What's the best
Test Data plant ")

Sample input:  spathiphyllum if plants == "Aku":


Expected output:  No, I want a
big Spathiphyllum! print("Yes - Spathiphyllum
Sample input:  pelargonium is the best plant ever")
Expected output:  Spathiphyllum!
exit()
Not pelargonium!
Sample input: Spathiphyllum
elif plants == "aku":
Expected output:  Yes -
Spathiphyllum is the best
print("No, I want a big
plant ever!
Spathiphyllum!")
4. Looping code with while
# Store the current largest number here.
largest_number = -999999999
# Input the first value.
number = int(input("Enter a number or type -1
to stop: "))
# If the number is not equal to -1, continue.
while number != -1:
# Is number larger than largest_number?
if number > largest_number:
# Yes, update largest_number.
largest_number = number
# Input the next number.
number = int(input("Enter a number or type
-1 to stop: "))

# Print the largest number.

print("The largest number is:", largest_number)

5. While

counter = 5
while counter != 0:
print("Inside the loop.",
counter)
counter -= 1
print("Outside the loop.",
counter)

6. For loop

for i in range(2, 5):


print("The value of i is
currently", i)
Hasil :
The value of i is currently 2
The value of i is currently 3
The value of i is currently 4

7. The break dan continue statement

print("The break instruction:") print("\nThe continue


for i in range(1, 6): instruction:")
if i == 3: for i in range(1, 6):
break if i == 3:
print("Inside the loop.", i) continue
print("Outside the loop.") print("Inside the loop.", i)
print("Outside the loop.")
Hasil :
The break instruction: Hasil :
Inside the loop. 1 The continue instruction:
Inside the loop. 2 Inside the loop. 1
Outside the loop. Inside the loop. 2
Inside the loop. 4
Inside the loop. 5
largest_number = -99999999 largest_number = -99999999
counter = 0 counter = 0
while True: number = int(input("Enter a number
number = int(input("Enter a number or type -1 to end program: "))
or type -1 to end program: "))
if number == -1: while number != -1:
break if number == -1:
counter += 1 continue
if number > largest_number: counter += 1
largest_number = number
if number > largest_number:
if counter != 0: largest_number = number
print("The largest number is", number = int(input("Enter a
largest_number) number or type -1 to end program:
else: "))
print("You haven't entered any
number.") if counter:
print("The largest number is",
Hasil : largest_number)
Enter a number or type -1 to end else:
program: 6 print("You haven't entered any
Enter a number or type -1 to end number.")
program: -1 Hasil :
Enter a number or type -1 to end
program: 6
Enter a number or type -1 to end
program: -1
The largest number is 6

word = "chupacabra" user_word = input("Input word ")


user_word = user_word.upper()
while True: for letter in user_word:
secret = input("enter secret if (letter == "A" or letter
word") =="I" or letter == "U" or letter
if (secret == word): == "E" or letter == "O"):
print("You've successfully continue
left the loop") print(letter)
break Hasil :
Input word gregory
Hasil : enter secret wordkkkll G
enter secret wordchupacabra R
You've successfully left the loop G
R
Y
8. The while loop and else branch
Scenario
1. take any non-negative and non-zero integer number and name it  c0 ;
2. if it's even, evaluate a new  c0  as  c0 ÷ 2 ;
3. otherwise, if it's odd, evaluate a new  c0  as  3 × c0 + 1 ;
4. if  c0 ≠ 1 , skip to point 2.

angka = int(input("entry number "))

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)

Hasil : Sample input = 16


8
4
2
1
steps = 4

9. The for loop and else branch


10. Bitwise operator

&  (ampersand) - bitwise conjunction;


|  (bar) - bitwise disjunction;
~  (tilde) - bitwise negation;
^  (caret) - bitwise exclusive or (xor).
11. Indexing List
numbers = [10, 5, 7, 2, 1]
print("Original list content:", numbers) # Printing original
list content.

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 :

List content: [10, 5, 7, 2, 1]


New list content: [111, 5, 7, 2, 1]
List length : 5
New list length : 4
12. Negative indices
a. The last one in the list
Print (numbers[-1])
b. The one before last list
Print (numbers[-2])
numbers = [111, 7, 2, 1]
print(numbers[-1])
print(numbers[-2])
Hasil :
1
2

13. Adding element to list with append()and insert()


list.append(value)= menambahkan di list terakhir
list.insert(0,5)= menambahkan di index ke o nilainya 5

14. Adding elements to a list


my_list = [] # Creating an empty list.

for i in range(5):
my_list.append(i + 1)

print(my_list)
Hasil :
[1, 2, 3, 4, 5]

15. Making use of list


my_list = [10, 1, 8, 3, 5]
total = 0

for i in range(len(my_list)):
total += my_list[i]
print(total)
Hasil : 27

16. Swap
variable_1 = 1
variable_2 = 2

variable_1, variable_2 = variable_2, variable_1

Bitwise operations ( & ,  | , and  ^ )


A ^
Argument  A Argument  B A & B A | B
B
0 0 0 0 0
0 1 0 1 1
1 0 0 1 1
1 1 1 1 0

17. Binary left shift and Binary right shift


Value >> bits
Menggeser ke kanan berarti membagi 2
Value << bits
Menggeser ke kiri berarti mengalikan dengan 2
var = 17
var_right = var >> 1
var_left = var << 2
print(var, var_right, var_left)
Hasil
17,8,68

18. Buble sort


my_list = [8, 10, 6, 2, 4] # list to sort
swapped = True # It's a little fake, we need it to
enter the while loop.

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:

Operator Description Example

x == y # False

returns if operands' values are equal, x == z # True


==
and  False  otherwise

x != y # True

returns  True  if operands' values are not equal, x != z # False


!=
and  False  otherwise

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:

 a single  if  statement, e.g.:

x = 10

if x == 10: # condition

print("x is equal to 10") # Executed if the condition is True.

 a series of  if  statements, e.g.:

x = 10

if x > 5: # condition one

print("x is greater than 5") # Executed if condition one is


True.

if x < 10: # condition two

print("x is less than 10") # Executed if condition two is True.

if x == 10: # condition three

print("x is equal to 10") # Executed if condition three is


True.

Each  if  statement is tested separately.

 an  if-else  statement, e.g.:


x = 10

if x < 10: # Condition


print("x is less than 10") # Executed if the condition is True.

else:
print("x is greater than or equal to 10") # Executed if the
condition is False.

 a series of  if  statements followed by an  else , e.g.:

x = 10

if x > 5: # True
print("x > 5")

if x > 8: # True
print("x > 8")

if x > 10: # False


print("x > 10")

else:
print("else will be executed")

Each  if  is tested separately. The body of  else  is executed if the last  if  is  False .

 The  if-elif-else  statement, e.g.:

x = 10

if x == 10: # True
print("x == 10")

if x > 15: # False


print("x > 15")

elif x > 10: # False


print("x > 10")

elif x > 5: # True


print("x > 5")
else:
print("else will not be executed")

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.

 Nested conditional statements, e.g.:

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")

Looping your code with for


Another kind of loop available in Python comes from the observation that sometimes it's more
important to count the "turns" of the loop than to check the conditions.

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

while i < 100:

# 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.

Take a look at the snippet:

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:

for i in range(2, 8):


print("The value of i is currently", i)

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

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, e.g.:

# Example 1

while True:

print("Stuck in an infinite loop.")

# Example 2
counter = 5

while counter > 2:

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"

for letter in word:

print(letter, end="*")

# Example 2

for i in range(1, 10):

if i % 2 == 0:

print(i)

2. You can use the  break  and  continue  statements to change the flow of a loop:

 You use  break  to exit a loop, e.g.:

text = "OpenEDG Python Institute"

for letter in text:

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"

for letter in text:

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()

for i in range(0, 3):


print(i)
else:
print(i, "else")

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

for i in range(6, 1, -2):


print(i, end=" ") # Outputs: 6, 4, 2

Exercise 1

Create a  for  loop that counts from 0 to 10, and prints odd numbers to the screen. Use the
skeleton below:

for i in range(0, 11):


if i % 2 != 0:
print(i)

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:

for digit in "0165031806510":


if digit == "0":
print("x", end="")
continue
print(digit, end="")

Key takeaways

1. Python supports the following logical operators:

 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:

 x = 15 , which is  0000 1111  in binary,


 y = 16 , which is  0001 0000  in binary.

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

z = ((x == y) and (x == y)) or not(x == y)


print(not(z))
Hasil : False

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.:

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

2. Lists can be indexed and updated, e.g.:

my_list = [1, None, True, 'I am a string', 256, 0]

print(my_list[3]) # outputs: I am a string

print(my_list[-1]) # outputs: 0

my_list[1] = '?'

print(my_list) # outputs: [1, '?', True, 'I am a string', 256, 0]

my_list.insert(0, "first")

my_list.append("last")
print(my_list) # outputs: ['first', 1, '?', True, 'I am a string', 256,
0, 'last']

3. Lists can be nested, e.g.:

my_list = [1, 'a', ["list", 64, [0, 1], False]]

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.

4. List elements and lists can be deleted, e.g.:

my_list = [1, 2, 3, 4]

del my_list[2]

print(my_list) # outputs: [1, 2, 4]

del my_list # deletes the whole list

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.

5. Lists can be iterated through using the  for  loop, e.g.:

my_list = ["white", "purple", "blue", "yellow", "green"]

for color in my_list:

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

7. A typical function invocation looks as follows:  result = function(arg) , while a


typical method invocation looks like this: result = data.method(arg) .

You might also like