Skip to main content

Command Palette

Search for a command to run...

Week 4: Python Foundations

Updated
8 min read

This week I focused on learning Python; it's gonna take me at least another two weeks to get through the whole course. I'm close to finishing the basics; I just need to do the last workshop, lab, review, and quiz. There are 7 more THM modules I want to go over. Next week, I'll finish out the Python basics to see if I can make the packet sniffer and start the Network Services THM module. Anyways, here are my Python notes so far:

Integers and floats don't only store numeric data, they also store math. Integers and floats can be positive or negative. To add two integers, simply assign a number to a variable then add two variables like so:

int_1 = 20

int_2 = 20

sum_ints = int_1 + int_2

print('Integer Addition:', sum_ints)

In other words, you assign the addition of two variables to another variable, just use the plus operator. And use the minus operator when subtracting:

int_1 = 20

int_2 = 20

diff_ints = int_1 - int_2

print('Integer Subtraction:', diff_ints)

To multiply, use the asterisk operator. To divide, use the forward slash (/) operator. The same is done for floats. Also, if an integer and float are combined, a float is printed.

Then there's the modulo operator %, which returns the remainder when a value on the left is divided by the value on the right. Next, they explained that the two forward slashes (//) divide two numbers and return the greatest integer that's less than or equal to the result. So if it's a float, it still returns a float but only the greatest part, like 12.0 // 5.4 = 2 instead of 2.2222

To get the exponentiation, use the double asterisk (**) operator. Also, long infinite numbers are rounded, so there might be minor errors at the end. To round to a specific number of decimals, use round(int_1, x). The x is the number of decimals to request. For example:

int_1 = 3.567

rounded_int_1 = round(int_1, 1)

print(rounded_int_1) # 3.6

abs() = absolute value of a number

pow() = rasies number to power of another

Augmented assignments are when an operation is applied to a different value from the variable, and the result is stored in the same variable. In other words, it's to add without repeating the variable name. For example:

variable = value is the same as variable = variable value

my_var = 10

my_var += 5 (instead of my_var = my_var +5)

print(my_var) (prints 15)

Any operator can be used like that; also, if a string is used and then a (* = ) then it repeats the string however many times it is multiplied by.

Then I worked on building a bill splitter. I got confused at the halfway mark because I couldn't figure out how to print a float with a string. I went over last week's notes and read that a string can't concatenate with a number but that a number can be turned into a string by using str(). And it worked! Then I tried the next step with str(), but it wouldn't accept the answer so I had to use the f'Here's a string: {variable}' option.

Conditional statements have comparison operators, which compares values and returns a boolean value.

== checks if two values are equal

!= checks if two values aren't equal

> checks if the left value is greater than the right

< checks if the left value is less than the right

>= checks if the left value is greater than or equal to the right

<= checks if the left value is less than or equal to the right

Then there are the if statements, which have a condition that must be true for the code to run. The condition can be set to 'pass' as a placeholder. Indentations determine code blocks to signal what belongs where. Four spaces are normally recommended for indentations, but any amount can be used as long as they're used consistently.

There's also the else statement, which prints something else if the first statement is false. Example:

If condition: pass

else pass

Nothing else can be placed between if and else. To further extend the statement, a elif (else if) can be used after else.

Nested conditional statements help compare multiple values at once. For example, it can check two conditions before printing something.

Also, every value in Python has a built-in Boolean value for logical contexts. For example, None, False, Int 0, Float 0.0, and empty strings "" are considered falsy. All other values that are not zero numbers or empty strings are truthy. To check the bool value, simply use (bool(value)).

There are three Boolean operators in Python: 'and', 'or', and 'not'. These operators allow the combination of multiple expressions to create more complex decisions.

The 'and' operator is a short-circuit operator, which checks values left to right and only returns a truthy value if both conditions are true. Otherwise, it returns a falsy value. For example, is_citizen = True and age = 25 are both truthy values, so print(is_citizen and age) would print the true value of 25.

The 'or' operator, also a short-circuit, returns a truthy value as long as one of the values is true. For example, age = 9 and is_employed = false, then print(age or is_employed) would return 9.

The 'not' operator changes values to their opposite value so a false value would become true.

Then I built a movie ticket booking calculator. I forgot to place a colon after the if condition, but it was fixed easily. At some point I had to write an 'or' conditional but couldn't join a string to a bool until I used == instead of just the = sign. Also learned that parentheses can be used to group conditions and control the order they are followed.

Afterward, I was tasked with building a weather planner. Initially, I didn't use an elif branch cause I didn't really understand them. After reading the lesson on conditionals again, I understood that elif works by testing any number of conditions before arriving at a conclusion if all the conditions aren't satisfied. I also learned I can place regular if - else statements within an elif. And that if nothing is printing, then the code is following the lack of else statements. I had a lot of trouble because I forgot to add the last else condition to this block:

elif distance_mi > 1 and distance_mi <= 6:

if has_bike == True and is_raining != True:

print('True')

else:

print('False')

I thought it would just assume to print the opposite, but it is a string so to the computer there is no opposite. Anyways, here's the full code I wrote:

distance_mi = 2

is_raining = True

has_bike = False

has_car = False

has_ride_share_app = False

if distance_mi == 0:

print('False')

elif distance_mi <= 1 and is_raining != True:

print('True')

elif distance_mi > 1 and distance_mi <= 6:

if has_bike == True and is_raining != True:

print('True')

else:

print('False')

elif distance_mi > 6:

if has_car or has_ride_share_app:

print('True')

else:

print('False')

else:

print('False')

I'm very happy my code eventually passed. At first I didn't even think it was missing that else conditional and pressed check code out of habit, but it worked!

Then I went over the lesson on functions, which are reusable pieces of code like the print() function. And input() prompts the user for input. For example, age = ('What is your age?') will ask a user to input a response. Custom functions can also be written by using the keyword def, the name of the function, parentheses, and a colon, like so:

def greeting ():

print('Hi everyone! Today is a wonderful day to learn some coding!')

greeting() would then print the whole string.

There are also custom functions with parameters. For example, def sum (a,b): print(a + b). The a and b are parameters, which are placeholders for a value that will change. Those values, the ones you would assign to the parameters a or b, are called arguments. So an argument could be 3 or 4, etc.

The return keyword is used to exit the function and return a value. For example, if naming a custom sum something specific like my_sum = sum(4,4) then sum (a,b) has to say return a + b instead of print(a+b) in order for it to properly calculate the sum. Otherwise, it prints None.

Scope basically states the lifetime of a variable. The LEGB rule helps determine the scope of a variable:

Local Scope: variables defined in the functions or classes. In other words, the variable can only be accessed within that function or class. For example:

def my_function():

my_var = 10

print(my_var)

Enclosing Scope: variables defined in enclosing or nested functions can only be accessed from said nested function. The keyword nonlocal can make a non-local variable. For example, add the nonlocal keyword before the variable inside a nested function:

def inner_func():

nonlocal res

res = 'How are you?'

Global Scope: variables defined at the top level of the module or file. It means a variable can be accessed from anywhere. Local variables inside a function can also become global by using the global keyword. The keyword can also be used to modify a variable. For example, if the variable was set to 10 at the beginning and later wants to be changed inside a function, then just use global like so:

global my_var

my_var = 20

Built-in Scope: reserved names in Python for predefined functions, modules, keywords, and objects. Such as str(), type(), isinstance(), etc.