Control Flow
We often need to run specific code for certain conditions or we must run a code snippet many times. Toward we have this behavors we need of structures of control flow.
Basically these structures are divided into conditional and repeating structures. Conditional structures allow select code snippets for specific conditions while Loop structures allow the execution of code snippets many times.
Conditional structures in Python
The logical conditionals usein Python are:
- Equals: a == b
- Not Equals: a != b
- Less than: a < b
- Less than or equal to: a <= b
- Greater than: a > b
- Greater than or equal to: a >= b
These conditions are fundamental to statement logical and loops
Simple if-statement.
In this example were declared two variables: a and b. In the if-statement was defined the condition b > a.
As b is equal the five and a is equal to three the message "b greater than a" will show to the user.
Code Block
In Python, The code block is defined through for indentation . Anycode that must run in the statement need to have the same indentation .
Ex:
if condition :
cmd1
cmd2
cmd3
If the condition is true the commands cmd1 and cmd2 will go running. If the condition is false just cmd3 will go running.
If-else statement
In this example two variables were declared: a and b. In the if-statement was defined the condition b > a.
As b is equal to five and a is equal to six the message "b is not greater than a" will show to the user.
The else statement will go running. The statement else execute all that is false in the logical condition b > a.
If-elif-else statement
In this example two variables were declared: a and b. In the if-statement was defined the condition b > a.
As b is equal to six and a is equal to six the message "b and a are equal" will be showing for
user. The elif makes it possible to add logical conditions for statement if-else
Loops
The while loop execute based on the true condition.
While
i = 1
while i < 6:
print(i)
i += 1
while i < 6:
print(i)
i += 1
This code displays the value of i until it has the value 6.
For
The for loop executes a set define number of times.
for x in range(9):
print(x)
print(x)
This code displays the value x until it has value 9.
well, now that we know the basics of Python programming logic, we'll need to proctice tp actually learn how to program.
Comentários
Postar um comentário