avatarVinicius Monteiro

Summarize

Python For Beginners: Conditions and Loops Syntax

if, for and while statements syntax in Python

Photo by Boitumelo Phetla on Unsplash

In this tutorial, you’ll learn Python’s basic syntax of control flows.

Learning to code if , for and while, is key for any programming language. A lot of a program’s implementation comes down to defining conditions (if X happens, do Y) and iterations (while X is happening, perform task Y).

if Statement

Conditional flows often take up a lot of an application code. That’s how you instruct the machine to do something in case of another event. The programmer can also code the otherwise flows using elif (short for else if) and else .

Here’s an example,

x = 31
if x < 0:
    print('Negative')
elif x == 0:
    print('Zero')
elif x == 10:
    print('Ten')
else:
    print('Greater than 10')

while Statement

Using while statements is a way of coding loop routines in the program. It’s a much-used type of instruction in any application. You tell the machine to do something while another event is true.

i = 1
while i < 10:
  print(f'item: {i}')
  i += 1

for Statement

It’s similar to the while statement. It’s also a form of loop routine. With for statements, you instruct the algorithm to iterate over items and perform tasks at each iteration.

Based on my experience and preference, for statements are more used than while statements. If I can achieve the same result with both for and while I usually choose to go with for .

words = ["writing", "technical", "articles", "is", "awesome"]
for word in words:
    print(word)

Reference:

Python 3.10.2 documentation

Thanks for reading. More on Python:

Programming
Python
Coding
Python For Beginners
Software Development
Recommended from ReadMedium