Notice: This page requires JavaScript to function properly.
Please enable JavaScript in your browser settings or update your browser.
Oppiskele While Loop | Control Flow
Introduction to Data Analysis in Python
course content

Kurssisisältö

Introduction to Data Analysis in Python

Introduction to Data Analysis in Python

1. Basics
2. Data Types
3. Control Flow
4. Functions and Modules
5. Introduction to NumPy

book
While Loop

While loop is another type of loops. It performs the same, but the construction of the loop differs.

We use a special variable, i.e. counter, to collect elements of the list. If you want to count the sum of the numbers from 1 to 10 using the while loop, you also have to create a variable that collects and updates the sum after each iteration.

We use len() when creating a while loop function to create a suitable iterable.

123456789
prices = [100, 458, 231, 378] i = 0 counter = 0 while i < len(prices): counter += prices[i] i += 1 print(counter)
copy
12345678910
# Summing all prices prices = [3, 5, 6, 2, 7, 8] i = 0 counter = 0 while i < len(prices): counter += prices[i] i += 1 print(counter)
copy

When we want to stop our loop immediately, we need to use break.

123456789
prices = [1, 2, 3, 4, 5, 6] i = 0 while i < len(prices): if prices[i] == 4: break else: print(prices[i]) i += 1
copy

Oliko kaikki selvää?

Miten voimme parantaa sitä?

Kiitos palautteestasi!

Osio 3. Luku 9

Kysy tekoälyä

expand
ChatGPT

Kysy mitä tahansa tai kokeile jotakin ehdotetuista kysymyksistä aloittaaksesi keskustelumme

course content

Kurssisisältö

Introduction to Data Analysis in Python

Introduction to Data Analysis in Python

1. Basics
2. Data Types
3. Control Flow
4. Functions and Modules
5. Introduction to NumPy

book
While Loop

While loop is another type of loops. It performs the same, but the construction of the loop differs.

We use a special variable, i.e. counter, to collect elements of the list. If you want to count the sum of the numbers from 1 to 10 using the while loop, you also have to create a variable that collects and updates the sum after each iteration.

We use len() when creating a while loop function to create a suitable iterable.

123456789
prices = [100, 458, 231, 378] i = 0 counter = 0 while i < len(prices): counter += prices[i] i += 1 print(counter)
copy
12345678910
# Summing all prices prices = [3, 5, 6, 2, 7, 8] i = 0 counter = 0 while i < len(prices): counter += prices[i] i += 1 print(counter)
copy

When we want to stop our loop immediately, we need to use break.

123456789
prices = [1, 2, 3, 4, 5, 6] i = 0 while i < len(prices): if prices[i] == 4: break else: print(prices[i]) i += 1
copy

Oliko kaikki selvää?

Miten voimme parantaa sitä?

Kiitos palautteestasi!

Osio 3. Luku 9
Pahoittelemme, että jotain meni pieleen. Mitä tapahtui?
some-alt