1/84
week 1-5: operators, conditional logic, int, float, eval, lists, loops,
Name | Mastery | Learn | Test | Matching | Spaced |
|---|
No study sessions yet.
program
set of instructions written in a programming language that a computer can execute
programming
the process of creating programs
telling a computer how to solve a problem or
perform an action.
programming includes
Problem solving (breaking problem into steps)
Writing instructions in a programming language
Testing and debugging
assembly languages
First step beyond binary — uses symbols instead of just 0s and 1s
Still low-level: You write instructions that directly control the CPU and memory
High-Level Languages (like Python, Java,
C++)
Easier and more expressive for
humans. They are compiled or interpreted
into machine code
interactive mode
Run Python directly in the shell (>>>prompt)
Each line runs immediately and shows output
Good for quick testing
script mode
Write code in a file (.py) and run it
Runs the whole program at once
Use print() to see results
print()
Displays output to screen
the instruction that tells Python to show something on the screen
immutable
cannot be changed after creation
Any operation that alters the value will create a new object in memory
mutable
can be updated after creation, without creating a new object.
immutable data types
number
strings
tuples
mutable data types
list
dictionary
sets
string
a sequence of characters
Can include letters, digits, or symbols
Written inside 'single', "double", or '''triple''' quotes
numeric data
integers and floats
widely used in calculations
integers
whole numbers no decimals
floats
decimal numbers
Boolean
true or false
tuples
ordered, immutable collections
lists
ordered collection of objects
ordered, changeable collections
dictionaries
key-value pairs
sets
unique items, no order
variables
a name that stores data
Variables point to a value, but we often say the
variable is the value. They can later be changed
to point to something else
variable rules
Must begin with a letter or underscore
Can include letters, digits must begin with a letter or underscore, and underscores
built-in-function name cannot be a variable
assignment statement
gives a variable a value using the ‘=’ sign
input()
lets users type values while program runs
Program pauses until user presses Enter
always returns string
type conversion
int() → number
float() → decimal
str() → text
bool() → True/False
,
automatically spaces values
+
if both sides are numbers, + means add them.
If both sides are strings, + means join them together.
expression
An expression combines values and operators to
produce a result
eval()
expressions with operators/parentheses
takes a string and evaluates it as Python code.
If the string looks like math, it will compute the result.
If the string is a variable name or other valid Python code, it will also try to run it
abs()
absolute value
pow(a, b)
a raised to b
typing rules
Case sensitive
Spaces: indentation matters in Python
Errors appear if spaces are used incorrectly
sep=" "
ensures the words have spaces between them
if statement
used to make decisions in code
checks a Boolean condition (True/False).
If the condition is True, the indented code runs.
If the condition is False, that code is skipped
indentation shows which code belongs to the if
**
exponentiation
//
integer division
gives you the whole number result (rounded down) of a division
%
modulo remainder
Returns the remainder from a division
< >
comparison operator
==
equality operator
!=
not equal to operator
not operator
Reverses the Boolean value of the operand
If the operand is True, it returns False, and vice versa
and operator
Returns True if both operands are True
Otherwise, returns False
or operator
Returns True if at least one operand is True
Returns False only if both operands are False
else statement
executes when the condition is false
elif
When you want to test multiple conditions sequentially in a chained if-else block
type()
returns the type (or class) of the given object useful for inspecting the type of variables or objects at runtime
sys.exit()
ends a Python program immediately
sys.exit(0)
The number 0 means the program exited normally (no error)
Before using sys.exit(), you must import the sys module
random.randint(min, max)
random integer (inclusive range)
must first import random
time.asctime()
returns current time as a string
time.sleep(secs)
pauses the program for secs seconds
random.gauss(mu, sd)
random float from Gaussian distribution
mu: The mean (average) of the distribution
sigma: The standard deviation (spread) of the distribution
while loop
repeat executing their [indented] code block until the condition becomes false
for loop
repeats something a specific number of times (for loop range (start,stop,step) or range(start,stop))
A for loop in Python does not include the last stop value from the range
break
stops the loop immediately, even if the condition is still true
continue
skips the rest of the current iteration and continues with the next
list() or []
list function
Create a list with comma-separated values inside square brackets
list index
position number, in square brackets
access an individual element of a list
starts with 0 counting up from the beginning
Or -1 counting down from the end
in
in a condition checks membership (True/False).
in a for loop provides each value as the loop iterates
checks whether a value is in a list (True/False).
Use with if/while for validation.
Use 'not in' to check absence
len()
function to get length of list
list.append(value)
add an item to the end of a list
list.pop(position)
removes item at position
print(list.pop() )
Get and remove the last element
list.sort()
sort a list in place (ascending by default)
list[start:end]
list slicing
slicing
extracts or assigns a range of elements
start is inclusive
end is exclusive indexes separated by a colon
Slices can be open-ended
Slicing can also replace or remove parts, growing or shrinking the list
list[start : end : step]
list slicing using step
start: The index where the slice begins (inclusive). Defaults to 0 if omitted.
stop: The index where the slice ends (exclusive). Defaults to the end of the list if omitted.
step: The interval between elements. Defaults to 1 if omitted.
x.copy()
x[:]
[0:len(x)]
copy
x % 2 == 0
checks if divisible by 2 (even numbers)
range()
generates a sequence of numbers within range, which is commonly used with a for loop to iterate over a specific range of values
inclusive start
exclusive stop
range (start, stop, step)
sum()
adds values within parentheses
min(list)
returns smallest item in a list
max(list)
returns largest item in a list
list[::-1]
list.reverse()
reverse list
list[::2]
even items
+=
adds a value to a variable and then assigns the result back to that variable
[] + []
adds one list to the end of another
[]*value
repeats the list for value
L=[1,2,4,7]
for i in range(len(L)):
print(L[i])
prints out the items of a list, one-by-one, on separate lines
average = sum(list) / len(list)
computes the average of the values in a list
print(list.count(“x”))
returns the number of times x occurs in a list
print(name.index("x"))
returns the location of the first occurrence of x
list.remove(“x“)
removes the first occurrence of x from the list
list.insert(position,”x”)
inserts x at index position on the list
list = [1,2,3,4]
for i in range(len(list)):
list[i] = list[i]**
Replaces each element in a list with its square