Как найти проценты от числа в python

I guess you’re learning how to Python. The other answers are right. But I am going to answer your main question: «how to calculate percentage in python»

Although it works the way you did it, it doesn´t look very pythonic. Also, what happens if you need to add a new subject? You’ll have to add another variable, use another input, etc. I guess you want the average of all marks, so you will also have to modify the count of the subjects everytime you add a new one! Seems a mess…

I´ll throw a piece of code where the only thing you’ll have to do is to add the name of the new subject in a list. If you try to understand this simple piece of code, your Python coding skills will experiment a little bump.

#!/usr/local/bin/python2.7

marks = {} #a dictionary, it's a list of (key : value) pairs (eg. "Maths" : 34)
subjects = ["Tamil","English","Maths","Science","Social"] # this is a list

#here we populate the dictionary with the marks for every subject
for subject in subjects:
   marks[subject] = input("Enter the " + subject + " marks: ")

#and finally the calculation of the total and the average
total = sum(marks.itervalues())
average = float(total) / len(marks)

print ("The total is " + str(total) + " and the average is " + str(average))

Here you can test the code and experiment with it.

In Python, the % sign is commonly used in three cases:

  1. Modulo calculation. For example, 5 % 3 returns 2.
  2. Old-school string formatting. For example, "I am %d years old" % 25 returns "I am 25 years old".
  3. “Magic” commands in IPython shell. For example, In [2]: %recall executes the previous command.

1. Modulo in Python

The most commonly known use case for % in Python is the modulo operator.

The modulo operator calculates the remainder of a division between two integers.

For example, dividing 10 to 3 evenly is impossible. There will be one leftover. To verify this using Python, write:

leftovers = 10 % 3
print(leftovers)

Output:

1

This can represent for example how many slices of pizza are left over when 10 slices are shared with 3 eaters.

Practical Modulo Example: Leap Years

Definition. A leap year is a year that is evenly divisible by 4 or 400. The exception is that years divisible by 100 are not leap years (unless they are divisible by 400). For example, 2016, 2000, 1600 are leap years but 2011 and 1900 are not.

Task. Write a program that checks if a given year is a leap year.

Answer. To solve this problem, you need to figure out if a given year is divisible by 4 but not by 100 unless it’s divisible by 400.

To turn this into code, you get this kind of result:

def is_leap(year):
    return year % 4 == 0 and (year % 100 != 0 or year % 400 == 0)

Example usage:

print(is_leap(2000))  # --> True
print(is_leap(1900))  # --> False
print(is_leap(2016))  # --> True

If this answer rings no bells, here is a complete guide on how to figure out leap years in Python.

2. Old-school String Formatting with % Operator

In earlier days, Python string formatting was possible using the % operator followed by a type identifier.

For instance, let’s add a string into another string using %s:

>>> name = "Alice"
>>> "Hello %s" % name
'Hello Alice'

This is positional formatting. It works such that you specify a place for a variable in a string using the % operator. Immediately after that, you specify the type of variable you want to insert.

In the above example, you embed a string into another string with the format specifier %s.

  • The percentage sign means a variable will be inserted in that position.
  • The character ‘s’ shows the type of the inserted variable is string.

In addition to embedding strings into strings, you can embed other types too. To do this, you need to use different format specifiers.

For example, to embed a number into a string, use the %d format specifier:

>>> age = 20
>>> "I am %d years old." % age
'I am 20 years old.'

Or if you want to convert an integer to a string that represents a hexadecimal number, you can use the %x format specifier:

>>> age = 1000
>>> "I am 0x%x years old." % age
'I am 0x3e8 years old.'

However, this formatting style is yesterday’s news.

  • In Python 2.6 and later, you can use .format() method to format strings.
  • As of Python 3.6, you can use formatted strings (F-strings) to format strings in a more elegant way.

An example of the string.format() method in Python 2.6+:

>>> age = 30
>>> "I am {} years old".format(age)
I am 30 years old

A formatted string example in Python 3.6+:

>>> age = 30
>>> f"I am {age} years old"
I am 30 years old

3. Magic Commands in IPython Shell

Magic commands are command-line-like commands that are available in the IPython shell.

But What Is an IPython Shell?

If you are using Jupyter Notebook you definitely know what an IPython shell is.

If you do not know what an IPython shell is, it is an interactive Python shell. It has rich features such as syntax highlighting or code completion. IPython Notebooks (these days Jupyter Notebook) is a popular web-based interactive computational environment. In this environment, you can create, run, visualize and document the code all in the same interactive shell.

Magic Commands in IPython Shell

If you are using Jupyter Notebook, you have to know about magic commands.

For example, you can get the present working directory in the IPython shell using %pwd magic command:

In [1]: %pwd
Out[1]: 'C:\User\Artturi'

This works the same way as the pwd command works in a command-line window.

In IPython, there are two types of magic commands:

  1. Line magics.
  2. Cell magics.

1. Line Magics in IPython

Line magic commands are similar to command-line commands. They start with a singular % character followed by the command without arguments or parenthesis.

These line magics can be used as expressions. Their result can be stored into a Python variable.

2. Cell Magics in IPython

Cell magics operate on multiple lines below the call as opposed to line magics. To call a cell magic command, use a two % operators, %%, followed by the command name.

A cell magic command can make modifications to the input. This input does not even have to be valid in Python. The whole block is received as a string by the cell magic command.

Available Magic Commands in IPython

To get a list of all the available line magics and cell magics, use the %lsmagic command.

For example:

In [1]: %lsmagic
Out[1]: 
Available line magics:
%alias  %alias_magic  %autoawait  %autocall  %autoindent  %automagic  %bookmark
  %cat  %cd  %clear  %colors  %conda  %config  %cp  %cpaste  %debug  %dhist  %d
irs  %doctest_mode  %ed  %edit  %env  %gui  %hist  %history  %killbgscripts  %l
dir  %less  %lf  %lk  %ll  %load  %load_ext  %loadpy  %logoff  %logon  %logstar
t  %logstate  %logstop  %ls  %lsmagic  %lx  %macro  %magic  %man  %matplotlib  
%mkdir  %more  %mv  %notebook  %page  %paste  %pastebin  %pdb  %pdef  %pdoc  %p
file  %pinfo  %pinfo2  %pip  %popd  %pprint  %precision  %prun  %psearch  %psou
rce  %pushd  %pwd  %pycat  %pylab  %quickref  %recall  %rehashx  %reload_ext  %
rep  %rerun  %reset  %reset_selective  %rm  %rmdir  %run  %save  %sc  %set_env 
 %store  %sx  %system  %tb  %time  %timeit  %unalias  %unload_ext  %who  %who_l
s  %whos  %xdel  %xmode

Available cell magics:
%%!  %%HTML  %%SVG  %%bash  %%capture  %%debug  %%file  %%html  %%javascript  %
%js  %%latex  %%markdown  %%perl  %%prun  %%pypy  %%python  %%python2  %%python
3  %%ruby  %%script  %%sh  %%svg  %%sx  %%system  %%time  %%timeit  %%writefile
Automagic is ON, % prefix IS NOT needed for line magics.

How to Use Magic Commands

Listing out all the possible magic commands is useful. But even more useful is knowing how to actually use them. Luckily, you do not need to start googling the magic commands up. Instead, you can use a built-in magic command to get help with any magic commands in IPython:

  • To get help on any line magic command, run %commandname?
  • To get help with a cell magic command, run %%commandname?

For example, let’s see what the line magic %autocall does:

In [11]: %autocall?
Docstring:
Make functions callable without having to type parentheses.
Usage:
   %autocall [mode]
The mode can be one of: 0->Off, 1->Smart, 2->Full.  If not given, the
value is toggled on and off (remembering the previous state).
In more detail, these values mean:
0 -> fully disabled
1 -> active, but do not apply if there are no arguments on the line.
In this mode, you get::
  In [1]: callable
  Out[1]: <built-in function callable>
  In [2]: callable 'hello'
  ------> callable('hello')
  Out[2]: False
2 -> Active always.  Even if no arguments are present, the callable
object is called::
  In [2]: float
  ------> float()
  Out[2]: 0.0
Note that even with autocall off, you can still use '/' at the start of
a line to treat the first argument on the command line as a function
and add parentheses to it::
  In [8]: /str 43
  ------> str(43)
  Out[8]: '43'
# all-random (note for auto-testing)
File:      /usr/local/lib/python3.9/site-packages/IPython/core/magics/auto.py

Or let’s take a look at what the cell magic command %%ruby does:

In [1]: %%ruby?
    ...: 
    ...: 
Docstring:
%%ruby script magic
Run cells with ruby in a subprocess.
This is a shortcut for `%%script ruby`
File:      /usr/local/lib/python3.9/site-packages/IPython/core/magics/script.py

Conclusion

The percentage operator % is used in three ways in Python:

  1. Calculating modulos.
  2. Old-school string formatting.
  3. Magic commands in IPython shell.

Thanks for reading.

Happy coding!

Further Reading

10 Jupyter Notebook Tricks

50 Python Interview Questions

Resources

https://docs.python.org/3/

About the Author

I’m an entrepreneur and a blogger from Finland. My goal is to make coding and tech easier for you with comprehensive guides and reviews.

Recent Posts

Как вывести процент в питоне?

Как вывести процент в питоне например я пишу мини программу в котором пользователе пишут цену продукта, а компьютер должен добавить 15 процентов налога на стоимость товара


  • Вопрос задан

    более двух лет назад

  • 2581 просмотр

Пригласить эксперта

Как пример:

TAX = 0.15
base_price = float(input('Enter the price without tax: '))
final_price = base_price + base_price * TAX
print(f'Price with tax: { final_price }')

?/100*115
Получаем 15 процентов к товару


  • Показать ещё
    Загружается…

25 мая 2023, в 15:24

5000 руб./за проект

25 мая 2023, в 15:24

1500 руб./за проект

25 мая 2023, в 15:11

2000 руб./за проект

Минуточку внимания

Ответ Брайана (пользовательская функция) — это правильная и простая в использовании вещь.

Но если вы действительно хотели определить числовой тип с (нестандартным) оператором «%», например, с помощью калькуляторов стола, так что «X% Y» означает X * Y/100.0, а затем с Python 2.6 и далее вы может переопределить оператор mod():

import numbers

class MyNumberClasswithPct(numbers.Real):
    def __mod__(self,other):
        """Override the builtin % to give X * Y / 100.0 """
        return (self * other)/ 100.0
    # Gotta define the other 21 numeric methods...
    def __mul__(self,other):
        return self * other # ... which should invoke other.__rmul__(self)
    #...

Это может быть опасно, если вы когда-либо использовали оператор «%» в смеси MyNumberClasswithPct с обычными целыми числами или плаваниями.

Что также утомительно в этом коде, вам также нужно определить все 21 другие методы Integral или Real, чтобы избежать следующего раздражающего и непонятного TypeError при его создании

("Can't instantiate abstract class MyNumberClasswithPct with abstract methods __abs__,  __add__, __div__, __eq__, __float__, __floordiv__, __le__, __lt__, __mul__,  __neg__, __pos__, __pow__, __radd__, __rdiv__, __rfloordiv__, __rmod__, __rmul__,  __rpow__, __rtruediv__, __truediv__, __trunc__")

Понравилась статья? Поделить с друзьями:
  • Как найти самое популярное слово
  • Как найти телефон управляющей компании дома
  • Как составить бизнес план на покупку оборудования
  • Как найти клиента мтс
  • Как найти где находится телефон билайн