Lecture 6 Flashcards
(16 cards)
Loops definition
Loops are used to repeat certain sections of code a defined number of times
What do loops allow us to do?
-automate repetitive tasks without having to rewrite code
-Add flexibility/adaptability to code when the number of times a code should be repeated is dynamic
-embedded automation systems operate as loops
What do for loops do
The for loop in Python is the concept of an editable which are data structures that contain multiple elements which can be retrieved one at a time.
What type of data structures are iterable?
Lists
Tuples
Sets
Dictionaries
For loop syntax
For <var> in <iterable>:
<code>
<code></code></code></iterable></var>
Given my_dict={“a”:1, “b”:2}
For x in my_dict:
print(x, “:”, my_dict[x])
Output =
a:1
b:2
Given my_dict={“a”:1, “b”:2}
For x in my_dict.values():
print(x)
Output:
1
2
Given my_dict={“a”:1, “b”:2}
For x, y in my_dict.items():
print(x, “:”, y)
Output:
a:1
b:2
How to break loops
Add the break command.
The loop will stop when this line is encountered, even if there are more things to iterate
Skipping the remainder of the current iteration, but continuing on with the next iteration command
Continue
Range command
range(start, stop, step)
Will return an editable that is a sequence of numbers from start to stop incremented by step .
Start, stop and step for range command
Start is optional and when excluded is default zero
Step is optional and when excluded is default one it may also be negative
An empty sequence is returned if start is greater than stop
Nested loop
Is a loop inside of a loop
While loops
While loops execute a section of coda as long as a condition is true. While loops, unlike four loops are almost the same as other other programming languages.
While loop syntax
while <condition>:
<code>
<code></code></code></condition>