Python is a high-level programming language, which is becoming more and more common. This is why learning Python is NECESSARY for Computer Scientists.
A loop is a series of instructions that is repeated. A loop falls in one of three categories:
- Count-control loop: This is a loop that occurs for a defined amount of times.
- Post-condition loop: This is a loop that repeats the sequence as long as the condition is FALSE. Python does not have post-condition loops, so, you’ll have to use a pre-condition loop.
- Pre-condition loop: This is a loop that repeats the sequence as long as the condition is TRUE.
Now it’s time to look at the syntax for each type of loop. When learning a new language the only thing that you learn for the first time is the language’s syntax.
In Python, indentation is absolutely necessary for the program to execute correctly. In addition, it’s important to insert colons after the loop. Finally, it’s important to note that Python doesn’t require semicolons at the end of each line of code, unlike other languages.
Count-control loop syntax:
for <x> in range (s,e,i): <statements>
Now, let’s define some of the values. These values (s, e, i) can only be integers [int() must be used to convert a string into an integer]. The lower bound, s, is where <x> starts at, incrementing by i after each loop. The loop ends when <x> reaches e.
The values of s and i do not have to be included, and are set to 0 and 1 when omitted.
while <condition>: <statements>
This is pretty self explanatory.
Create a program to take as input two numbers. The program is supposed to count down by 1 from the first number to the second.
We can use a count controlled loop to complete the task. Our first attempt at writing this program might look like this:
num1 = input("Input large number: ") num2 = input("Input smaller number: ") for x in range (int(num1),int(num2)-1,-1): print(x, end = ' ')
However, if the user input results in num1 being greater than num2, then the program will crash. So, we need to reprompt the user until num1 > num2.
This can be achieved with a pre-condition loop (since Python doesn’t have post-condition loops). We can ammend the code to look like this:
while int(num1) < int(num2) num1 = input("Input large number: ") num2 = input("Input smaller number: ") for x in range (int(num1),int(num2)-1,-1): print(x, end = ' ')
- Python is a common high-level programming language.
- The Python syntax involves the use of indentation and colons.
- In general, there are three types of loops: count-controlled, post-condition, and pre-condition.
- Python only has count-controlled pre-condition loops.