Python Handbook For Beginners - стр. 6
4 Division Without Remainder
Let's talk about division without remainder in Python. Did you notice that we've got a fraction when we divided 10 by 2, which was 5.0? But what if we need to get an integer? To get that, all we need is to use a double division operator – // Try it out. Open the input field, write 10//2, and hit enter. What number have you got now?
5 Calculation Order
Python handles calculation order, which has no difference from the order you've learned in math classes. Can you calculate (5+5)*3, then write it into the input field and check if you were right? Here is how Python will calculate it:
First, Python will calculate whatever is in brackets, following the order: first multiplication, then division, then addition, then subtraction. After that, Python will calculate whatever is around brackets, following the same order as above (multiplication, division, addition, subtraction)
Hence, Python will add 5 and 5, which will result in 10. And multiply 10 by 3, which will result in 30. Was your answer – 30? Or was it something else?)
6 Numbers and Variables
By this time, we've learned print function, variables, and numbers in Python. Let's combine them all!
Let's write an example with numbers, save its result in a variable, and then display it. Here is how it looks like:
result = 2+2
print(result)
Guess what the output will be? Please take the above code and run it in the console to check it out.
Let's break it down:
1) First, we declared a variable, giving it the name "result" and the value "1 + 1";
2) Then we went down one line, wrote the print function, and passed the name of our variable in its brackets;
3) When we ran the code, Python calculated the value of the variable by adding 2 + 2;
4) The calculation returned 4, and Python assigned this value to the variable "result";
5) Then Python saw that we want to display the result's value because of the print (result) and print it accordingly.
As you can see, numbers and variables work well together in Python.
Let's practice some more and create your examples with numbers and variables, similar to what we just saw. Here are some boilerplate examples for you:
___________
result = 2+2
print(result)
___________
result = 10-5
print(result)
___________
result = 5*5
print(result)
___________
result = 10/2
print(result)
___________
7 Wrapping Up Chapter Three
In chapter three, we have accomplished the following:
1) Refreshed on what are integers and fractional numbers;
2) Learned basic math operators used in Python;
3) Learned how to divide a number without remainder in Python;