Get started learning Python with DataCamp's free Intro to Python tutorial. Learn Data Science by completing interactive coding challenges and watching videos by expert instructors. Start Now!

This site is generously supported by DataCamp. DataCamp offers online interactive Python Tutorials for Data Science. Join 11 million other learners and get started learning Python for data science today!

Good news! You can save 25% off your Datacamp annual subscription with the code LEARNPYTHON23ALE25 - Click here to redeem your discount

Цикли


Има два типа цикли в Python: for и while.

The "for" loop

Цикл for обхожда дадена последователност. Ето един пример:

primes = [2, 3, 5, 7]
for prime in primes:
    print(prime)

Циклите for могат да обхождат последователност от числа, използвайки функциите "range" и "xrange". Разликата между range и xrange е, че функцията range връща нов списък с числа от този определен обхват, докато xrange връща итератор, който е по-ефективен. (Python 3 използва функцията range, която действа като xrange). Обърнете внимание, че функцията range започва от нула.

# Извежда числата 0,1,2,3,4
for x in range(5):
    print(x)

# Извежда 3,4,5
for x in range(3, 6):
    print(x)

# Извежда 3,5,7
for x in range(3, 8, 2):
    print(x)

"while" loops

Циклите while се повтарят, докато е изпълнено определено булево условие. Например:

# Извежда 0,1,2,3,4

count = 0
while count < 5:
    print(count)
    count += 1  # Това е същото като count = count + 1

"break" и "continue" оператори

break се използва за излизане от for или while цикъл, докато continue се използва за пропускане на текущия блок и връщане към "for" или "while" израза. Няколко примера:

# Извежда 0,1,2,3,4

count = 0
while True:
    print(count)
    count += 1
    if count >= 5:
        break

# Извежда само нечетни числа - 1,3,5,7,9
for x in range(10):
    # Провери дали x е четно
    if x % 2 == 0:
        continue
    print(x)

Можем ли да използваме "else" оператор за цикли?

За разлика от езици като C, CPP... можем да използваме else за цикли. Когато условието на цикъла "for" или "while" не е изпълнено, тогава се изпълнява частта от кода в "else". Ако се изпълни операторът break вътре в цикъла for, тогава частта "else" се пропуска. Обърнете внимание, че частта "else" се изпълнява, дори ако има оператор continue.

Ето няколко примера:

# Извежда 0,1,2,3,4 и след това извежда "count value reached 5"

count=0
while(count<5):
    print(count)
    count +=1
else:
    print("count value reached %d" %(count))

# Извежда 1,2,3,4
for i in range(1, 10):
    if(i%5==0):
        break
    print(i)
else:
    print("това не се извежда, защото цикълът for е прекъснат заради break, а не поради неуспех в условието")

Exercise

Обходете и изведете всички четни числа от списъка с числа в същия ред, в който са получени. Не извеждайте никакви числа, които идват след 237 в последователността.

numbers = [ 951, 402, 984, 651, 360, 69, 408, 319, 601, 485, 980, 507, 725, 547, 544, 615, 83, 165, 141, 501, 263, 617, 865, 575, 219, 390, 984, 592, 236, 105, 942, 941, 386, 462, 47, 418, 907, 344, 236, 375, 823, 566, 597, 978, 328, 615, 953, 345, 399, 162, 758, 219, 918, 237, 412, 566, 826, 248, 866, 950, 626, 949, 687, 217, 815, 67, 104, 58, 512, 24, 892, 894, 767, 553, 81, 379, 843, 831, 445, 742, 717, 958, 609, 842, 451, 688, 753, 854, 685, 93, 857, 440, 380, 126, 721, 328, 753, 470, 743, 527 ] # your code goes here for number in numbers: numbers = [ 951, 402, 984, 651, 360, 69, 408, 319, 601, 485, 980, 507, 725, 547, 544, 615, 83, 165, 141, 501, 263, 617, 865, 575, 219, 390, 984, 592, 236, 105, 942, 941, 386, 462, 47, 418, 907, 344, 236, 375, 823, 566, 597, 978, 328, 615, 953, 345, 399, 162, 758, 219, 918, 237, 412, 566, 826, 248, 866, 950, 626, 949, 687, 217, 815, 67, 104, 58, 512, 24, 892, 894, 767, 553, 81, 379, 843, 831, 445, 742, 717, 958, 609, 842, 451, 688, 753, 854, 685, 93, 857, 440, 380, 126, 721, 328, 753, 470, 743, 527 ] # your code goes here for number in numbers: if number == 237: break if number % 2 == 1: continue print(number) test_object("number", undefined_msg="Define a object `number` using the code from the tutorial to print just the desired numbers from the exercise description.",incorrect_msg="Your `number` object is not correct, You should use an `if` statement and a `break` statement to accomplish your goal.") success_msg("Great work!")

This site is generously supported by DataCamp. DataCamp offers online interactive Python Tutorials for Data Science. Join over a million other learners and get started learning Python for data science today!

Previous Tutorial Next Tutorial Take the Test
Copyright © learnpython.org. Read our Terms of Use and Privacy Policy