
Simple constructions in the Python language: branches and loops have their own characteristics in comparison with other languages. Therefore, I decided to spend time on this and tell. The stuff is quite simple!
Also at the request of readers added to the end of the article analysis of a simple program for a visual demonstration of the material studied.
Conditional if statement
I think everything is clear here:
if 1: 1 elif 2: 2 else: 3
')
There is also a short form of recording (analogue of the ternary operator in C):
X = A if else B
Replaces the construction of the form:
if condition:
X = A
else:
X = B
Interception exceptions
General form:
try:
block 1 # interpreter tries to execute block1
except (name1, name2):
block 2 # is executed if the name1 or name2 exception is raised in the try block
except name3:
block 3 # is executed if the name3 exception is raised in the try block
except:
block 4 # is executed for all other exceptions that occurred
else:
block 5 # is executed if there is no exception in the try block
finally:
block 6 # will always be executed
The else construct was added to the exception handling instruction so that we could separate situations without resorting to the use of flags when program execution continued because there were no exceptions in the try block, or they were intercepted and processed.
The else construct in Python has also been added to loops.
While loop
General form:
while condition:
block1
else: # optional part of else
block2 # is executed if the exit from the cycle was not performed by the break instruction
break -
goes beyond the cycle
continue - goes to the beginning of the loop (to the header line)
Cycle for
General form:
for <element> in <object to be iterated>:
block1
if condition: continue
else: break
block2 # will never be executed, given the if statement
else:
block3 # will be executed if the exit from the loop was not performed by the break instruction
Examples of using:
>>> L = [(5.5), (6.6)]
>>> for (x, y) in L: # assigning a tuple in a for loop
... print x, y, # output without adding the line end character
...
5 5 6 6
Consider the typical problem of finding common elements of two lists. It can be solved in completely different ways, for example, with the help of sets, but in this case we are interested in the solution with the help of nested for loops.
for elem1 in list1:
for elem2 in list2:
if elem1 == elem2:
print elem1, u'element found '
break
else:
print elem1, u'not found '
However, this task can be solved using only one for loop, thanks to the use of the in operator:
for elem in list1:
print (elem, 'found') if elem in list2 else (elem, 'not found')
In this case, the in operator itself scans the list and searches for an item. This solution will work faster than the first. Therefore, in all cases where it is possible, it is better to try to use the already described language constructs.
A similar theme to cycles in Python is the notion of an iterator. And it is very opportune that this topic
was described by the same number on the day. I used some of the points described in it when writing a practical example, especially for this article. For example, the function enumerate () In general, the tendency of a single appearance of a large amount of Russian-language material on Python is very positive!
Practice
The condition of the problem: to build a graph of the change in the rate of given currencies for a given period of time from the current date.
The drawCurrency () function takes 4 parameters as input:
- dictionary, the keys of which are the names of currencies, and the values are currency identifiers defined by the Central Bank.
- the number of months of interest to us
- picture width
- picture height
Implementation:
dumpz.org/4991Result of work:

Description:
At
www.cbr.ru/scripts/Root.asp, the Central Bank of the Russian Federation provides a description of interfaces for working with web services. Thus, we can follow a specific link containing the starting and ending dates, as well as the currency identifier, and as a result receive an XML document containing currency rates by day. Further to carry out its parsing.
This part of the work in my implementation is done by the getData () function for working with dates using the datetime library, and for parsing XML - xml.dom. The output of the function is a dictionary containing three objects:
- list containing currency exchange rates by day
- minimum value in the list
- maximum value in the list
We will need the last two elements in order to scale the image. They can be determined later. But in this case, I wanted to show how with the help of the built-in data types, you can actually return several objects, listed by commas, by function.
Also inside the function, a try / except construct is used. In that case, if the document could not be retrieved from the server, or incorrect values were passed to the function, the parse () function will throw an exception and then the program logic will go to the exception handler except where our function will return None.
Loop for j, key in enumerate (currency.keys ()): in the body of the function, drawCurrency () bypasses the currency dictionary. For each of them, it calls the getData () function, randomly generates a color for displaying the exchange rate on the chart, and determines the minimum and maximum exchange rate values for all currencies transferred to the input.
After that, a consistent drawing of the charts of each currency is carried out.
If you need clarification of some points - I will answer in the comments. In the next article,
cleg planned to expand on the topic of functions in depth, however, given the parallel appearance of articles, I cannot yet know whether he would do it. It becomes more and more interesting))