0% found this document useful (0 votes)
22 views22 pages

VAT in Python

1. The document describes a Python program that calculates the VAT of 5 products entered by the user. 2. The program asks for the price of each product in a loop, sums the total prices, and calculates the VAT by applying 16% to the sum. 3. Finally, it displays the total without VAT, the VAT amount, and the total with VAT.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
22 views22 pages

VAT in Python

1. The document describes a Python program that calculates the VAT of 5 products entered by the user. 2. The program asks for the price of each product in a loop, sums the total prices, and calculates the VAT by applying 16% to the sum. 3. Finally, it displays the total without VAT, the VAT amount, and the total with VAT.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd

Make a

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

product_count 1# Know which product we are going for


precio_total Total product accumulator
While the product count is less than or equal to 5
while product_count<= 5:
mensaje Enter the price of product number {}:
product_count)
precio_como_cadena input(message)
Convert to float
precio float(price_as_string)
Add it to the total price
total_price = total_price + price
We already read a product, we added it to the count.
product_count = product_count + 1
When the cycle ends, we calculate the VAT
increase = total_price * (VAT_PERCENTAGE / Divide by 100 because it is a percentage
Summarize the increase
total_price + increase
Print totals
print("Total: ${}"
ormat(precio_total))
VAT: ${}
Total including VAT: ${}
In Python, it is not necessary to define variables before using them, unlike C and
similar. You just need to declare it by assigning a value to it. For example, write directly:

>>> 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:

base = input ("Please give me the price of the item:")

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

>>> base = input("Give me the price of the item, please:")


Give me the price of the item, please: 99
>>> print(base)
99

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:

>>>print (base +1)


Traceback (most recent call last):
File "<pyshell#5>", line 1, in <module>
print (base +1)
TypeError: Can't convert 'int' object to str implicitly

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

To calculate VAT we can do:

VAT = base * 1.21


Traceback (most recent call last):
File "<pyshell#10>", line 1, in <module>
base * 1.21
TypeError: can't multiply sequence by non-int of type 'float'

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:

========== RESTART: C:\Python35-32\dos.py ================


Give me the price of the item, please: 100
100.0 21.0 121.0
>>>

Here I leave you the first little program:

program to calculate VAT and total

base = input("Please give me the price of the item:")


base = float( base)
vat = base * 0.21
total = base + VAT
print (base, vat, total)

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.

Creation of a function with the pass command.


The intentional way to declare a function that does nothing has to
to hit with a command that does nothing either. We present you the
commandpass. And that's what it does, nothing at all. Look at this code:

... pass #Here we will place code in the future


...
goodbye()
>>>
As you can see, when invoking the function it does "nothing". Here we are going to explain line by line.
line:

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.

Creation of a useful function in real life.


It's very nice to study theory, but we must be pragmatic and put it to work in
our lives. To do this, we are going to create a function that calculates a given amount.
the sales tax that we must pay (Value Added Tax, VAT or
VAT). In our country, Venezuela, all of that is regulated by law and if you want
review itwe have published a post about it.
The calculation is as follows: to the amount (which we will call the taxable base or base) it
we multiply by the tax rate and divide it by one hundred. As of today, the rate is
of 12% but it can increase or decrease over time, but in general
it lasts months and even years at the same value. We will assume then that it is 12% and
we move on to write the function:

>>> def tax(base):


Tax to pay:
...
tax(100)
Impuesto a pagar: 12
>>>
We quickly observe, in the only line of the function, how we have used the
function print(), we have separated the arguments with commas to print us a
blank space between them, and one of the arguments we passed a
function round() in turn with two arguments: the calculation of the tax itself and the
number 2 to indicate that he should round the tax to two decimal places sinceso it
the law demands(there are certain cases like the handling of foreign currency or exchange -for example:
€- and sale of hydrocarbons that, due to the high amounts, when multiplied by only 2
Decimals make a big difference: only in those cases are 4 decimals required. Why?
demons, do we explain this? You will see later.

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.

So then, let's write our comment enclosed in triple quotes.


to comply with Python.org and its rules, let's see

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:

>>> def tax(base=0):


Calculation of VAT on a given amount V. 0.1
... if base==0:
Enter an amount greater than zero.
...
Tax to pay:
>>>
We added a valueby default so if we do not pass to the function when calling it
the argument then takes a value of zero and if the value is zero it prints a message
inviting to do it. We have turned a function with a mandatory argument into a
which it is not. This has advantages and disadvantages: if we do not value it for
we force ourselves to be better programmers. But how do we
we set a default value, it is advisable that the program warns that it is being
passing, whether true or not, a value of zero, therefore the tax would be zero and the
function would have no reason to exist. If we made a mistake while programming and at some point
we call the function without an argument and in time we will receive a beautiful call
telephone of our clients saying something like 'we input the amount of the base and the
the program says to enter a value greater than zero.

Thus our function continues to evolve: we place it again to be


the base is mandatory as an argument BUT we leave the message and improve it for
handling negative values, version 0.2 would look like this:

>>> def tax(base):


Calculating VAT on a given amount Ver. 0.2
... if base<=0:
Enter an amount greater than zero.
else:
... print('Tax to pay:', round(base*12/100,2))
>>>

Functions with keyword arguments.


We told you that the amount of the tax rate lasts for months and even years with the
same value, but eventually changes. Therefore, we are going to think about the future and
let's modify it again, it would be version 0.3:

>>> def tax(base, rate=12):


... ''' Calculation of VAT on a given amount Ver. 0.3 '''
... if base <= 0:
Enter an amount greater than zero.
... else:
Enter rate (12%)
... if len(n_tasa) > 0:
... rate=float(n_rate)
Tax to be paid: Bs.
...
>>>
Here we give the user the opportunity to modify the rate if it has changed, of the
otherwise press enter and the rate will remain at its default value of 12%.
we place it when declaring the function. The function input() returns a string: if
the user wrote something the length of the string is greater than zero and the len() function tells us
it will say so, on the other hand the function float() will convert the string to a number
double precision, capable of handling decimals.

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:

... n_tasa = input('Enter rate (' + str(tasa) + '%)')


To call the function, we will write tax(100, 15) to inform the function,
By logic, to calculate 15% tax on an amount of Bs. 100. But with Python
we have several ways to call the function and they will all produce the same result:
Bs. 15 -if we simply press enter when checking the rate-, try it in
your consoles please:

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?

Please read as well Python 3.5.2 tutorial


Powered byInline Related Posts
Annotations in functions.
We can 'ask' the function what it is for by means of
Simply enter the following:

>>> 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:

def tax(base: float, rate: float = 12) -> float:


VAT calculation on a given amount Ver. 0.3
... if base<=0:
Enter an amount greater than zero.
...
n_rate = input('Enter rate (12%)')
... if len(n_tasa) > 0:
... rate=float(n_rate)
Tax to pay: Bs.
...
>>>print(impuesto.__annotations__)
float
Do you notice the format in which it returns the definitions of the arguments? Let's go
analyze them and for this we will place it in several lines in an indented manner:

{
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

tax(decimals=2, rate=10, base=1500)


150.0
>>> impuesto(decimales=2, tasa=10)
Traceback (most recent call last):
File /usr/lib/x86_64-linux-gnu/gedit/plugins/pythonconsole/console.py line
378, in __run
r = eval(command, self.namespace, self.namespace)
File "<string>", line 1, in <module>
TypeError: impuesto() missing 1 required positional argument: 'base'
However, if we only pass the decimals and the rate, we do not pass the ...
base throws an error because it must be a required argument, as rate and
We set default values for decimals and thus convert them into arguments.
optional.

Use of variables to pass them to functions.


We will see something that is easily deducible, but we will complicate it a little with the
default values in optional function arguments. Let us explain:
We can store the values in variables and then pass them to the function:

>>> 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.

Functions with arbitrary arguments.


We can define a function that accepts any argument, having already studied
previously the flexibility that Python denotes. There are few characters that it
component, but do not be fooled: it is a complex function and difficult to assimilate,
very generic, and it's hard to give it a practical use:

>>> def my_function(*arguments):


... for mi_arg in arguments:
... print(my_arg)
...
my_function(20)
20
my_function()
my_function(20, "test")
20
test
my_function(20, "test", 17, 20, "another test")
20
test
17
20
another test
>>>

Functions with arbitrary arguments but with words


keys.
To declare arbitrary arguments in a function, we only have to
precede it with an asterisk and thus Python will "know" how to group them in a "dictionary"
which allows us to list them (and work with) those arguments (which will be a simple
variable more within the function). But as better is explicit than implicit, Python
it allows us to pass arguments with keywords (and all must have their word)
key or will produce an "error" or exception). Let’s take our function again
calculation of VAT with a given base

def tax(**arguments) -> float:


Functions with arguments and keywords
... monto=0
... base = 0
... tasa = 12
... decimales = 2
... for arg_clav in arguments.keys():
... if arg_clav=='base':
... base=float(arguments[arg_key])
... if arg_clav=='rate':
... rate=float(arguments[arg_key])
... if arg_clav=='decimals':
... decimals=int(arguments[arg_key])
... amount=round(base*rate/100,decimals)
return amount
...
tax(decimals=2, base=500, rate=7)
>>> print(vat_amount)
35.0
>>> print(impuesto.__annotations__)
float
>>> print(tax.__doc__)
Functions with arguments and keywords
>>>

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:

Line 1: we declare the function itself with included metadata.


Line 2: we set his substring.
Lines 3 to 6: we initialize the variables with their default value, if they have one.
Line 7: we call a for loop to enumerate all the arguments with
keywords "past" to the function.
Lines 8 to 13: through conditional statements we check if all the
elements of the formula for calculating the tax are present, if any are missing
some would take their default value.
Line 14: performs the calculation itself.
Line 15: returns the result outside of the function.
Other lines: function annotations and substring. Note that in
The annotations only indicate that it is a function that only returns a value.
floating point, without any information about the necessary arguments for
that "does your job"

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:

>>> diccionario = { "base" : 277.25 , "tasa" : 19 , "decimales": 3 }


tax(**dictionary)
52.678
>>>
Note that the key words must be enclosed in quotes, and that
we must put two asterisks when calling the function, even if we are declaring the
function with **arguments, this is the most curious thing about the matter and brings us back to
Principle: any function accepts arguments with keyword arguments if it
we put ** when calling the function with a dictionary, complex, right? And barely

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:

>>> diccionario = { "base" : 277.25 , "tasa" : 17 , "decimales": 4 }


tax
>>> import(**dictionary)
47.1325
>>>

Lambda shorthand function.


Sometimes we need to use a function just once (a rare thing) and code it in 3
lines at least (apart from being in a separate section of our project dedicated
to the functions) since it takes us time and space. For this we rely on the
function of functions? the lambda command. This command allows us to apply, for
example, a calculation like ours, which is extremely simple, let's practice:

>>> (lambda base : round(base*12/100,2))(100)


12.0
As we see, we did not name the function; we only indicated that it should return the
same basis with the tax calculation (it is everything that encloses the first pair of
left parenthesis to right) and in the second pair of parentheses we pass the
argument with the base to calculate. It may be complicated to understand so
we proceed to define the function and "clone" it with a name:

tax=lambda base : round(base*12/100,2)


>>> impuesto(1000)
120.0
tax(7)
0.84
tax(70)
8.4
tax(100)
12.0
>>>
Here we see that it is a way to quickly define a function. If we want
We can define putting in the complete arguments as follows:

lambda base, rate, decimals: round(base * rate / 100, decimals)


tax(100,12,2)
12.0
tax(543, 17, 4)
92.31
>>>
It is evident that the arguments are positional, if we want to add them
keywords... well, for that we define the complete function as we have already done.
done. We find this command/function useful within another declared function
so that it is confined within that function only, but you all judge and
give it some other novel use, let's practice!

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=

VAT Calculation You have two methods:


Method a: If we provide the price without VAT and the VAT percentage we
will give the RRP (Recommended Retail Price)
Method b: If we give the price with VAT and the VAT percentage, we
will give the base price
method = input('Which method do you want to use? (a/b) ')
method = method.lower()

while method != 'a' and method != 'b':


Method = input('The input term is not valid Which method do you want?
use? (a/b)
method = method.lower()
if method == 'a':
methodA()
elif method == 'b':
methodB()

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)

You might also like