Hello, world!
Lecture 13 - Python Data Types, Boolean Logic, and Control Structures
16 October, 2024
int
(integer): whole numbers (e.g., 1, 2, 3)float
(floating-point number): numbers with decimal points (e.g., 1.0, 2.5, 3.14)str
(string): text (e.g., “Hello, world!”)bool
(boolean): logical values (e.g., True, False)list
: ordered, mutable collection of items (e.g., [1, 2, 3])tuple
: ordered, immutable collection of items (e.g., (1, 2, 3))dict
(dictionary): unordered collection of key-value pairs (e.g., {“name”: “Alice”, “age”: 25})set
: unordered collection of unique items (e.g., {1, 2, 3})x
, y
age
, name
, etcfor
, while
, class
)myVar
≠ myvar
)=
) to assign values to variables
x = 42
+
(addition)-
(subtraction)*
(multiplication)/
(division)//
(floor division)%
(modulus)**
(exponentiation)dtype
than expected, it will change int
to float
//
allows us to do “integer division” (aka “floor division”) and retain the int
data type, it always rounds down%
“modulus” operator gives us the remainder after divisionstring
'...'
) or double quotes ("..."
)"""This function adds two numbers"""
==
(equal)!=
(not equal)>
(greater than)<
(less than)>=
(greater than or equal to)<=
(less than or equal to)is
(identity)not
(negation)in
(membership)and
(logical and)or
(logical or)not
(logical not)and
operator returns True
if both operands are True
or
operator returns True
if at least one operand is True
not
operator returns True
if the operand is False
[]
)[1, 'two', [3, 4, 'five'], True, None, {'key': 'value'}]
len()
functionstart:stop:step
Note from the above that the start of the slice is inclusive and the end is exclusive
So my_list[1:3]
fetches elements 1 and 2, but not 3
Strings behave the same as lists and tuples when it comes to indexing and slicing
Remember, we think of them as a sequence of characters
append()
: add an item to the end of the listinsert()
: add an item at a specific positionremove()
: remove an item by valuepop()
: remove an item by indexreverse()
: reverse the list{}
)set()
functionupper()
: convert to uppercaselower()
: convert to lowercasestrip()
: remove leading and trailing whitespacereplace()
: replace a substringsplit()
: split the string into a listf-strings
which were introduced in Python 3.6f
out the front of your string and then you can include variables with curly-bracket notation {}
name = "Newborn Baby"
age = 4 / 12
day = 20
month = 3
year = 2020
template_new = f"Hello, my name is {name}. I am {age:.2f} years old. I was born on {day}/{month:02}/{year}."
template_new
'Hello, my name is Newborn Baby. I am 0.33 years old. I was born on 20/03/2020.'
:.2f
notation is a way of formatting the number to two decimal places:02
notation is a way of formatting the number to two digits, with leading zeros if necessary{}
)dict()
function{'name': 'Alice', 'age': 25, 'city': 'New York', 'country': 'USA'}
[]
, ()
, and {}
respectivelylist()
, tuple()
, and set()
functions{}
or dict()
""
or str()
True
or False
if
: execute a block of code if a condition is True
elif
: execute a block of code if the previous condition is False
and the current condition is True
else
: execute a block of code if all previous conditions are False
if condition:
elif
statementselse
statementname = "Danilo"
if name.lower() == "danilo":
print("That's my name too!")
elif name.lower() == "juan":
print("That's a nice name!")
else:
print(f"Hello {name}! That's a cool name!")
print("Nice to meet you!")
That's my name too!
Nice to meet you!
elif
and else
blocks are optionalelif
blocks as you wantif
statement evaluates the condition name.lower() == "danilo"
True
, the code block under the if
statement is executedFalse
, the code block under the elif
statement is executedFalse
, the code block under the else
statement is executedprint("Nice to meet you!")
statement is executed regardless of the conditionif
statements inside other if
statementsif
statements to execute a single line of code based on a conditionvalue = true_value if condition else false_value
'short list'
False
:
None
False
0
, 0.0
, 0j
)[]
, ()
, {}
, ""
)True
item
variable takes on each value in the sequence
in turnsequence
can be a list, tuple, set, dictionary, range, or string:
ends the first line of the loopitem
variable can be any name you wantrange()
range()
range()
gives you a sequence of integers up to some value (non-inclusive of the end-value) and is typically used for loopingrange()
function can take up to three arguments: start
, stop
, and step
start
is 0
step
is 1
stop
value is non-inclusiverange()
function is very useful for creating loops that iterate a specific number of timesfor
loops inside other for
loops(1, 'a')
(1, 'b')
(1, 'c')
(2, 'a')
(2, 'b')
(2, 'c')
(3, 'a')
(3, 'b')
(3, 'c')
while
loopswhile
loops allow us to execute a block of code as long as a condition is True
while condition:
n -= 1
statement decrements the value of n
by 1n
is less than or equal to 0[expression for item in sequence]
if
statement to filter the items[expression for item in sequence if condition]
def
keyworddef function_name(parameters):
, then the code block (indented)return
statement exits the function and returns a valuename
variable is a parametergreet("Alice")
statement calls the function with the argument "Alice"
print()
, len()
)'My name is Danilo'
lambda
keywordnumpy
and pandas
📊