0% found this document useful (0 votes)
5 views

vertopal.com_workingwithlistpart1

The document provides an overview of using loops in Python, specifically focusing on the for loop to iterate through lists and perform actions on each element. It includes examples of printing messages, handling indentation errors, and creating numerical lists using the range() function. Additionally, it covers list comprehensions for more concise code and presents exercises to reinforce the concepts learned.

Uploaded by

Rasheal Mehdi
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
5 views

vertopal.com_workingwithlistpart1

The document provides an overview of using loops in Python, specifically focusing on the for loop to iterate through lists and perform actions on each element. It includes examples of printing messages, handling indentation errors, and creating numerical lists using the range() function. Additionally, it covers list comprehensions for more concise code and presents exercises to reinforce the concepts learned.

Uploaded by

Rasheal Mehdi
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 9

# Uptil now, you learned how to make a simple list, and you learned to

work with the individual elements in a list.


# you’ll learn how to loop through an entire list using just a few
lines of code, regardless of how long the list is.
# Looping allows you to take the same action, or set of actions, with
every item in a list.
#As a result, you’ll be able to work efficiently with lists of any
length, including those with thousands or even
# millions of items.

######Looping Through an Entire List######


# You’ll often want to run through all entries in a list, performing
the same task with each item.
# For example, in a game you might want to move every element on the
screen by the same amount.
# In a list of numbers, you might want to perform the same
statistical operation on every element.
# Or perhaps you’ll want to display each headline from a list of
articles on a website.
#When you want to do the same action with every item in a list, you
can use Python’s for loop.

#Let’s use a for loop to print out each name in a list of magicians:
magicians = ['alice', 'david', 'carolina']
for magician in magicians:
print(magician)

alice
david
carolina

#Looping is important because it’s one of the most common ways a


computer automates repetitive tasks.
#If you have a million items in your list, Python repeats these steps
a million times
#However, it’s helpful to choose a meaningful name that represents a
single item from the list.
#examples such as:
#for cat in cats:
#for dog in dogs:
#for item in list_of_items:

###########Doing More Work Within a for Loop############

#Let’s build on the previous example by printing a message to each


magician,
# telling them that they performed a great trick

magicians = ['alice', 'david', 'carolina']


for magician in magicians:
print(f"{magician.title()}, that was a great trick!")
Alice, that was a great trick!
David, that was a great trick!
Carolina, that was a great trick!

###Let’s add a second line to our message, telling each magician that
we’re looking forward to their next trick:

magicians = ['alice', 'david', 'carolina']


for magician in magicians:
print(f"{magician.title()}, that was a great trick!")
print (f"I can't wait to see your next trick,{magician.title()}.\n")

Alice, that was a great trick!


I can't wait to see your next trick,Alice.

David, that was a great trick!


I can't wait to see your next trick,David.

Carolina, that was a great trick!


I can't wait to see your next trick,Carolina.

###Doing Something After a for Loop####


#What happens once a loop has finished executing? for Usually, you’ll
want to summarize a
# block of output or move on to other work that your program must
accomplish.
#Let’s write a thank you to the group of magicians as a whole,
thanking them for putting on
# an excellent show. To display this group message after all of the
individual messages
# have been printed, we place the thank you message after the for
loop,
# without indentation:

magicians = ['alice', 'david', 'carolina']

for magician in magicians:


print(f"{magician.title()}, that was a great trick!")
print(f"I can't wait to see your next trick,{magician.title()}.\n")
print("Thank you, everyone. That was a great magic show!")

Alice, that was a great trick!


I can't wait to see your next trick,Alice.

David, that was a great trick!


I can't wait to see your next trick,David.

Carolina, that was a great trick!


I can't wait to see your next trick,Carolina.
Thank you, everyone. That was a great magic show!

###Indentational Errors####

##Forgetting to Indent
#Error 1
#magicians = ['alice', 'david', 'carolina']
#for magician in magicians:
#print(magician)
# Error 2: Forgetting to Indent Additional Lines
#This is a logical error. The syntax is valid Python code, but the
code does not
# produce the desired result because a problem occurs in its logic.
# Sometimes your loop will run without any errors but won’t
#produce the expected result. This can happen when you’re
#trying to do several tasks in a loop and you forget to indent
# some of its lines.
#magicians = ['alice', 'david', 'carolina']
#for magician in magicians:
#print(f"{magician.title()}, that was a great trick!")
#print(f"I can't wait to see your next trick,{magician.title()}.\n")
#Error 3: Indenting Unnecessarily
#If you accidentally indent a line that doesn’t need to be indented,
# Python informs you about the unexpected indent
#message = "Hello Faculty members!"
#print(message)
#Error 4: Indenting Unnecessarily After the Loop

Cell In[10], line 21


print(message)
^
IndentationError: unexpected indent

# Another logical Error

for magician in magicians:


print(f"{magician.title()}, that was a great trick!")
print(f"I can't wait to see your next trick, {magician.title()}.\n")
#print("Thank you everyone, that was a great magic show!")

Alice, that was a great trick!


I can't wait to see your next trick, Alice.

Thank you everyone, that was a great magic show!


David, that was a great trick!
I can't wait to see your next trick, David.

Thank you everyone, that was a great magic show!


Carolina, that was a great trick!
I can't wait to see your next trick, Carolina.

Thank you everyone, that was a great magic show!

###Error 5: Forgetting the colons

#The colon at the end of a for statement tells Python to interpret the
next line as the start of a loop.

#magicians = ['alice', 'david', 'carolina']


#for magician in magicians
#print(magician)

####EXERCISE PIZZA####
# List of favorite pizzas

favorite_pizzas = ["Chicken Tikka", "Pepperoni", "BBQ Chicken"]

# For loop to print a sentence for each pizza


for pizza in favorite_pizzas:
print(f"I like {pizza} pizza.")

I like Chicken Tikka pizza.


I like Pepperoni pizza.
I like BBQ Chicken pizza.

# Final statement outside the loop


print("\nI really love pizza!")

I really love pizza!

####EXERCISE Animals

# List of animals with a common characteristic


animals = ["Dog", "Cat", "Rabbit"]

# For loop to print a statement for each animal


for animal in animals:
print(f"A {animal.lower()} would make a great pet.")
# Final statement outside the loop
print("\nAny of these animals would make a great pet!")

A dog would make a great pet.


A cat would make a great pet.
A rabbit would make a great pet.

Any of these animals would make a great pet!

###Making Numerical Lists####


#Many reasons exist to store a set of numbers. For example, you’ll
need to keep track of
# the positions of each character in a game, and you might want to
keep track of a player’s high scores as well.
##In data visualizations, you’ll almost always work with sets of
numbers, such as temperatures, distances,
##population sizes, or latitude and longitude values, among other
types of numerical sets.
#Lists are ideal for storing sets of numbers, and Python provides a
variety of tools to help
# # you work efficiently with lists of numbers.

############Using the range() Function#############


#Python’s range() function makes it easy to generate a series of
numbers.
# For example, you can use the range() function to print a series of
numbers.

for value in range(1, 5):


print(value)

1
2
3
4

# it will read from First number to second number assigned in small


brackets

for value in range(1,6):


print(value)

1
2
3
4
5

##Now lets make the list of numbers


# We can use list() to convert that same set of numbers into a list

numbers = list(range(1, 6)) # List () function is applied over here.


# to covert the number to the list.

[1, 2, 3, 4, 5]

#We can also use the function to tell Python to skip range() numbers
in a given range.
# If you pass a third argument to range(), Python uses that value as a
step size
# when generating numbers.
##For example, here’s how to list the even numbers between 1 and 15

even_numbers = list(range(2, 15, 2))


print(even_numbers)
[2, 4, 6, 8, 10, 12, 14]

#For example, consider how you might make a list of the first 10
square numbers
# (that is, the square of each integer from 1 through 10).
# In Python, two asterisks (**) represent exponents.
# Here’s how you might put the first 10 square numbers into a list

squares = [] # empty list with the name "squares"


for value in range(1, 11): #We tell python to loop for each value from
1 to 10
square = value ** 2 # inside the loop, the current value is raised
to second power and assigned to variable square
squares.append(square) # Each new value of square is then appended to
the list squares
print(squares) #Finally, when the loop has finished running, the list
of squares is printed.

#To write this code more concisely, omit the temporary variable square
and append
# each new value directly to the list.

squares = []
for value in range(1,11):
squares.append(value**2)
print(squares) # The result will be same, but there is no temporary
variable over here such as "square"

#########Simple Statistics with a List of Numbers#########

digits = [1, 2, 3, 4, 5, 6, 7, 8, 9, 0]

min(digits)

max(digits)

sum(digits)

#NOTE: The examples in this section use short lists of numbers


#that fit easily on the page. They would work just as well
#if your list contained a million or more numbers.
##List Comprehensions
#Making the list of two to three line of codes
#The approach described earlier for generating the list squares
consisted of
# using three or four lines of code.
#A list comprehension allows you to generate this same list in just
one line of code.
#A list comprehension combines the loop and for the creation of new
elements into one line,
# and automatically appends each new element.
# List comprehensions are not always presented to beginners.

squares = [value**2 for value in range(1, 11)] #descriptive name of


variable=square bracket start followed by expression that is value**2,
for loop with no colons
print(squares)

##EXERCISE 1
#Counting to Twenty: Use a for loop to print the numbers from 1 to 20,
inclusive.
# For loop to print numbers from 1 to 20
for number in range(1, 21):
print(number)

# EXERCISE 2
# One Million: Make a list of the numbers from one to one million,
and then use a for
# loop to print the numbers. (If the output is taking too long, stop
it by pressing
# CTRL-C or by closing the output window.)
# List of numbers from 1 to 1 million
#numbers = list(range(1, 1000001))
# For loop to print each number
#for number in numbers:
#print(number)

#EXERCISE 3 Make a list of the numbers from one to one million, and
# then use min() and max() to make sure your list actually starts at
one and
# ends at one million. Also, use the sum() function to see how quickly

# Python can add a million numbers.


# List of numbers from 1 to 1 million

numbers = list(range(1, 1000001))


# Check the minimum and maximum values
print(f"The minimum number in the list is: {min(numbers)}")
print(f"The maximum number in the list is: {max(numbers)}")
# Calculate the sum of all numbers in the list
total_sum = sum(numbers)
print(f"The sum of all numbers from 1 to 1 million is: {total_sum}")

The minimum number in the list is: 1


The maximum number in the list is: 1000000
The sum of all numbers from 1 to 1 million is: 500000500000

# EXERCISE 4: Odd Numbers: Use the third argument of the range()


function to make a list of
# the odd numbers from 1 to 20. Use a for loop to print each number
# List of odd numbers from 1 to 20
odd_numbers = list(range(1, 21, 2))

# For loop to print each odd number


for number in odd_numbers:
print(number)

1
3
5
7
9
11
13
15
17
19

# EXERCISE 5: Threes: Make a list of the multiples of 3, from 3 to 30.


Use a for loop to print the
# numbers in your list.
# List of multiples of 3 from 3 to 30

multiples_of_three = list(range(3, 31, 3))

# For loop to print each multiple of 3


for number in multiples_of_three:
print(number)

3
6
9
12
15
18
21
24
27
30

# EXERCISE 6:
# Cubes: A number raised to the third power is called a cube. For
example, the cube of 2
# is written as 2**3 in Python. Make a list of the first 10 cubes
# (that is, the cube of each integer from 1 through 10), and use a for
loop to print out
# the value of each cube.
# List of the first 10 cubes

cubes = [number**3 for number in range(1, 11)]


# For loop to print each cube
for cube in cubes:
print(cube)

1
8
27
64
125
216
343
512
729
1000

# EXERCISE 7: Cube Comprehension: Use a list comprehension to generate


a list
# of the first 10 cubes.

# List of the first 10 cubes using list comprehension


cubes = [number**3 for number in range(1, 11)]
# Print the list of cubes
print(cubes)

[1, 8, 27, 64, 125, 216, 343, 512, 729, 1000]

You might also like