Deck 1 Flashcards
#
Comment – anything after this does not get read by computer
print()
Print function. Computer will “speak” the words inside this, as long as there are quotation marks around the words
strings
Blocks of text. Must have either “double” or ‘single’ quotation marks around them. Must be consistent with either double or single all the way through.
variable
Assigns string of data to this using equal sign. Data is stored for later use. Must use quotation marks for strings. this = “the string of data to be stored”
print(this) –outputs– the string of data to be stored
variable rules
Can’t have spaces or symbols other than underscore (_). Cannot begin with number, although can have numbers in it.
reserved words a
and
as
assert
reserved words b
break
reserved words c
class continue
reserved words d
def del
reserved words e
elif
else
except
reserved words f
finally
for
from
reserved words g
global
reserved words i
if
import
in
is
reserved words l
lambda
reserved words n
nonlocal
not
reserved words o
or
reserved words p
pass
reserved words r
raise
return
reserved words t
try
reserved words w
while
with
reserved words y
yield
> > >
interactive chevron prompt. this prompt is the Python interpreter’s way of asking you, “What do you want me to do next?” Python is ready to have a conversation with you.
quit()
the proper way to say “good-bye” to Python. enter at interactive chevron prompt.
script
python file
.py
file extension for python scripts, what python files are saved as
$
operating system prompt
numbers
numbers without quotation marks make them math-y and can be used in math operations
+
adds stuff together, both numbers and words
-
subtracts stuff
*
multiplies
/
divides
reserved words
we must use these words to mean the thing that python expects them to mean, so we cannot use them in variables or such
len()
function that tells you how many characters are in a string OR how many items are in a list
print(len(list))
print(len(string))
integers
whole numbers (including negatives)
float
numbers with decimals, or fractions, etc.
int()
converts a string to a number
boolean
term for a value that is either True or False, or Yes or No
True
equal to 1
False
equal to 0
boolean expression
a combination of booleans (and comparison operators) that evaluates to True or False, or Yes or No
and
A boolean operator. An expression with ‘and’ evaluates to True if and only if both parts of the expression are True
or
A boolean operator. True if either side of the expression is true.
not
Negates a boolean value and makes it the opposite of whatever it currently is
if
If statements. They allow a python program to make decisions based on boolean expressions. The code following keyword if must be a boolean expression.
if boolean statement : (equates to true or false)
print(‘whatever’) executes “then statement” if true
code is executed in an if statement
when the condition is True
elif
chains multiple conditions together if elif elif (only one value outputs, not all three as would happen if all were if)
else
when if condition is false, else block will be executed
added at end of an if block
statement
if statement :
then statement (runs if true)
else :
then statement (runs if false)
final statement
list
contains values that are accessed by indexes [0, 1, 2, 3, 4] mix of numbers and words, words must be in quotes , commas between can be strings, integers, floats, etc.
var = [0, 1, 2, 3, 4] [ ] makes it a list
index
first value is at index 0 indexes are list values [0, 1, 2, 3, 4]
printing lists
print(listname) prints everything including parenthesis
phillies = [“aaron”, 27, “bryce”, 3, “jt”, 10]
print(phillies)
[“aaron”, 27, “bryce”, 3, “jt”, 10]
print index values to get individual entries
print(phillies[0])
aaron
print(phillies[1])
27
append()
adds a value to a list
print(listname)
listname.append(‘new entry’)
pop()
deletes a value from the list, will delete last one unless specified listname = ["a", "b", "c"] listname.pop() print(listname) ["a", "b"]
listname = [“a”, “b”, “c”]
listname.pop(0)
print(listname)
{“b”, “c”]
in
tests whether list contains a value, will output True or False
listname = [“kiwi”, 4, “grape”, 5, “basket”]
print(“grape” in listname)
True
print(“apple” in listname)
False
dictionary
a collection of key-value pairs, an associative array dictname = { "key": "value", "entry": "definition", "a": "b" }
printing a dictionary
print(dictname)
key
first entry in a dictionary pair surrounded by quotes, followed by colon
value
second entry in a dictionary pair surrounded by quotes, separated by comma
accessing value of a key
x = dictname[“key”]
print(x)
getting value of a key
x = dictname.get(“key”)
print(x)
overwriting value in a dictionary
names = {“John” : “Doe”}
names[“John”] = “Smith”
print(names)
dictname = {“key” : “oldvalue”}
dictname[“key”] = “newvalue”
print(dictname)
**
power
%
remainder/modulo does the division, but gives the remainder instead of the quotient
operator precedence rules
- Parentheses
- Exponents
- Multiplication, Division, and Remainder
- Addition and Subtraction
- Left to right
float()
converts to floating point
input()
a function that allows user input
input(prompt)
x = input(“Enter your name:”)
print(“Hello, “ + x)
conditional statements
statement
if statement : (if + boolean statement)
then statement (must be indented by 4 spaces, will run if boolean statement if true; then statement is often print(‘whatever’))
if statement : (if + boolean statement)
then statement (must be indented by 4 spaces, will run if boolean statement if true)
final statement
<=
less than or equal to
==
equal to
> =
greater than or equal to
>
greater than
!=
not equal
indenting in conditional code
indenting is vital to run “then” statements, won’t run without them
4 spaces
can run multiple “then” statement off one “if” statement, as long as they are all indented will run until next non-indented statement
to stay in block of code, maintain/increase indent; to get out of block of code, decrease indent
see colon, indent
…<=….
less than
try
tries the code paired with except if no exception error, try code will run and except will be ignored if error, except code will run and try will be ignored
try:
code
except
runs when exception error occurs in try code usually an error message comes after try: code
except:
code
function
a block of organized, reusable code that is used to perform a single, related action
stores for later, like a variable that holds code
some stored code that we use. takes some input and produces an output
defining a function
def funcname() : indent- print('whatever') indent -print('this thing')
conditions for function (indented things) will be executed whenever function is called
function ends when de-indented
calling function
funcname()
will execute function conditions
argument
information can be passed into functions (when called) as this
goes in parenthesis of function name
type()
method returns class type of the argument(object) passed as parameter. this function is mostly used for debugging purposes
parameter
variable listed inside the parentheses in the function definition
can use if elif else with variable indent def greet (lang) : indent if lang == 'es' : indx2 print('Hola') ind elif lang == 'fr' : indx2 print('Bonjour') ind else: indx2 print('Hello')
return
lets a function return a value
def my_function(x) : return 5*x
print(my_function(3))
15
fruitful function
one that produces a return value
multiple parameters/arguments
separate with commas
for
loop used for iterating (repeating) over a sequence (that is either a list, a tuple, a dictionary, a set, or a string)
fruits = [“apple”, “strawberry”, “cherry”]
for x in fruits:
ind print(x)
while
loop used for executing a set of statements as long as a condition is true
in
python keyword used to:
a. check if value is present in a sequence (list, range, string, etc.)
b. used to iterate through a sequence in a for loop
break
stops the loop, ends the current loop and jumps to the statement immediately following the loop
if x == “whatever” :
ind break
continue
ends the current iteration and jumps to the top of the loop and starts the next iteration
if x == “whatever” :
ind continue
i
variable for integer iteration
counting in a loop
to count how many times we execute a loop, we introduce a counter variable that starts at 0 and we add one to it each time through the loop
count = 0 print('Before', count) for thing in [n1, n2, n3, n4, n5] : ind count = count + 1 ind print(count, thing) print ('After', count)
summing in a loop
to add up a value we encounter in a loop, we introduce a sum variable that starts at 0 and we add the value to the sum each time through the loop
total = 0 print ('Before', total) for thing in [n1, n2, n3, n4, n5] : ind total = total + thing ind print = (total, thing) print ('After', total)
finding the average in a loop
an average just combines the counting and sum patterns and divides when the loop is done
count = 0 sum = 0 print ('Before', count, sum) for value in [n1, n2, n3, n4, n5] : ind count = count + 1 ind sum = sum + value ind print (count, sum, value) print ('After', count, sum, sum / count)
filtering in a loop
we use an if statement in the loop to catch/filter the values we are looking for
print('Before') for value in [n1, n2, n3, n4, n5] : ind if value > 20 : indent2 print 'Large number' ,value print ('After')
search using a boolean variable
If we just want to search and know if a value was found, we use a variable that starts at False and is set to True as soon as we find what we are looking for
found = False print('Before', found) for value in [n1, n2, n3, n4, n5, n6] : ind if value == n4 : indent2 found = True ind print(found, value) print('After', found)
None
absence of a value variable
finding the smallest value
the first time through the loop smallest is None, so we take the first value to be the smallest
smallest = None print('Before') for value in [n1, n2, n3, n4, n5, n6] : ind if smallest is None : indent2 smallest = value ind elif value < smallest : indent2 smallest = value ind print {smallest, value) print('After', smallest)
is
operator that can be used in logical expressions
implies “is the same as”
similar to, but stronger than ==
returns True if both variables are the same object
is not
also a logical operator
returns True if both variables are not the same object
index operator
access each letter in a string with an index that starts at 0
in square brackets, pronounced ‘sub’
fruit = ‘banana’
letter = fruit[1]
print(letter)
a
banana
012345
looping through strings (indeterminate)
using a while statement and an iteration variable, and the len function, we can construct a loop to look at each of the letters in a string individually
fruit = 'banana' index = 0 while index < len(fruit) : ind letter = fruit[index] ind print(index, letter) ind index = index + 1
0 b 1 a 2 n 3 a 4 n 5 a
looping through string (determinate)
a definite loop using a for statement, the iteration variable is completely taken care by the for loop
fruit = 'banana' for letter in fruit : ind print(letter)
b a n a n a
looping and counting number of things
counting number of ‘a’s in banana -
word = 'banana' count = 0 for letter in word : ind if letter == 'a' : indent2 count = count + 1 print (count)
slicing strings
can look at any continuous section of a string using a colon operator
the second number is one beyond the end of the slice - “up to but not including”
if the second number is beyond the end of the string, it stops at the end
if we leave off first number the last number of the slice, it is assumed to be the beginning or end of the string respectively
>>> s = 'Monty Python' >>> print(s[0:4]) Mont >>> print(s[6:7]) p >>> print(s[6:20]) Python
Monty Python
1234567891011
>>> s = 'Monty Python' >>> print(s[:2]) Mo >>> print(s[8:]) thon >>> print(s[:]) Monty Python
string concatenation
applying + operator to strings, must add spaces in separately
a = ‘Hello’
b = a + ‘There”
print(b)
c = a + ‘ ‘ + ‘There’
print(c)
in as a logical operator
the in keyword can also be used to check to see if one string is “in” another string
the in expression is a logical expression that returns True or False and can be used in an if statement
fruit = ‘banana’
‘n’ in fruit
True
‘m’ in fruit
False
‘nan’ in fruit
True
if ‘a’ in fruit:
ind print(‘Found it!’)
Found it!
‘
string comparison
uppercase letters are less than lowercase letters
if word == ‘banana’ :
print(‘All right, bananas.’)
if word < ‘banana’:
print(‘Your word,’ + word + ‘, comes before banana.’)
elif word > ‘banana’:
print(‘Your word,’ + word + ‘, comes after banana.’)
else:
print(‘All right, bananas.’)
objects
variables that have capabilities that are grafted on or built into them
(strings are objects)
method
function that belongs to/built into an object
dir
lists methods available for an object
dir(object)
string functions
functions built into strings
invoke them by appending the function to the string variable
functions do not modify original string, they return a new string that been altered
string library
where the string functions are
.lower()
makes string lowercase
> > > greet = ‘Hello Bob’
zap = greet.lower( )
print(zap)
hello bob
> > > print(‘Hi There’.lower())
hi there
\n
new line
\t
new tab
'
puts single quote in a single-quoted string
"
puts double quote in a double-quoted string
:=
Walrus Operator (assignment expression operator) assigns variables in the middle of expressions