VAT in Python
VAT in Python
program in
Python that
ask for it
price of 5
products and
show the
total according to
the rate of
Current VAT.
@author parzibyte
Recommended:
Defining a constant in Python: https://parzibyte.me/blog/2019/01/16/constantes-
"""
VAT_PERCENTAGE = 16
>>> base = 86
>>> iva = base * 0.21
total = base + tax
>>> print (total)
104.06
>>>
For those of you who have never programmed, it may seem quite normal. They look like the
operations that we perform on a calculator or in a spreadsheet. The difference is
that Python has memorized the variables. Try with:
base
86 18.06 104.06
But those of you coming from C will probably be surprised that we have not defined the type of
variables like int or float, and yet Python has graciously accepted the input
assuming our intentions, and he has considered them whole.
It would be more convenient if we could ask Python to request a value and then
let's calculate the VAT and the total. We have an instruction to request information from
user:
Python will extract the message we pass to it in quotes and will wait for us to give it a
response that will be assigned to the base variable. If you write now
Notice that I have written an article with an accent. Python 3 is so broad and reproduces.
correctly the non-USA symbols. This is one of the reasons for the change from Python 2 to 3.
Python 2 only accepts standard ASCII code, while Python 3 works from
The principle with Unicode to allow us this type of characters.
In Python 2, you would have problems writing accents and Ñs..
But you have to be careful with input because it converts what it receives into a String, with
somewhat bewildering results for the novices. What do you think of this?
>>> print (base * 3)
999999
Python considers a String as a base and that's why when trying to multiply it does something that for it is
very normal (And for me) understands that multiplying a String by 3 means copying it 3 times, and the
that is the result.
The overload of operators that we saw with C++ and Arduino is integrated since the
principle in Python.
It's quite reasonable, but you have to get used to it because if not, the interpreter can you
to play a trick. In fact, try this:
Base is a String and does not allow implicit conversion and rejects the operation.
The problem is that Python is not sure which implicit conversion we want.
Do we want the result to be an int and then the value would be 99+1 = 100, or on the contrary
we want it to be a String and the result is "991"?
And in case of doubt, reject the operation.
If you don't believe me, try this:
>>> type(base)
<class 'str'>
You see that he insists that base is a String and that’s it. If you want to convert it into a number
you need the int() function:
>>> print(int(base) * 2)
198
Here we go again. 1.21 is a float and it does not accept that we multiply it by an int just like that.
The types must be the same and for that we need the float() function.
iva = float(base) * 0.21
>>> print(value)
21.0
The newcomers, don't be scared. I intended to push a little harder today, to demonstrate that
Although we don't need to define types, Python is not going to let us pass anything as soon as it has
doubts (Unlike C++ which would make implicit conversions on the fly)
Okay, with all this we are ready to write a program in the editor, that asks us for a
price and then we calculate VAT and total based on the base price (properly converted to
float or int)
I suggest that you try it without looking at the solution that follows. Remember that it
learn by thinking, not by copying.
The output should be something like this:
By the way, I take the opportunity to tell you that if you start a line with the symbol #, Python
it will consider that entire line as a comment.
1. Start:
2. Write: program that calculates the VAT of a product.
3. Write: Insert the value of the product.
4. Read: The value of the product (x).
5. Examine; Perform the operation (x)(.16) = n.
6. Examine: Perform (X+n)=g
7. Write: Show the result of 'g'.
8. End.
Line 1: we define the function with the reserved word def followed by a
space and the name we have chosen for the function. Then we place
by parentheses, one that opens and another that closes, there we will later place the
arguments or data that we want to pass to the function. The colon ':'
they indicate that the line doesn't end there, that there is more in the following lines and to the
press enter you will notice that the prompt becomes '...' and invites us to write
the second line.
Line 2: in the first part of this tutorial we talked about setting up our
text editor so that when pressing the TAB key it inserts spaces instead
of thetab characterNow we ask you, to comply with the rules of
Python.org that you configure it exactly to 4 spaces that you press 4
spaces the first time and then your processor will automatically indent
every time you press enter. So we place the pass command (which does not
it only takes 4 bytes on our hard drive when stored in a
file). Then we add a comment about what we plan to do at
future with that function.
Line 3: a blank line to be able to press enter and return to the prompt
interactive. We should also leave a blank line if we were
writing in a file, for reasons of readability and clarity in our
code.
Of course, we will remove the pass command and the comment as well, but not
we must leave it like this, we should always add an explanatory text, not just for
we in the future, that we might forget things (let's go,unless you are
Rainman!) but to enrich the free software community, we must share
our creations (and charge for the service, of course, those who work earn their bread
diary). If we haven't convinced you with those arguments, here is a third one which is
necessary: Python.org has something calleddocustringthat was designed to be
they can build manuals from a special format that we add
to our functions. How does this work? We only tell you that we must
continue studying how to write functions and we will return to touch on it in due time
theme.
def tax(base):
Calculation of VAT on a given amount
Tax to be paid:
...
>>>
How much clearer is our function? But watch out, now we're going to call the
taxFunction() just like that, without any amount and we will see a beautiful error, down the drain
with our excitement, but the computer is right, and if we have
failed what do we expect then from our future users of our
programs?
Well, here we are going to improve our function, version 0.1, like this:
We will overlook the user entering a non-numeric value; it will come later.
time to improve our code. For now we are interested in continuing to learn. So
how we modify our function allows us for the rate from the call to the
function, therefore it is correct to show said amount so that the
input function() shows the rate that will be applied, we can modify the line of the
next way:
tax(100, 15)
Bs. 15.0
>>> impuesto(base=100 ,tasa=15)
Bs. 15.0
>>> impuesto(tasa=15,base=100)
Bs. 15.0
>>> tax(rate=15,100)
impuesto(tasa=15 , 100)
^
SyntaxError: non-keyword argument after keyword argument
In the last entry, it gives us an error because we are not passing the value with its
keyword, Python expects the first argument to be mandatory and it doesn't matter if
it only has 2 arguments (with a keyword because by elimination the other argument
it is the 'remaining'), that is, if we are going to change the order of the arguments always
we must pass the keyword to indicate where each value goes. In another
way, as we memorize the exact order of the arguments of
each function. If we have an editor to help us write the functions, good,
The tooltips will tell us the name and type of variable that each function expects.
while we are writing a command while programming. But in GNU/Linux it
they need small programs that do small things and do them
Good. Anticipating future programming, heading towards artificial intelligence, Python gives us
offers something very interesting. Let's start withdocustringDo you remember it?
>>> print(tax.__doc__)
Calculation of VAT on a given amount V. 0.3
We are already seeing the usefulness of documenting as we code; also
we have the possibility to 'know' how many arguments the function receives without having to
after a single piece of data, which prepares us to be able to use it (if another person
it is what we write for other people). To do this we must
add to our function the following notation "-> float:" as this defines what
the type of data the function expects to deliver and receive (this disciplines our tactics of
programming, passing the correct data type to the function:
{
float
float
float
}
The first and last line encloses the definition with opening and closing brackets.
closes. The second line indicates that an argument has the keyword name the word
'base' must be a floating point number. The third line 'return' indicates what it returns.
the function, a floating-point numeric variable (which we will have rounded to two
decimals, as we explained). It does not specify a name as we already know what it is called.
the function. The fourth line also indicates that it must receive an argument called
'rate' and it must be a numerical type float. You will notice that they are named in brackets.
angulars like 'class' or class in Spanish: if we were to make our
We can refer to our own classes at any time. There are classes
'float' is a numeric variable that allows up to
16 decimals (we will see the available data types in Python later).
Function annotations are entirely optional and are defined inPEP
484and they are of recent adaptation, year 2015, although they are based on other PEPs,
besides being compatible, in a way.
Keyword "return".
The next thing we are going to do is completely transform our code into a
true function with the command return, let's see:
>>> def tax(base: float, rate: float =12, decimals: int =2) -> float:
VAT calculation on a given amount Ver. 0.4
amount=round(base*rate/100, decimals)
... return amount
...
tax(100)
>>> print(tax_value)
12.0
What we did was add an additional, optional argument with the keyword
"decimals" which is set by default to 2 (by law of our Republic) and the "rate" of
tax which is currently 12 but we can pass a value to the function
the case may be different. We also use a variable called 'tax_value'
where we store the returned value for the function and then we print it by
screen; but we can use this variable wherever and however we need it. So
we can practice in various ways using keywords, let’s see, that practice
makes the teacher (let's remember that we are in interactive mode and simply to
calling the function is automatically printed on the screen, but if the
we save in a .py file we must save in a variable to later
print it, just as we coded, otherwise we won't have output for
screen):
tax(20)
2.4
tax(100, rate=7)
7.0
tax(100, rate=15, decimals=4)
15.0
tax(1477, rate=17, decimals=4)
251.09
tax(1970, rate=17.89, decimals=4)
352.433
tax(1341, decimals=4, rate=17.89)
239.9049
What we always have to do is to 'pass' the base, and then through words.
keys, regardless of the order, the other two arguments, otherwise it throws an error (or
exception which is the correct name). If we want to pass arguments to it, no matter
the order, we must assign keywords to all the arguments, as follows
way
>>> miMonto=450
>>> miTasa=10
>>> myDecimals=3
tax(myAmount, myRate, myDecimals)
my tax
45.0
tax(rate=miTasa, base=miMonto, decimals=misDecimales)
myTax
45.0
This doesn't need further explanation: it's simply passing the values through
variables. What is more advanced is passing the default values to the function by
through variables declared before defining the function and those variables later
They can change their value but the function will remain defined with the given values.
exactly before having defined the function. We can thus redefine the function and
then we will explain its usefulness:
valor_tasa=15
def tax(base: float, rate: float = value_rate, decimals: int = 2) -> float:
Calculation of VAT on a given amount Ver. 0.4
amount=round(base*rate/100,decimals)
return amount
valor_tasa=16
Although we later change the variable value_tax_rate to 16, the function tax() will remain
with a default value of 15 in the rate throughout the entire program.
Do you remember that we told you that the tax rate may vary, depending on the
country's fiscal needs? Well, our function can be prepared to
future (for example, we created a simple invoicing and management application and handling of
inventory) if we write our functions this way, we can return them to
recompile quickly if we change the value to the main module.
Our functions are becoming more complex, and it is increasingly difficult to write them.
in interactive mode, we believe it is already worth writing them to a file through
from our favorite text editor, we will soon provide some recommendations on the matter
and some Python regulations. Meanwhile, let's see what happens in this last example:
What is the use of this, declaring such a strange function that accepts anything
number of arguments with keyword arguments? When we look at the dictionaries in
we will think of a few useful uses, at this point we are going to
try something very simple:
we are starting .
"cloned" functions.
Python allows us to take the functions we import and "rename" them.
Thus our tax() function that we wrote may be for us to memorize it.
in another way, for example impt(), we only need to write impt = tax and
pass the values with the dictionary we made earlier, here:
We create two functions, one for method a and another for method b. We ask the
user to indicate which method they wish to calculate. For the method, we ask for the price.
base and the VAT percentage and we provide the price including VAT. For the
method b we request the RRP (recommended retail price) or price with VAT included,
we also request the VAT percentage and provide the base price or price without
IVA. The functions provide the final result by printing the value on the screen.
result rounded to two decimals.
def methodA():
Base value?
Value of percentage?
result = base * (1 + (percent / 100))
Base=
print('Price with VAT=', round(result,2))
def methodB():
Price with VAT?
Percentage?
result = conIVA / (1 + (percent / 100))
Print(' Price with VAT=', conIVA, ' Percentage= ' + str(percent) + '%')
Base price=
1. # Repetition, decision
2. # Mastermind
3. The computer selects a number and asks the
user who guesses it.
4. Every time you enter a value, the computer will
indicate to the user if he
5. # chosen by him is greater or less than the entered one.
6.
7. import random
8.
random.seed()
10. x= random.randint(1, 99)
11.
12. turnos 1
13. valor Mastermind Give me a value from 1 to
99: "))
14. while valor != x:
15. if valor > x:
16. It is smaller.
17. elif value < x:
18. It is greater.
19. else:
20. break
21.
22. shifts += 1
23. valor Mastermind Give me a value from 1 to
99: "")
24. You have guessed it in shifts.
1. # Lists, loops
2. # Fibonacci in a list
3. The Fibonacci sequence consists of starting with the
two first elements
4. # being 0 and 1. The following elements are calculated
adding the value in the
5. # previous position, and the value in the penultimate
position.
6.
7. n= int(input("Give me the number of positions in Fibonacci: "))
suc_fibo [0, 1]
9. n -= 2
10.
11. for _in range(n):
12. suc_fibo[-1] + suc_fibo[-2]
13. suc_fibo += [new_element]
14.
15. print(suc_fibo)
1. # Loops
Convert a binary value (base 2) to base 10.
3.
4. binary Give me the binary value:
5. binary = binary.strip()
6.
number_of_digits= length of binary
8. base = num_digits - 1
resultado 0
10. for iin range(num_digits):
11. result += (2 ** base) * int(binary[i])
12. base -= 1
13.
14. Result in decimal:
15.
1. # Dictionaries, loops, decision
2. # Frequencies
3. # Calculate the frequencies of each character in a text
order by keyboard.
4.
5. # Request the data
texto Give me a text:
texto str.lower(str.strip(text))
8. frecs= {}
9.
10. Handling accented vowels
11. str.replace(text) 'á', 'a')
12. str.replace(text) 'é', e
13. str.replace(text) 'í', 'i')
14. texto= str.replace(text) 'ó', 'o')
15. str.replace(text) 'ú', 'u')
16. str.replace(text) 'ü', 'u')
17.
18. Initialize the frequency dictionary
19. for xin abcdefghijklmnpqrstuvwxyzñ
20. frecs[x] = 0
21.
22. Calculate the frequencies in the text
23. for a text:
24. if xin frecs:
25. frecs[x] += 1
26.
27. Visualize the results
28. claves_ordenadas list(dict.keys(frecs))
29. list.sort(sorted_keys)
30. for ordered_keys:
31. frec= frecs[k]
32. if frec> 0:
33. Letter {0} appears: {1} time(s).
k, frec))
1. # Dice game
2. # In a dice game, all participants have
the
3. # same number of dice (with 6 faces, from 1 to 6).
4. In each turn, each player rolls all their dice.
adding
5. # each die to obtain a score.
The player with the highest score after three turns wins.
7. #
8. # [email protected] - (c) 2017 - MIT License
9.
10.
11. import random
12.
13.
14. class Dice:
15. Represents a six-sided die, from 1 to 6.
16.
17. def self:
18. self.last_result = 0
19.
20. def draw(self):
21. self.last_result = random.randint(1, 6)
22. return self.last_result
23.
24. def __str__(self)
25. return str(self.last_result)
26.
27.
28. class Player:
29. Represents a player who has x dice.
30.
31. def __init__(self, nick, num_dados):
32. Create a new player.
33.
34. The player's nickname.
35. Number of dice for the
departure.
36.
37. self.nick = nick
38. self.num_data = num_data
39. self.data = []
40. self.last_roll = []
41. for iin range(num_dados):
42. self.data += [Data()]
43.
44. def roll(self):
45. Make a roll with all the dice.
46.
47. self.last_roll = []
48.
49. for dadoin self.dados:
50. self.last_roll += [dice.roll()]
51.
52. return self.last_roll
53.
54. def __str__(self):
55. self.nick + ': '
56.
57. for Xin self.ultima_tirada:
58. toret += str(x) + ' '
59.
60. return toret.strip()
61.
62.
63. class Game:
64. Represents a game of x players and y turns.
65. It will allow the incorporation of players.
66. The play() method throws the y turns, saving
67. the partial results and the total score.
68.
69. def __init__(self, num_turns, num_dice):
70. Create a new game.
71.
72. The number of turns to play.
73. The number of dice for everyone.
74. """
75.
76. self.num_turns = number_of_shifts
77. self.num_data = number_data
78. self.players = []
79. self.max_points = []
80. self.partial_points = []
81. self.shifts = []
82.
83. def insert_player(self, nick):
84. self.players += Player(nick self.num_data)]
85.
86. def plays(self):
87. self.max_points = [0] * len(self.players)
88. self.shifts = []
89.
90. for _in range(self.num_turns):
91. self.partial_points = [[]] *len(self.players)
92.
93. for i, playerin enumerate(self.players):
94. pts = player.roll()
95. self.puntos_max[i] += sum(pts)
96. self.partial_points[i] =
list(player.last_throw)
97.
98. self.shifts += list(self.partial_points)
99.
100. def __str__(self)
101. Game of {0} turns and {1}
data.
102. self.num_turnos, self.num_dados
103.
104. for puntosin self.shifts:
105. for i, ptsin enumerate(points):
106. toret += self.players[i].nick + ': ' + str(pts)
107.
108. toret +=
109. toret +=
110.
111. toret += Final scores:
112. for i, ptsin enumerate(self.max_points):
113. toret += self.players[i].nick + ': ' + str(pts) +
114.
115. return toret
116.
117. if __name__== __main__
118. random.seed()
119. game= Game(random.randint(2, 6),
random.randint(3, 6))
120. game.insert_player("Baltasar")
121. game.insert_player("Fulano")
122. game.insert_player("Mengano")
123. game.insert_player("Zutano")
124. game.play()
125. print(game)