Selection and Iteration and arrays

0.0(0)
studied byStudied by 0 people
learnLearn
examPractice Test
spaced repetitionSpaced Repetition
heart puzzleMatch
flashcardsFlashcards
Card Sorting

1/61

flashcard set

Earn XP

Description and Tags

week 2,3 & 4

Study Analytics
Name
Mastery
Learn
Test
Matching
Spaced

No study sessions yet.

62 Terms

1
New cards

Conditional Expressions Overview

allows programs to make decision based on whether they true or not

2
New cards

relational operators.

used to compare two values

  • they return boolean value

3
New cards

examples of rational operators

  • >

  • <

  • >=

  • <=

  • == checks if values are equal

  • = used for assignment

  • !=

4
New cards

boolean operators

  • and true, if both operands are true

  • or true if at least one is true

  • not , true if operands is false, false if operands is true

5
New cards

Operator Precedence

Now that we have seen how operators can be mixed, we need precedence rules for all operators

() (highest precedence – performed first)

**

* / // %

+ -

< <= >= > == !=

not

and

or (lowest precedence – performed last)

6
New cards

De Morgan’s Laws

2 rules for boolean

  • 1st rule Not(A and B) —> Not A or Not B

  • 2nd rule Not (A or B) —> Not A and Not B

7
New cards

BOOLEAN

binary value that can either be true or false

8
New cards

Conditional (relational) expression

expression that converts values using relational or conditional operators

9
New cards

Iteration

executing the same basic task multiple times

  • allows repetition many times without having to type the same statement many times

10
New cards

Counter-Controlled Loops

  • repeats a block of code for specific number of times

  • In Python, this is typically implemented with the for loop and the range() function.

11
New cards

note

  • range(n) —> start from 0 and stop before n

  • range(start, stop, step) —> start from start, stop before stop and add a step

12
New cards

Print numbers 1 to 5 using a counter-controlled loop

for counter in range(1, 6):

print(counter)

#1 2 3 4 5

13
New cards

Condition-Controlled Loops

used when we don’t in advance how many times a loop should repeat

14
New cards

Count-Controlled Loop (for loop)

you know in advance how many times you want the loop to repeat

  • for variable in range(start, stop, step)

15
New cards

Condition-Controlled Loop (while loop)

Use it when:

  • You don’t know how many times the loop should repeat ahead of time.

  • The loop should continue based on a condition being true

  • i = 0

    while i < 5:

    print("Count is:", i)

    i += 1

16
New cards

What Is a Post-Check Loop?/do-while loop

  • runs at least once

17
New cards

Infinite Loops

loop that never end unless stopped manually or broken from inside

18
New cards

The break Statement

  • stops when a certain condition is met

  • exit the loop

  • while True:

    num = int(input("Enter a number (0 to stop): "))

    if num == 0:

    break

    print("You entered:", num)

19
New cards

The continue Statement

  • skips the rest of the loop for the current iteration and goes to the next one

  • for i in range(1, 6):

    if i == 3:

    continue # Skip 3

    print(i)

  • result

  • 1

    2

    4

    5

20
New cards

The else Statement (with loops)

  • the else statement after break wont print

21
New cards

The pass Statement

  • does nothing

22
New cards

pass

placeholder that does nothing

23
New cards

array

  • data structure that stores values accessible under index

  • it can hold different types of data

  • called a list

24
New cards

index

  • position

25
New cards

Arrays can be fixed length or variable length

  • fixed array cannot be changed

  • variable array can be altered

26
New cards

x.append

adds an item to the end of a list

27
New cards

x.remove

removes an item from the list

28
New cards

print(x[index])

accessing position of a number in a list

29
New cards

print(x[-1])

accessing the last item in a list

30
New cards

x[index] = new item

changing old item into a new item

31
New cards

Iterating over items in list

when you don’t need to know the indexes

  • for a in X:

    print(a)

    when you need to know indexes

  • for n in range (len (X)):

    print(n, X[n])

32
New cards

Common Pitfall/Error

accessing an item that is not in the list

33
New cards

IndexError:

  • list index is out of range

34
New cards

Merging lists (concatenation)

  • adding list

  • list1[1, 2 ] + list2[3, 4 ]

  • = [1, 2, 3, 4]

35
New cards

Checking for item (membership)

  • checking an item a from list

  • X = [1, 2, 3]

    print(2 in X)

    print(5 in X)

  • true

    false

36
New cards

Multiplying content of lists (repetition)

  • repeating content in a list

  • list1[1, 2]

    list1×2

    =[1, 2, 1, 2]

37
New cards

Access List Item (Indexing)

  • list = [1, 2, 3, 4, 5]

  • print(list[2])

    3

38
New cards

Get Length of List (Length)

  • use len

  • list = [1, 2, 3, 4, 5]

  • print(len(list))

    5

39
New cards

DELETE

  • del(list)

  • different from remove

  • = [10, 20, 30, 40]

    del X[1] # Deletes the item at index 1

    print(X)

  • [10, 30, 40]

  • but then remove removes an item

  • X = [10, 20, 30, 40]

    X.remove(20) # Removes the value 20

    print(X)

  • [10, 30, 40]

40
New cards

Get Slice of List (Slicing)

x[start, stop, step]

41
New cards
  • Iterate Over List (Iteration)

X = [1, 3, 5]

for num in X:

print(num * 2)

  • 2

  • 6

  • 10

42
New cards

Add element to end

x.append

43
New cards

Sort list

  • x.sort

  • from smallest to the biggest

44
New cards

Reverse items

  • X.reverse()

  • X = [6, 5, 4, 3, 2, 1]

45
New cards

Find position of item

x.index[2]

46
New cards

Insert item at index

x.insert(index, new value)

x.insert(2, 99)

47
New cards

Count occurrences of item

  • count how many times does an item appear on a list

  • x.count(2)

  • it will count how many times does 2 appears

48
New cards

Remove first occurrence of an item

  • remove the fisrt occurrence of a number

  • x.remove(99)

49
New cards

Remove and return item at index

x.pop(99)

  • it will return the position on 99 in the list

50
New cards

Split string into list

  • x.split(‘,’)

  • x=“1”, “2”, “3”

  • [“1”, “2”, “3”]

51
New cards

Split by space (default)

  • sentence = "Hello world this is ChatGPT"

    words = sentence.split()

    print(words)

    ['Hello', 'world', 'this', 'is', 'ChatGPT']

52
New cards

# Join list into string

  • does similar work to sep

  • x=[1, 2, 3]

  • ‘*’.join(x)

  • 1*2*3

  • sep = ‘*’

    sep.join(x)

  • 1*2×3

53
New cards

2-Dimensional Arrays

  • a list of list

  • x =[ [1, 2], [3, 4]]

  • x[0] = [1, 2]

  • x[1] = [3, 4]

  • x[0][0] = 1 (return an item in row 0 column 0)

  • x[0][1] = 2

  • x[1][1] = 1

54
New cards

note

  • x[0][0]

  • the first index selects a row

  • the second index selects a column

55
New cards

multi-dimensional lists

students = [['saleem', ['csc1015f', ['12 april', ['5','6','7']]]]]

solve

x[0][0]

x[0][1][0]

x[0][1][1][0]

x[0][1][1][1]

x[0][1][1][1][2]

56
New cards

Dictionaries

  • { }

  • its immutable

  • D = {'a': 'apples', 'b': 'bananas', 'p': 'pears'}

    'a', 'b', and 'p' are the keys, and 'apples', 'bananas', and 'pears' are their corresponding values.

57
New cards

D = {'a': 'apples', 'b': 'bananas', 'p': 'pears'}

  • print(D[‘a]) #apples

  • D[“b”] = cherry #D = {'a': 'apples', 'b': 'cherry', 'p': 'pears'}

  • D.keys() – returns all keys

  • D.values() – returns all values

  • D.items() – returns key-value pairs

    for key, value in fruits.items():

    print(key, ":", value)

    a : apples

    b : bananas

    p : pears

58
New cards

Remove a key and return its value

removed = fruits.pop('p')

print(removed) # Output: pears

print(fruits) # Output: {'a': 'apples', 'b': 'bananas'}

59
New cards

Remove all items

fruits.clear()

print(fruits) # Output: {}

60
New cards

generic (or nested) data structures

you can combine lists dicts and tuples ect.

61
New cards

Dictionary of Lists

  • D = {

    'kayleigh': [12, 23, 31],

    'callum': [45, 54, 55]

    }

  • print(D['kayleigh']) # Output: [12, 23, 31]

    print(D['callum'][1]) # Output: 54

  • D['kayleigh'].append(42)

    print(D['kayleigh']) # Output: [12, 23, 31, 42]

  • 'kayleigh and callum are key

  • and the lists are values

62
New cards

List of Dictionaries

  • E = [

    {'name': 'palesa', 'year': 1},

    {'name': 'luqmaan', 'year': 1}

    ]

  • print(E[0]['name']) # Output: palesa

    print(E[1]['year']) # Output: 1

  • E.append({'name': 'samira', 'year': 2})

    [

    {'name': 'palesa', 'year': 1},

    {'name': 'luqmaan', 'year': 1},

    {'name': 'samira', 'year': 2}

    ]