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

לולאות


There are two types of loops in Python, for and while.

הלולאה "for"

לולאות for עוברות על רצף נתון. הנה דוגמה:

לולאות for יכולות לעבור על רצף של מספרים באמצעות הפונקציות "range" ו-"xrange". ההבדל בין range ו-xrange הוא שהפונקציה range מחזירה רשימה חדשה עם מספרים בטווח שהוגדר, בעוד ש-xrange מחזירה איטרטור, שהוא יעיל יותר. (ב-Python 3 משתמשים בפונקציה range, שמתפקדת כמו xrange). שימו לב שהפונקציה range מבוססת אפס.

לולאות "while"

לולאות while יחזרו כל עוד תנאי בוליאני מסוים מתקיים. לדוגמה:

משפטי "break" ו-"continue"

break משמשת כדי לצאת מלולאת for או while, בעוד ש-continue משמשת כדי לדלג על הבלוק הנוכחי ולחזור אל הצהרת ה-"for" או "while". הנה כמה דוגמאות:

האם אפשר להשתמש בסעיף "else" ללולאות?

בניגוד לשפות כמו C,CPP... אפשר להשתמש ב-else בלולאות. כאשר תנאי הלולאה של הצהרת "for" או "while" נכשל אז החלק של הקוד ב-"else" מבוצע. אם משפט break מבוצע בתוך הלולאה for אז החלק "else" נעקף. שימו לב שהחלק "else" מבוצע גם אם יש משפט continue.

הנה כמה דוגמאות:

Exercise

Loop through and print out all even numbers from the numbers list in the same order they are received. Don't print any numbers that come after 237 in the sequence.

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