Chap 8 - programing python - print, if/elif/else, (nested) loops, len, string manipulation, arrays Flashcards
name 6 data types
-integer
-string
-boolean
-float
-character (char)
-date
how do you use the print function
print(“ “)
2 ways you can print messages on print function
-comma
-concatenation (adding)
meaning of concatenation
join together
how do you use comma when printing
use comma between words
how do you use concatenation when printing
use ( + ) to add the strings
what is the difference between using comma and concatenation
space in comma, no space in concatenation
can you add strings
yes
can you add integers
no
what must you put when using \t and \n
quotations because they’re strings
what does \t do
a tab of space
what does \n do
a new line
what does = do
assignment of variable
what does != mean
not equal
3 rules for variables
-has to start with a char
-case sensitive
-no special char and spaces - willc hange program (except underscore)
arithmetic operation for
-addition
-subtraction
-multiply
-divide
-remainder
-power
-squared
- +
- -
- *
- / (float), // (integer)
- %
- **
- **(1/2)
relational operation for:
-greater than
-greater than or equal
-smaller than
-smaller than or equal
-equal (Equality (eg, 2 obj, same 2 content))
-not equal (Equality (eg, 2 obj, same 2 content))
- >
- > =
- <
- <=
- ==
- !=
logical operators
- and
- or
- not
eg. if not hungry:
note: explain each thing when explaining assignment
eg. c = a + b
- c: variable
- +: addition of a and b
- =: assignment of variable
equality vs identity vs memebership
equality - checks if obj has same contents (2 obj, same 2 content)
identity - check if obj are the same by refer back to same memory (2 obj, 1 content)
membership - check if value exists in a sequence
what does = & == do
= - assignment of variables
== - comparison
how do you find input for diff data types
str(input(“ “))
int(input(“ “))
float(input(“ “))
1)can integer be stored in float, why
2)can float be stored in integer, why
1)yes, integer requires less memory than float
2)no, float requires more memory than integer
what is the drawback of integer and float stored as string
they’ll be used as a string - lose their properties (can’t do mathematical operations on them)
1)can integer and float be stored in string
2)can a string be an integer/ float
1)yes
2)no
how do you use if, elif, else conditional statement
if ( ):
, start here
-indentation
elif ( ):
, start here
-indentation
else:
, start here
-indentation
how do you use nested ifs
if ( ):
if ( ):
-indentation
how do you use and & or conditions in conditional statements
eg. if ( age> 10 and age< 20):
eg. if ( age> 10 or age< 20):
how do you use conditional statement to get something in between value
eg. if (0 < username <10):
nota: % - remainder, // - integer, / - float (for division)
note: all chars are strings, not all strings are chars
Iteration
looping
why are looped required
use same algorithm for diff. inputs
types of loops
-for
-while
basic structure of loops
-initializer- variable which controls if loop is done or not
-action
-stopping condition
-updating counter/ no. loops
how to write for loop
-for i in range (__,__,_if you want__):
-for i in (variable/ list/ str)
-third one changes the steps between the loop
-don’t need to write iterating variable at start
(i changed to elements in variable/ list/ str)
(auto counter update)
how to update counter
i = i+1
i +=1
how to write while loop
i = 0
while (____):
i +=1
(manuel counter update)
how does range function work
eg, (0, 5) - no.s - 0, 1, 2, 3, 4, - no 5
(0, 20, 2) - no.s 0-19, with 2 step btw (eg, 0, 2, 4…)
(variable/ list/ str) = no.s in that variable, list
diff btw for & while loops
-for - knows how many times to run = count controlled
-while - checks iterating value before running = precondition
types of loop control statements
-break
-continue
-pass
how to use break loop control
-write break within loop
-stop loop
-if used in nested loop, it stop the inner most loop
how to use pass loop control
-write pass within loop
-acts as a placeholder and doesn’t print the i for that loop
how to use continue loop control
-write continue within loop
-skips current iteration and jumps to next loop
how to write loop/if/elif with a list as its range
n= [“A”, “B”]
-for i in n:
-while i in n:
-if variable[i] in n:
note: i changes to elements in list, list can be any data type
index values in list
-all char has an index value
-first element = 0 - positive
-last element = -1 - negative
-space also has an index value
note: space is considered a char so has an index value
how to use len function
-finds no. elements in a list - list can be of any data types
n = [1,2,3]
length = len(n)
print(length)
how to extract a certain char from a list
num = [1,2,3,4]
- print(num[ 0 ]) = 1
-print(num[ 0: ]) = 1, 2, 3, 4
-print(num[ 0:2]) = 1,2 (index after : not included)
-print(num[:2]) = 1,2 (index after : not included)
-print(num[-1]) = 4
-print(num[i:i+ n ]) = value with i index & n no.s after it
diff btw in range of loops -
-for i in range (10, lengthData+10):
= i starts from 10th index - if range i beyond elements in list = index out of range error
-for i in range (0, lengthData):
= i starts from 0th index
how to print i in a single line in a loop
print( i, end=” “)
how to use match case statements
match (variable):
case “something”:
action
case _:
action (only run when none of others match)
-use like if statements
define array
-a sequence of elements of the same data type
what the the index value of first element called
lower bound
what the the index value of last element called
upper bound
how do you create a blank 1D array
-reserving memory in ram
-variable = [ None ] * (number of times)
how to use blank array and string manipulation together
-variable [index number] = “ “
-for i in range ( , ):
variable [i] = ______
-while i < ___:
variable [i] = ______
note: there are index values for each element in an array
2 types of searching algorithms
-linear search
-binary search
1 type of sorting algorithm
-bubble sort
how does linear search work & its time
-compare target value with elements from left to right until they match (can be sorted or unsorted list)
-time: 0(n)
advantages and disadvantages of linear search
advantages:
-fast for small to medium data sets
-works for sorted & unsorted sets
-good for data structures with no random access
disadvantages:
-slow for large data sets
how does binary search work & its time
-check if target value if equal, bigger or smaller than the element in the middle
-eg, it’s smaller so all the elements smaller than the mid element and the mid element are left out in the next search
-continue until target value is found
-time: 0 (log n)
advantages and disadvantages of binary search
advantages:
-quick
-good for large data sets
disadvantages:
-needs to be sorted
how does bubble sort work & its time
-start with 1 chosen element
-compares adjacent elements to the chosen element and swaps them if needed until it is no longer needed
-time: 0 (n^2)
advantages and disadvantages of bubble sort
disadvantages:
-bad for large data sets
how to do nested for loops
-2 counters for inner and out loops
-outer loop only loops after inner loop is finished
eg. for j in range (0,3):
for i in range (0,2):
action
what variable can you use for bubble sort
a temporary variable for the element swapping process
Code for bubble sort
n = len(array)
for i in range(n - 1):
for j in range(n - i - 1):
if array[ j ] > array[ j + 1 ]:
temp = array[ j ]
array[ j ] = array[ j + 1]
array[ j + 1] = temp
code for linear search
for i in range (len(array)):
if array[ i ] == number:
print(“number found”)
code for sum of reach row in 2D array
for row in range ( , ):
sum = 0
for column in range( , ):
sum += array[row] [column]
print(sum)
code to put highest/ lowest/ avg value from 2D array in 1D array
highest_stores = [0 for i in range( )]
salary = [[0 for c in range( )] for r in range( )]
for r in range ( , ):
highest_salary = salary[r] [c]
for c in range ( , ):
if salary[r] [c] > highest_salary:
highest_salary = salary[r] [c]
highest_stores[r] = highest_salary
print(“Highest salary in”, r, “is”, highest_salary[r])
-declare the first element in each row as highest salary & compare it with others
-if others are bigger, highest salary is replaced by it
how to swap elements without a temporary variable
-ages [i], ages [i+1] = ages [i+1], ages [i]
1 2 2 1
Left to right:
1 goes to 2
2 goes to 1
How does a post test loop work (not used in python)
-initialize loop counter
-execute action
-update counter
-check condition
-if condition met, stop
else repeat
how does a pre test loop work
-initialize loop counter
-check condition
if condition met:
-execute action
-update counter
note: arrays cannot be implemented on python so just think of them like list with 1 data type
what is a 2D list
a list made up of lists
eg.
meats = [“chicken”, “fish”, “turkey”]
groceries = [fruits, groceries, meats]
how to use a 2D list with variables to print row or element
for a row:
-print(groceries [row])
for a single element:
-print(groceries [row] [column])
-each list is a row, each element is in a column (like a table)
define traversing
accessing individual elements in 2D array
how to traverse
groceries = [[“apple”, “orange”, “banana”, “coconut”],
[“celery”, “carrots”, “potatoes”],
[“chicken”, “fish”, “turkey”]]
-for j in groceries:
for i in j:
print(i)
-for row in range ( , ):
for column in range ( , ):
print(groceries [row] [column])
-finish inner loop before changing outer loop
row, column:
0, 0
0, 1
1, 0
1, 1
what does end = “ “ do
rearranges the printed word in a single line
note: for loop doesn’t check condition, only runs it
pre- condition loop in pseudocode
while loop
post- condition loop in pseudocode
REPEAT
what is size of array
number of elements
how to randomly choose an element
import random
random.choice( )
random.randint( ) / random.randstr ( ) / random.randfloat ( )
how to add time
import time
time.sleep( )
-in seconds
what happens if index is too big
index out of range error
how to create empty 2D array
array = [ [ 0 for column in range ( , )] for row in range ( , )]
-can replace 0 with None or “ string” to fill in the blank array
order of row & column in 2D array when:
1)creating array
2)printing array
3)traversing
mark row = 1, column = 2
1) column, row 2, 1
2) row, column 1, 2
3) row, column 1, 2
what can you do with traversing
-print each elements
-add data into 2D array eg. input or adding
difference between for i in range ( , ) & for i in array when comparing & printing Found/ Not found
for i in range ( , ):
-print Found/ Not found as many times as range
for i in array:
-print Found/ Not found 1 time
note:
before making 2D array - make a table look alike of it
mark row = 1, column = 2
difference btw 1D & 2D array in terms of memory
1D - data is stored randomly in memory cell = more comparisons to find them
2D - data is stored consecutively in memory cell = less comparisons to find them
help for arrays:
https://docs.google.com/document/d/1b5Tt-2W5yVyTZYWSwUQk3DXtFnfM_McnkaAZX1FV1QQ/edit?tab=t.0#heading=h.isd4beaopm41
note:
for loop - limited running
while - unlimited running
what loop to use for validation
while loop