Snippets Collections
JavaScript

for (let i=0; i < arrayName.length; i++){
  console.log(arrayName[i])
}

i.e.):

movies = ['legally blonde', 'Ms. & Ms. Smith', 'The Incredibles'];

for (let i=0; i < movies.length; i++){
  console.log(movies[i])
}

Python

for singular_array_name in array_name_pluralized:
	print(singular_array_name)

i.e.):

movies = ['legally blonde', 'Ms. & Ms. Smith', 'The Incredibles']

for movie in movies:
	print(movie)
# numpy and matplotlib imported, seed set

# Simulate random walk 500 times
all_walks = []
for i in range(500) :
    random_walk = [0]
    for x in range(100) :
        step = random_walk[-1]
        dice = np.random.randint(1,7)
        if dice <= 2:
            step = max(0, step - 1)
        elif dice <= 5:
            step = step + 1
        else:
            step = step + np.random.randint(1,7)
        if np.random.rand() <= 0.001 :
            step = 0
        random_walk.append(step)
    all_walks.append(random_walk)

# Create and plot np_aw_t
np_aw_t = np.transpose(np.array(all_walks))

# Select last row from np_aw_t: ends
ends = np_aw_t[-1, :]

# Plot histogram of ends, display plot
plt.hist(ends)
plt.show()
# Numpy is imported; seed is set

# Initialize all_walks (don't change this line)
all_walks = []

# Simulate random walk 10 times
for i in range(10):

    # Code from before
    random_walk = [0]
    for x in range(100) :
        step = random_walk[-1]
        dice = np.random.randint(1,7)

        if dice <= 2:
            step = max(0, step - 1)
        elif dice <= 5:
            step = step + 1
        else:
            step = step + np.random.randint(1,7)
        random_walk.append(step)

    # Append random_walk to all_walks
    all_walks.append(random_walk)

# Print all_walks
print(all_walks)


#####################################################################
# numpy and matplotlib imported, seed set

# Simulate random walk 250 times
all_walks = []
for i in range(250) :
    random_walk = [0]
    for x in range(100) :
        step = random_walk[-1]
        dice = np.random.randint(1,7)
        if dice <= 2:
            step = max(0, step - 1)
        elif dice <= 5:
            step = step + 1
        else:
            step = step + np.random.randint(1,7)

        # Implement clumsiness
        if np.random.rand() <= 0.001 :
            step = 0

        random_walk.append(step)
    all_walks.append(random_walk)

# Create and plot np_aw_t
np_aw_t = np.transpose(np.array(all_walks))
plt.plot(np_aw_t)
plt.show()


# Numpy is imported, seed is set

# Initialization
random_walk = [0]

for x in range(100) :
    step = random_walk[-1]
    dice = np.random.randint(1,7)

    if dice <= 2:
        step = max(0, step - 1)
    elif dice <= 5:
        step = step + 1
    else:
        step = step + np.random.randint(1,7)

    random_walk.append(step)

# Import matplotlib.pyplot as plt
import matplotlib.pyplot as plt

# Plot random_walk
plt.plot(random_walk)

# Show the plot
plt.show()
# Numpy is imported, seed is set

# Initialize random_walk
random_walk = [0]

# Complete the ___
for x in range(100) :
    # Set step: last element in random_walk
   
    step = random_walk[-1]

    # Roll the dice
    dice = np.random.randint(1,7)

    # Determine next step
    if dice <= 2:
        step = step - 1
    elif dice <= 5:
        step = step + 1
    else:
        step = step + np.random.randint(1,7)

    # append next_step to random_walk
    random_walk.append(step)

# Print random_walk
print(random_walk)

#Not Going below zero
# Numpy is imported, seed is set

# Initialize random_walk
random_walk = [0]

for x in range(100) :
    step = random_walk[-1]
    dice = np.random.randint(1,7)

    if dice <= 2:
        # Replace below: use max to make sure step can't go below 0
        step = max(0, step - 1)
    elif dice <= 5:
        step = step + 1
    else:
        step = step + np.random.randint(1,7)

    random_walk.append(step)

print(random_walk)
# Numpy is imported, seed is set

# Starting step
step = 50
# Roll the dice
dice = np.random.randint(1,7)
# Finish the control construct
if dice <= 2 :
    step = step - 1
elif dice <= 5 :
    step = step + 1
else:
    step = step + np.random.randint(1,7)

# Print out dice and step
print(dice)
print(step)
# Import numpy as np
import numpy as np

# Set the seed
np.random.seed(123)

# Generate and print random float
print(np.random.rand())

#Roll The Dice
# Import numpy and set seed
import numpy as np
np.random.seed(123)

# Use randint() to simulate a dice
print(np.random.randint(1,7))
# Use randint() again
print(np.random.randint(1,7))


# Import cars data
import pandas as pd
cars = pd.read_csv('cars.csv', index_col = 0)

# Use .apply(str.upper)


cars['COUNTRY'] = cars['country'].apply(str.upper)
print(cars)
# Import cars data
import pandas as pd
cars = pd.read_csv('cars.csv', index_col = 0)

# Adapt for loop
for lab, row in cars.iterrows() :
    print(lab + ": " + str(row['cars_per_cap']))

#Something new

# Import cars data
import pandas as pd
cars = pd.read_csv('cars.csv', index_col = 0)

# Code for loop that adds COUNTRY column
for lab, row in cars.iterrows():
    cars.loc[lab,'COUNTRY'] = row['country'].upper()


# Print cars
print(cars)
#Iterating over a Pandas DataFrame is typically done with the iterrows()
# Import cars data
import pandas as pd
cars = pd.read_csv('cars.csv', index_col = 0)

# Iterate over rows of cars
for lab,row in cars.iterrows():
    print(lab)
    print(row)
# Import numpy as np

import numpy as np
#for x in my_array : #in 1D Numpy array
#for x in np.nditer(my_array) : #for 2D Numpy array

# For loop over np_height

for x in np_height:
    print(str(x) + " inches")

# For loop over np_baseball
for x in (np.nditer(np_baseball)):
    print(x)
# Definition of dictionary
europe = {'spain':'madrid', 'france':'paris', 'germany':'berlin',
          'norway':'oslo', 'italy':'rome', 'poland':'warsaw', 'austria':'vienna' }
          
# Iterate over europe
for key, value in europe.items() :
    print('the capital of ' + str(key) + ' is ' + str(value))
# house list of lists
house = [["hallway", 11.25], 
         ["kitchen", 18.0], 
         ["living room", 20.0], 
         ["bedroom", 10.75], 
         ["bathroom", 9.50]]
         
# Build a for loop from scratch
for x in house :
    #x[0] to access name of room
    #x[1] to access area in sqm
    print('the ' + x[0] + " is " + str(x[1]) + " sqm")
1.# For-Else Syntax

2.for item in seq:
    3.statement 1
    4.statement 2
    5.if <cond>:
        6.break
7.Else:
8.Example:
     9.birds = ['Belle', 'Coco', 'Juniper', 'Lilly', 'Snow']
10.ignoreElse = False


11.for theBird in birds:
    12.print(theBird )
    13.if ignoreElse and theBird is 'Snow':
        14.break
15.else:
    16.print("No birds left.")
                              
                                
#make two lists:
1.num_list = [1, 2, 3]
2.alpha_list = ['a', 'b', 'c']

#use for loop for 1st list:
3.for number in num_list:
#print the list    
4.print(number)
#use for loop for @nd list:    
5.for letter in alpha_list:

star

Sat Jan 15 2022 19:01:04 GMT+0000 (Coordinated Universal Time)

#python #javascript #array #list #forloop #iteration
star

Fri Nov 26 2021 10:49:17 GMT+0000 (Coordinated Universal Time)

#list #forloop #for #loop #dicegame #matplotlib #[plot #graph
star

Fri Nov 26 2021 10:42:38 GMT+0000 (Coordinated Universal Time)

#list #forloop #for #loop #dicegame
star

Fri Nov 26 2021 10:06:16 GMT+0000 (Coordinated Universal Time)

#list #forloop #for #loop ##dictionary
star

Fri Nov 26 2021 09:45:49 GMT+0000 (Coordinated Universal Time)

#list #forloop #for #loop ##dictionary
star

Thu Nov 25 2021 17:01:18 GMT+0000 (Coordinated Universal Time)

#list #forloop #for #loop ##dictionary
star

Thu Nov 25 2021 16:48:58 GMT+0000 (Coordinated Universal Time)

#list #forloop #for #loop ##dictionary
star

Thu Nov 25 2021 16:42:08 GMT+0000 (Coordinated Universal Time)

#list #forloop #for #loop ##dictionary
star

Thu Nov 25 2021 16:28:23 GMT+0000 (Coordinated Universal Time)

#list #forloop #for #loop ##dictionary
star

Thu Nov 25 2021 16:16:28 GMT+0000 (Coordinated Universal Time)

#list #forloop #for #loop ##dictionary
star

Thu Nov 25 2021 15:55:42 GMT+0000 (Coordinated Universal Time)

#numpy #booleans_in_numpy #list #forloop #for #loop
star

Tue Apr 21 2020 05:48:50 GMT+0000 (Coordinated Universal Time)

#python #python #loops #forloop #forelse
star

Tue Mar 31 2020 05:29:39 GMT+0000 (Coordinated Universal Time)

#python #python #loops #forloop #nestedfor loop

Save snippets that work with our extensions

Available in the Chrome Web Store Get Firefox Add-on Get VS Code extension