For Loops

  • A for loop is used in python for iterating over a sequence of code.
  • Through using a for loop, we can execute a set of commands that are in a list or set.
  • Here is an example
vegetables = ["🥒", "🥑", "🥕"]
for x in vegetables:
  print(x)
🥒
🥑
🥕

Looping Through a String

  • Even strings are iterable objects and contain a sequence of characters
  • Here in an example
for x in "avocado":
  print(x) 
a
v
o
c
a
d
o

The Break Statement

  • A break statement can aid us in stopping a loop before it has loops all the items.
  • Here is an example
vegetables = ["🥒", "🥑", "🥕"]
for x in vegetables:
  print(x)
  if x == "🥑":
    break
🥒
🥑

For Loops in Javascript

  • For Loops that are iterated over arrays can be in executed in Javascript in addition to Python.
  • Here is an example
%%javascript
const fruits = ['apple', 'banana', 'cherry'];

for (let i = 0; i < fruits.length; i++) {
    console.log(fruits[i]);
}
<IPython.core.display.Javascript object>

Looping Through a String in Javascript

  • This Loop is used to help iterate through every character in the string but in javascript
  • Here is an example
%%javascript
const str = "Hello, World!";

for (let i = 0; i < str.length; i++) {
    console.log(str[i]);
}
<IPython.core.display.Javascript object>

Popcorn Hack #1

  • This first hack is in Javascript and allows you to count from 0 to 4.
  • Through using this simple hack you can utilize for loops and create an array of numbers
%%javascript
for (let i = 0; i < 5; i++) {
    console.log(i);
}
<IPython.core.display.Javascript object>

Popcorn Hack #2

  • The second hack is the use of code to make an array of fruits using Python
  • Through this hack you can use minimal code to list your favorite things
fruits = ['🍎', '🍌', '🍒']

for fruit in fruits:
    print(fruit)
🍎
🍌
🍒

Homework

  • Try to add in two of the loops into your code, one in python and one in javascript.
  • This will help build your understanding on loops in both javascript and python
  • Additionally, try looping through a dictionary in order to be more creative with your code and personalize it
person = {'name': 'Arshia', 'age': 16}

# Looping through keys
for key in person:
    print(key, person[key])

# Looping through values
for value in person.values():
    print(value)

# Looping through keys and values
for key, value in person.items():
    print(key, value)

name Arshia
age 16
Arshia
16
name Arshia
age 16