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

Столкнулся с такой проблемой, мне нужно было узнать сколько 30% от числа 0.000175.

Написал я 0.000175 / 100 * 30, а python говорит что это 5.25е-05, но это не 30%, если делать это через калькулятор, то выходит 0.0000525.

Либо это я тупой и ничего не понимаю либо тут что-то не так.

gil9red's user avatar

gil9red

76.3k6 золотых знаков51 серебряный знак117 бронзовых знаков

задан 6 авг 2018 в 13:16

Zlatex's user avatar

3

Выводите значение в строку через форматирование с указанным количеством знаков после запятой (в данном примере 10 знаков)

print('{:.10f}'.format(0.000175 / 100 * 30))  # '0.0000525000'
print(f'{0.000175 / 100 * 30:.10f}')          # '0.0000525000'

Если не нравятся дополнительные 0 из-за большой точности, то можно их убрать (костылем):

value = '{:.10f}'.format(0.000175 / 100 * 30)
print(value)              # '0.0000525000'
print(value.rstrip('0'))  # '0.0000525'

Точность можно не указывать, но тогда может быть округление, как в примере ниже:

value = '{:f}'.format(0.000175 / 100 * 30)
print(value)  # '0.000053'

ответ дан 6 авг 2018 в 13:23

gil9red's user avatar

gil9redgil9red

76.3k6 золотых знаков51 серебряный знак117 бронзовых знаков

5.25е-05 = 5.25 * 10^-5 = 0.0000525

Если вам сложно понимать такое представление чисел, то изучите форматирование. Источник.

print( '%f!' % (0.000175 / 100 * 30) )

Таким образом вы сможете получить вывод в той форме, которая вам требуется. Но изучить экспоненциальную запись также полезно, с ней ваш код будет выглядеть более солидно)

ответ дан 6 авг 2018 в 13:41

sevnight's user avatar

sevnightsevnight

5821 золотой знак5 серебряных знаков25 бронзовых знаков

С дробными, целыми и знаком / нужно быть аккуратней.

print 100/3
33

Обратитесь к модулю decimal или например можно заменить знак деления на умножение и степень, в этом случае работает корректно:

print 0.000175 *(100)**-1 * 30
# 5.25e-05

print '{:.7f}'.format(0.000175 *(100)**-1 * 30)
# '0.0000525'

ответ дан 6 авг 2018 в 13:24

Eugene Dennis's user avatar

Eugene DennisEugene Dennis

2,4721 золотой знак8 серебряных знаков14 бронзовых знаков

1

John on April 21, 2021

To get a percentage of two numbers in Python, divide them using the division operator (/) then multiply the result by 100 using the Python multiplication operator (*).

To demonstrate this, let’s get the percentage of 3 out of 9 using Python.

percent = 3 / 9 * 100

print(percent)
33.33333333333333

Python Percentage Function

If you need to get percentages many times in your program, it may be worth creating a small helper function.

def getPercent(first, second, integer = False):
   percent = first / second * 100
   
   if integer:
       return int(percent)
   return percent

print(getPercent(3, 9))
33.33333333333333

With the above function, to get an integer back pass True as the third argument.

def getPercent(first, second, integer = False):
   percent = first / second * 100
   
   if integer:
       return int(percent)
   return percent

print(getPercent(3, 9, True))
33

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 процентов налога на стоимость товара


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

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

  • 2560 просмотров

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

Как пример:

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 процентов к товару


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

19 мая 2023, в 16:45

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

19 мая 2023, в 16:10

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

19 мая 2023, в 16:08

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

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

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

Но если вы действительно хотели определить числовой тип с (нестандартным) оператором “%”, например, с помощью калькуляторов стола, так что “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__")

Добавить комментарий