Data Science Explorer

[Basic Grammar] Python For Loops 본문

Python

[Basic Grammar] Python For Loops

grace21110 2023. 10. 21. 11:57
반응형

A For Loop is used for iterating over a sequence (that is either a list, a tuple, a dictionary, a set, or  a string). In other words, it repeats the same function. 


Example 

Print each color in a color list. 

colors = ["blue", "white", "black"] 
for x in colors: 
	print (x)

** When you use for loops, dont' forget ":" and be careful with the indentation! **

 

  • Looping Through a String 

Example 

Loop through the letters in the word "blue". 

for x in "blue":
  print(x)

 

  • The break statement 

It is used to stop the loop. 

 

Example 

Exit the loop when x is "white".

colors = ["blue", "white", "black", "red"] 
for x in colors: 
	print(X)
    	if x == "white":
    		break

 

  • The continue statement 

When you use continue statement, you will go to the next (skipping the relevant item that is true to the if statement)

 

Example 

Do not print americano.

coffee = ["latte", "americano", "matcha latte"]
for x in coffee:
  if x == "americano":
    continue
  print(x)

 

  • The range () function 

The range function returns a sequence of numbers, staring from 0 by default, and increments by 1 (by default). 

 

Example 

for x in range (7)
	print(x)

It gives a result as 0 1 2 3 4 5 because it always starts from 0 and ends at a specified number.

 

Example 

for x in range(2, 6):
  print(x)

This code gives you result of 2 3 4 5, starting from 2. 

 

Example 

Increment the sequence with 3 (default is 1). 

for x in range(2, 65, 3):
  print(x)

 

  • Else in For Loop 

Example 

Print all numbers from 0 to 5, and print a message when the loop has ended. 

for x in range (6): 
	print (x) 
else: 
	print("Finally finished!")

** If the loop is stopped by a break statement, the else block will not be executed.**

 

Example 

Break the loop when x is 8, and see what happens with the else block.

for x in range (10):
	if x == 8: break 
    	print (x)
    
else: 
	print("Finally finished!")

 

  • Nested Loops 

Example 

adj = ["green", "big", "tasty"]
fruits = ["apple", "blueberry", "cherry"]

for x in adj:
  for y in fruits:
    print(x, y)

Answer

green apple
green blueberry
green cherry
big apple
big blueberry
big cherry
tasty apple
tasty blueberry
tasty cherry

 

  • The pass statement 

To avoid getting an error, we can use pass statement when for loops is empty. 

 

Example

for x in [0, 1, 2]:
  pass

 

Exercises 

1. Write a Python program that prints the first 10 even numbers. Use a for loop to generate and print the numbers.

for x in range (2, 21, 2):
	print(x)

 

2. Create a Python script that calculates the sum of all numbers from 1 to 100. Use a for loop to iterate through the numbers and calculate the sum.

total = 0
for i in range(1, 101):
    total += i
print("The sum of numbers from 1 to 100 is:", total)

3. Write a Python program that uses a for loop to search for a specific element, target, in a list. If the target is found, print its index and exit the loop using the break statement. If the target is not found, print "Target not found."

 

numbers = [2, 4, 6, 8, 10]
target = 6

for index, num in enumerate (numbers): 
	if num == target: 
    		print (f"Target {target} found at index {index}.")
        	break 
        
else: 
	print ("Target not found.")

** "f": The string is marked as an f-string by adding the "f" prefix before the opening double quotation mark. ** 

 

'Python' 카테고리의 다른 글

[Basic Grammar] Python Lambda  (1) 2023.10.21
[Basic Grammar] Python Functions  (0) 2023.10.21
[Basic Grammar] Python While Loops  (0) 2023.10.20
[Basic Grammar] Python If ... Else  (0) 2023.10.20
[Basic Grammar] Python Casting  (0) 2023.10.20