Notice: This page requires JavaScript to function properly.
Please enable JavaScript in your browser settings or update your browser.
Lernen For Loop | Introduction to Python 2/2
Introduction to Python for Data Analysis

book
For Loop

We use loops if we want to repeat any action n-times.

Look at the example!

# Decreasing prices by 1
prices = [3, 5, 6, 2, 7, 8]

for i in prices:
print(i, end = ' ')
12345
# Decreasing prices by 1 prices = [3, 5, 6, 2, 7, 8] for i in prices: print(i, end = ' ')
copy

end = ' ' means that the result will be written in one row (not column).

Look at the table to understand how to minimize the writing of mathematical operators!

FormulaHow to minimize
a = a + 1a += 1
a = a - 1a -= 1
a = a * 2a *= 2
a = a / 2a /= 2
Aufgabe

Swipe to start coding

Update subscription prices according to discounts.

  1. Set the for loop to work with the prices using the i iterator.
  2. Set the condition if the element of the list is greater than 30.
  3. Set the 25% discount if the price is greater than 30.
  4. Decrease the i by 3.
  5. Print the prices.

Lösung

prices = [20.35, 30.5, 12.65, 8.5, 6.5, 5.8, 40.5]
print(prices)
prices_upd = []

# Set the for loop to work with the prices
for i in prices:
# Set the condition if the element of the list is greater than 30
if i > 30:
# Set the 25% discount
i *= 0.75
else:
# Decrease the price by 3
i -= 3
# Appending values to the upd list
prices_upd.append(i)

# Print the updated subscription prices to see the changes
print(prices_upd)

War alles klar?

Wie können wir es verbessern?

Danke für Ihr Feedback!

Abschnitt 2. Kapitel 5
prices = [20.35, 30.5, 12.65, 8.5, 6.5, 5.8, 40.5]
print(prices)
prices_upd = []

# Set the for loop to work with the prices
for ___ in ___:
# Set the condition if the element of the list is greater than 30
if ___:
# Set the 25% discount
i *= ___
else:
# Decrease the price by 3
i ___ 3
# Appending values to the upd list
prices_upd.append(i)

# Print the updated subscription prices to see the changes
print(___)

Fragen Sie AI

expand
ChatGPT

Fragen Sie alles oder probieren Sie eine der vorgeschlagenen Fragen, um unser Gespräch zu beginnen

some-alt