Chap 8 - programing (python) - conditions, loops, string manipulation, arrays Flashcards
commenting on code
this symbol must be added for each line of comment
rules for variables
-has to start with a character
-no special char and spaces - will change program (except underscore)
-case sensitive
Poop & poop are 2 diff variables
note: explain each thing when explaining assignment
eg. c = a + b
- c: variable
- +: addition of a and b
- =: assignment of variable
name 6 data types in python
-integer
-string
-boolean
-float
-character (char)
-date
features of data types
-all chars are strings, not all strings are chars
-integer be stored in float because it requires less memory than float. it cannot work the other way around
-integer & float can be stored as string but lose their properties = can’t do mathematical operations on them, string cannot be stored in integer or float
how do you find input for diff data types
str(input(“ “))
int(input(“ “))
float(input(“ “))
print function
print(“ “)
how to print i in a single line in a loop
print( i, end=” “)
2 ways you can print multiple messages on print function
-comma btw words
-concatenation (adding) = join tgt only strings using +
(space in comma, no space in concatenation)
what does \t do
a tab of space
what does \n do
a new line
what must you put when using \t and \n
quotations because they’re strings
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 (comparison)
-not equal (comparison)
- >
- > =
- <
- <=
- ==
- !=
difference btw = & ==
= - assignment of variable
== - comparison
logical operators in conditions
- and
- or
- not
eg. if not hungry:
and & or conditional statements
eg. if ( age> 10 and age< 20):
eg. if ( age> 10 or age< 20):
conditional statement to get something in between value
eg. if (0 < username <10):
when checking for discounts, always put bigger no. first
if total > 1000;
discount = total *0.2
elif total > 500:
discount = total *0.1
if, elif, else conditional statement
if ( ):
action
-indentation
elif ( ):
action
-indentation
else:
action
-indentation
nested ifs
if ( ):
if ( ):
-indentation
match case statements
match (variable):
case “something”:
action
case _:
action (only run when none of others match)
-use like if statements
use of loops
use same algorithm for diff. inputs
types of loops
-for (count controlled) - knows how many times to run - doesn’t check condition
-while (pre condition) - checks iterating value before running - use for validation
basic structure of loops
-initializer- variable which controls if loop is done or not
-action
-stopping condition
-updating counter/ no. loops
for loop
-for i in range (__,__,_if you want__):
-for i in (variable/ list/ str) = (i changed to elements in variable/ list/ str)
-third one changes the steps between the loop
-don’t need to initialize iterating variable at start
(auto counter update)
how does range function work
eg, (0, 5) - no.s - 0, 1, 2, 3, 4 (last value not counted) - total 5
(0, 20, 2) - no.s 0-19, with 2 step in btw (eg, 0, 2, 4…)
(variable/ list/ str) = no.s in that variable, list
error 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
what happens if index is too big
index out of range error
while loop
i = 0
while (condition):
i +=1
-initialize iterating variable at start
(manual counter update)
update counter
i = i+1
i +=1
how to do nested for loops
-2 counters for inner and outer loops
-outer loop only loops after inner loop is finished
eg. for j in range (0,3):
for i in range (0,2):
action
types of loop control statements
-break
-continue
-pass
break loop control
-write break within loop
-stop loop
-if used in nested loop, it stop the inner most loop
pass loop control
-write pass within loop
-acts as a placeholder and doesn’t print the i for that loop
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
len function
-finds no. elements in a list - list can be of any data types
n = [1,2,3]
length = len(n)
print(length)
index values in list
-all char has an index value
-first element = 0 - positive
-last element = -1 - negative
-space also has an index value
extract a certain char from a list (string manupilation)
num = [6, 7, 8, 9]
-print(num[ 0 ]) = 6
-print(num[ 0: ]) = 6, 7, 8, 9
-print(num[ 0:2]) = 6, 7 (index after : not included)
-print(num[:2]) = 6, 7 (index after : not included)
-print(num[-1]) = 9
-print(num[i:i+ n ]) = value with i index & n no.s after it
define array
-a sequence of elements of the same data type
-each element has an index value
-arrays cannot be implemented on python so just think of them like list with 1 data type
name of index value of first & last element
first - lower bound
last - upper bound
create a blank 1D array
-reserving memory in ram
-variable = [ None ] * (number of times)
searching algorithm - linear search
-compare target value with elements from left to right until they match (can be used for sorted or unsorted list)
code for linear search
for i in range (len(array)):
if array[ i ] == number:
print(“number found”)
sorting algorithm - bubble sort
-start with 1 chosen element
-compares adjacent elements to the chosen element and swaps them if needed until it is no longer needed
-use a temporary value to swap elements
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
swap elements with a temporary variable
a = 5
b = 10
temp = 0
————————
temp = a
a = b
b = temp
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
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
what is a 2D list
a list made up of lists
eg.
meats = [“chicken”, “fish”, “turkey”]
groceries = [fruits, groceries, meats]
note:
before making 2D array - make a table look alike of it
mark row = 1, column = 2
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
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
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)
traversing - accessing individual elements in 2D array
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
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 randomly choose an element
import random
random.choice( )
random.randint( ) / random.randstr ( ) / random.randfloat ( )
how to add time
import time
time.sleep( )
-in seconds
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
help for arrays:
https://docs.google.com/document/d/1b5Tt-2W5yVyTZYWSwUQk3DXtFnfM_McnkaAZX1FV1QQ/edit?tab=t.0#heading=h.isd4beaopm41
How does a post condition loop work (not used in python)
-initialize loop counter
-execute action
-update counter
-check condition
-if condition met, stop
else repeat
built in functions
1) len(list) - no. of element in list
2) variable.upper ( ) - all string will be uppercase
3) variable.lower ( ) - all string will be lowercase
4) pow (base, exponent)
5) round (number, decimal place)
6) import random
random.choice( )
random.randint( ) / random.randstr ( ) / random.randfloat ( )
7) import time
time.sleep( )