CSC 101 - Day 2

2024-09-07 11:36:13 -0400 EDT


Debugging Interlude

Debugging is arguably the most under-appreciated and under-taught skills in introductory programming; So debugging interludes are interspersed with within the course.

Firstly, to avoid having to debug at all:

Find Clues (look at error messages and use print statements to understand the problem)

Conditional Execution

Comparison Operators

there’s also Logic Operators: and, or and not; they work exactly the same as they do the english.

Now actual conditional statements. these are statements that will trigger or not trigger code if a condition is met

For example:


x = 2
y = 3

if x == y:
    print("x and y are equal")
    # plus any other code
else:
    print("x and y are not equal")
    # plus any other code

print("the condition statement is over")

In this block of code, x and y are checked if they are equal. if they are, all the code with the indent will be executed (e.i: “x and y are equal”). if they are not equal, that code will not be executed and instead the code indented after else (e.i: “x and y are not equal”), will be executed in its place (else will be executed whenever none of the conditions are met). After all the indented code is executed, regardless of it met the condition or not, it will then move on and execute the rest of the code.

You can chain multiple if statements together with elif statements.


x = 2
y = 1

if x == y:
    print("x and y are equal")
elif x > y:
    print("x is larger than y")
elif x < y:
    print("x is smaller than y")

You can nest conditions into each other as well.


x = 2
y = 1

if x == y:
    print("x and y are equal")
else:
    if x > y:
        print("x is larger than y")
    else x < y:
        print("x is smaller than y")

if you are having errors and you want something to execute in the errors place, nest your conditions in the try/except condition to catch it.


x = input('give me an x value:')
y = input('give me a y value:')

try:

    x = int(x)
    y = int(y)

    if x == y:
        print("x and y are equal")
    else:
        if x > y:
            print("x is larger than y")
        else x < y:
            print("x is smaller than y")
except:
    print("you need to give me numbers")

with this code, it will attempt to run the code indented after “try.” but if it comes up with an error, like the code trying to turn words into integers, it will run the code in except.