
I'm learning to program
on python: variables and functions

To begin with, I'll explain something. The blog is called “I am learning to program”, and not “I learn to program” - in other words, this is not a programming textbook. I am not an expert and do not have the skills of a teacher, and therefore, if I can take the right to teach someone, then only myself.
The blog has two goals. The first is personal: I want to systematize and strengthen the knowledge that I have. As you know, one of the best ways to learn is to tell and explain to other people what you know. That is why I will be happy to read reviews and indications of errors (the last time, by the way, valuable comments were on our Facebook). The second goal is propaganda. I sincerely believe that anyone can learn to program now, and I want to show with my example: since the editor of the site LOOK at Me can write a code, then anyone can write it at all.
Note: the entire code is given for Python version 3.0 and older, and therefore may not work on older versions.
Last time, we wrote a simple program that calculates the square of the entered number. In the end, I called two shortcomings of the program. Firstly, she stops working immediately after she derives the result. Secondly, it is not protected from inaccuracies when entering: if we enter not the number, but the letter, then the program will show the error and close. Let's start with the first drawback. To eliminate it, we introduce the concept of a cycle - a structure that allows you to perform the same set of operations as many times as you like - even endlessly if desired.
Compared to the code from the previous release of the blog, I made only one change: I placed the last two lines in the unconditional cycle While True:. The instructions performed by the cycle are placed in the code block with an indent of four gaps (according to the PEP 8 standard) - just like the contents of the function. Cycles with a key word While are as follows:
The interpreter sees the key word While and the condition that is set after it. In our case, this is a TRUE condition type Boolean. The Boolean type also includes FALSE. In other words, this is a logical type that can only have two meanings - truth or lies. The words While and True form something like an idiomatic structure that speaks the interpreter: follow the instructions inside the block endlessly-if only suddenly something does not interrupt them.
The interpreter performs the instructions inside the block in order, from the first line to the last.
The interpreter sees that the code block has ended and checks whether the condition specified after the key word While is fulfilled. If it is executed, then the interpreter returns to the first line of the block (pay attention to the block, not the entire program) and goes in order. If the condition is not fulfilled, then the cycle ends, and the interpreter goes to the line, which follows immediately behind the last line of the block. In our case, the condition will always be fulfilled, regardless of what is happening inside the block. But in theory, we could set another condition, for example, to make the design work only three times:
I introduced a variable I and appropriated her value 0, and therefore it will be the type of int. Next, I placed a new line I ++ in the cycle block. ++ is an incremental operator (increase): after it is executed to the value of the variable I, 1 is added 1. Write I ++ is equivalent to recording I = I+ 1, it is just a shorter option. Thus, after the third execution of all the instructions of the block I will reach 3, and condition I <3 (I less than three) will cease to be executed, and the cycle will end.
Attention! I just gave a not very competent code, and more precisely, not a very pythonic code. Although the interpreter will accept it, the design that I used is rather characteristic of other languages - for example, C (although, in my opinion, it is still not very elegant) . In Python, in order to set how many times the cycle should perform instructions inside the block, usually use the cycle with the counter with the key words for and in, but we will talk about it later.
Perhaps someone will have a question-why didn’t I place the line I = 0 inside the block? Wouldn't it be more reasonable, given that the variable is not used outside the block? In addition to the fact that this is simply not a very neat code, remember that if we made i = 0 the first line inside the block, then at the beginning of each cycle the value of I would be reset. I will explain how the code is erroneous below:
At the beginning of the first cycle, the interpreter performs instructions on the first line of the block and assigns a variable I value 0.
The interpreter reaches the fourth line of the block, conducts an increase in I ++, and the value I becomes 1.
The interpreter, seeing that the block has ended and condition I <3 is still executed (1 really less than 3) , begins the second cycle.
The interpreter again performs the instructions on the first line and assigns a variable I with the current value of 1 new old value 0.
Clauses 1-4 are repeated endlessly. In fact, we get a crookedly written analogue of the While True cycle - the value of I will never achieve not only 3, but even 2.
Although we fixed the first flaw, another appeared in its place. Now our program works endlessly - it is impossible to get out of it. But what if you set a condition under which the user, having gained the letter Q, could leave the program? Let's do it, but at the same time we will analyze the changes in the code:
Pay attention to the third and last lines. I added Print () functions to output messages that will help the user to navigate the program. The first message will always be displayed once at the very beginning, the second - once, when the program finishes the work. Inside the block related to the While True:, IF and Else branch operators appeared. They allow you to set the conditions for the performance of code blocks and are equivalent to the syntactic structure "If ..., then ...". This is how they work:
After the keyword, IF is given the condition. If this condition is fulfilled, then the interpreter goes to the code inside the block following the colon. In our case, the condition is number == 'Q', and the whole line will be read as “if the value of the Number variable is 'Q'”. Operator == means “equal” - do not confuse it with the operator =, which denotes the assignment (the condition number = 'Q' will give an error - this is an attempt to assign a variable Number, the value of which has just been introduced, the value of 'Q'; we need to compare the introduced value with the value 'Q').
Inside the block, the key word Break is used, speaking the interpreter, that he needs to interrupt the current cycle and move on to the line of the program following the block - in our case this is the last line of the program with the Print () function. The IF ...: is located inside the While True: and therefore line with the keyword Break is recorded with an indentation of eight gaps. If there were no Break words, then the interpreter, passing the Else block:, would continue to move on the cycle.
If the condition is not fulfilled, then the interpreter passes to the line following the block, in our case, a line with the key word ELSE. This word tells the interpreter that if the condition is not fulfilled in if, then the code should be executed inside the ELSE:. In this block, I placed two operations that used to be inside the While True:.
Thus, the program appears in the program: if the symbol we introduced is q, then the cycle must be completed, if not, then continue, transfer the Number variable from the type of int into type int and display a message with a square of the number.
Surely many will have a question - why did I put out an operation to transfer the Number variable from the type of String to the Int type to a separate line inside the ELSE block:? The fact is that if you leave this operation on the first line of the cycle, then after entering the symbol Q, the program will give an error, because the symbol Q cannot be translated into Int - that is, to make an entire number. In other words, the program will give an error even before it has time to check the condition. If we remove the transfer of the ELSE block, then entering Q will allow you to get out of the program. It remains only to make sure that the input of other letters does not lead to an error.
So that the program does not throw out the user every time he introduces a non -kissed number and any letter except Q, we will use the Try and Except exceptions for exceptions - and describe how they work:
The design with the keywords of Try and Except has become part of the Else block: from the While True cycle: and therefore both words are introduced with an indent to eight gaps, and the lines inside the Try blocks: and Except Valueerror: - in 12 spaces.
The word try indicates the interpreter that you need to check whether the instructions are executed inside the block following the colon. If they are executed and do not give errors, then you need to perform them and return to the previous code block (in our case, the While True block :), if impossible, go to the block with the key word Except.
The Except word block indicates what to do if the operations from the Try block: were impossible. In our case, we expect an error like Valueerror and indicate it after the keyword - although it was possible to simply write except: that is, what to do if an error of any type appears.
Thus, the program checks what the user introduced. If he introduced a non -kissed number and any letter, except Q, then the program, realizing that it is impossible to execute the first line from the Try block: displays an error from the Except block: and continues the cycle further. Now, if you introduce the wrong symbol, the program will immediately suggest you try to do this again, and not stop working.
Now the program does everything as I wanted from the very beginning. It can be expanded - for example, so that it calculates not only the square, but also the cube of the entered number or work with decimal fractions, for which you need to use the Float data type. I will not do this on the blog, but if suddenly there is a desire - forward.
Perhaps today I went too far with new material, and all this will not be easy to digest. But I deliberately did not delve into each of the topics, but only touched them: we will meet these concepts more than once and we will sit down how to use them. So far I have not decided what would be in the next issue - I think either a simple text game, or the task that I gave myself in the first release of the blog. The main thing is that next time we will strengthen and expand the ideas obtained in this and previous issue.
Please, if something is not clear to you, write comments under fasting and on social networks-I will be glad and any other reviews. If you are a more experienced person in programming than I, then I will be happy to listen to substantial criticism. Thank you, and until the next time!
Read also:
Full Python courses on Codeacademy and Treehouse *
* - paid courses, but there is a trial period
Development of programming thinking on udacy
Python Cycles on Learnpython.org and Python Course
Conditions in Python on Learnpython.org and Python Course
Exceptions to Python on Learnpython.org and Python Course
Image Via Shutterstock