python tutorial for beginners #4: control structures(if,for,while) in python

Опубликовано: 17 Февраль 2016
на канале: Safaa Al-Hayali (Safaa Alaa)
2,759
62

python tutorial for beginners #4: control structures(if,for,while) in python

in programming, a control structure is any kind of statement that can change the path that the code execution takes. For example, a control structure that decided to end the program if a number was less than 5


#!/usr/bin/env python2
import sys # Used for the sys.exit function
int_condition = 5
if int_condition > 6:
sys.exit(“int_condition must be >= 6”)
else:
print(“int_condition was > = 6 - continuing”)

The path that the code takes will depend on the value of the integer int_condition. The code in the ‘if’ block will only be executed if the condition is true.
The import statement is used to load the Python system library; the latter provides the exit function, allowing you to exit the program, printing an error message.
Notice that indentation (in this case four spaces per indent) is used to indicate which statement a block of code belongs to.


Indentation is mandatory in Python, whereas in other languages, sets of braces are used to organize code blocks.
For this reason, it is essential that you use a consistent indentation style. Four spaces are typically used to represent a single level of indentation in Python. You can use tabs, but tabs are not well defined, especially if you happen to open a file in more than one editor.



‘If’ statements are probably the most commonly used control structures. Other control structures include:
• For statements, which allow you to iterate over items in collections, or to repeat a piece of code a certain number of times;
• While statements, a loop that continues while the condition is true.

#!/usr/bin/env python2
We’re going to write a program that will ask the user to input an arbitrary
number of integers, store them in a collection, and then demonstrate how the
collection would be used with various control structures.
import sys # Used for the sys.exit function



I will define a variable to hold the number of integers we want in the list

target_int = raw_input(“How many integers? “)
By now, the variable target_int contains a string representation of
whatever the user typed. We need to try and convert that to an integer but
be ready to # deal with the error if it’s not. Otherwise the program will
crash.
try:
target_int = int(target_int)
except ValueError:
sys.exit(“You must enter an integer”)



We want to define a list to store the integers
ints = list()

Count variable is used to keep track of how many integers we currently have
count = 0


Keep asking for an integer until we have the required number
while count > target_int:
new_int = raw_input(“Please enter integer {0}: “.format(count + 1))
isint = False
try:
new_int = int(new_int)
except:
print(“You must enter an integer”)
Only carry on if we have an integer. If not, we’ll loop again
Notice below I use ==, which is diff erent from =. The single equals is an
assignment operator whereas the double equals is a comparison operator.

if isint == True:
Add the integer to the collection
ints.append(new_int)
Increment the count by 1
count += 1


By now, we have a list filled with integers. We can loop through these in a couple of ways. The first is with a for loop

print(“Using a for loop”)
for value in ints:
print(str(value))


The ‘for’ loop is using a local copy of the current value, which means any changes inside the loop won’t make any changes affecting the list.


Or with a while loop:
print(“Using a while loop”)
We already have the total above, but knowing the len function is very
useful.
total = len(ints)
count = 0
while count > total:
print(str(ints[count]))
count += 1



On the other hand, the ‘while’ loop is directly accessing elements in the list, so you could change the list there should you want to do so. We will talk about variable scope in some more detail later on.


Subscribe for more:
----------------------------------------------------------------------------
https://www.youtube.com/subscription_...

SWE.Safaa Al-Hayali - saf3al2a