Nested Loops/If Statements, Try/Except, Iteration through Recursion

Overview

You can add loops and if statements inside loops as well

This can check each element of a list/dictionary, each character in a string, loop through an element, etc.

With Try/Except, you can try to run an operation and use except to check for a specific error, in which case you run certian code

Finally, recursion is when you call a function inside of a function to have it run repeatedly every time it is called

Nested if statements

nums = [1, 2, 3, 4, 5]

for num in nums:
    if num == 2:
        print("This is the number two")
    else:
        print(num)
1
This is the number two
3
4
5
%%js
const nums = [1, 2, 3, 4, 5];

for (const num of nums) {
    if (num === 2) {
        console.log("This is the number two");
    } else {
        console.log(num);
    }
}
<IPython.core.display.Javascript object>

Nested for loops

names = ["John", "Abraham"]

for name in names:
    for letter in name:
        print(letter)
    print("Next:")
J
o
h
n
Next:
A
b
r
a
h
a
m
Next:
%%js
const names = ["John", "Abraham"];

for (const name of names) {
    for (const letter of name) {
        console.log(letter);
    }
    console.log("Next:");
}
<IPython.core.display.Javascript object>

Code Breakdown

  • The first example creates a for loop and checks if the value ‘num’ is 2
  • If ‘num’ is 2, then it prints a special message
  • Otherwise, it just prints the number

  • The second example has a list of names
  • The first for loop goes through each element in the list
  • The second for loop runs for each iteration of the main for loop and gives each element of the element
  • Between loops, we print ‘Next:’

Using try/except in a for loop

nums = [1, 2, 4, 7, 0, 4]

for num in nums:
    try: 
        print((10/num))
    except ZeroDivisionError:
        print("You cannot divide by 0")
10.0
5.0
2.5
1.4285714285714286
You cannot divide by 0
2.5
%%js
const nums = [1, 2, 4, 7, 0, 4];

for (const num of nums) {
    try {
        console.log(10 / num);
    } catch (error) {
        if (error instanceof RangeError) {
            console.log("You cannot divide by 0");
        }
    }
}
<IPython.core.display.Javascript object>

Code breakdown:

  • In this scenario, we create a list of numbers and a for loop that wants to divide 10 by each number
  • We use try and except to check for a specific error, in this case ZeroDivisionError, and run something if we encounter it

Recursion

def factorial(n):
    if n == 0:
        return 1
    else:
        return n * factorial(n - 1)

result = factorial(7)
print(f"Factorial of 7 is", result)
Factorial of 7 is 5040
%%js
function factorial(n) {
    if (n === 0) {
        return 1;
    } else {
        return n * factorial(n - 1);
    }
}

const result = factorial(7);
console.log(`Factorial of 7 is ${result}`);
<IPython.core.display.Javascript object>

Code Breakdown

  • We create a function that returns the factorial of a given number
  • At the end of the function, it calls itself in order to continue giving the factorial
  • When the number gets to 0, it will return 1 and end the ‘loop’

Hack #1 While loops

Create a python script that asks a user for a password in the terminal, then if the password is correct, it prints out that the password is correct.

If the password is incorrect it asks for the password again.

Tips

Use a while loop and if statements to check if the password is correct,

If it is correct, then make the condition of the while loop false

How to do user input in python

You first must have a variable or be declaring a variable when asking for user input

You also have to have a prompt for the user

Syntax looks like this

name = input("Enter your name: ")

print ("hello,", name)
hello, Arnav

How to do if/else statements in python

If statements are simply made up of conditions and blocks of code

If the condition is true, then the code is run

if it is not, then the else code is run

x = 5
y = 2

if x + y == 7:
    print("true")

else:
    print("false")
true

Hack #2 For loops

Create python script that asks for a user’s name

Then iterate through the name and print it out letter by letter through the terminal

Tips

Use a for loop, this one should be pretty easy

Hack #3 For loops with lists

Create a python script that has a list of at least 7 different fruits

then create a for loop that iterates through that list and prints out each fruit seperate to the terminal

tips

refer to 3.8.4 for basics on how to do this

For Loop Meme</img> –>