2

So I have an application in Python that calculates the variable number in the "PV = nRT" chemical equation. The code is like this:

r = 0.082
# Variables
p = float(input('Pressure = '))
p_unit = input('Unit = ')

print('_____________________')

v = float(input('Volume = '))
v_unit = input('Unit = ')

print('_____________________')

n = float(input('Moles = '))

print('_____________________')

t = float(input('Temperature = '))
t_unit = input('Unit = ')

# Unit Conversion
if p_unit == 'bar':
    p = p * 0.987

if v_unit == 'cm3':
    v = v / 1000

if v_unit == 'm3':
    v = v * 1000

if t_unit == 'c':
    t = t + 273

if t_unit == 'f':
    t = ((t - 32) * (5 / 9)) + 273


# Solve Equation
def calc():
    if p == 000:
        return (n * r * t) / v
    if v == 000:
        return (n * r * t) / p
    if n == 000:
        return (p * v) / (r * t)
    if t == 000:
        return (p * v) / (n * r)

and then at the end I run the function to get the result. But the problem is I want to convert the result to a Scientific Number (e.g. 0.005 = 5 x 10^-3). I tried the solution below:

def conv_to_sci(num):
    i = 0
    if num > 10:
        while num > 10:
            num / 10
            i = i - 1
    if num < 10:
        while num < 10:
            num * 10
            i = i + 1
    return num + "x 10^" + i

but it didn't work. Any questions?

  • 1
    Does this answer your question? [Display a decimal in scientific notation](https://stackoverflow.com/questions/6913532/display-a-decimal-in-scientific-notation) – Diane M Nov 13 '20 at 08:25
  • Probably you wanted to modify `num` with the instructions `num / 10` and `num * 10`? You have to use `/=` or `*=` to modify a variable in-place. – Frank Nov 13 '20 at 08:34

2 Answers2

1

I'd just use numpy to get scientific notation

import numpy as np
num = 0.005
num_sc = np.format_float_scientific(num)
>>> num_sc
'5.e-03'
aarribas12
  • 416
  • 1
  • 4
  • 12
  • 1
    numpy is a big dependency for just that. There are imho better fits in the standard library – Diane M Nov 13 '20 at 08:25
  • @ArthurHv you're right. Maybe i'd be better to use Decimal right? I've made some research and with '%.2E' % Decimal('your_num') you can print the scientific notation but you won't be able to operate with it as it is a plain string. – aarribas12 Nov 13 '20 at 08:29
1

Use str.format

"{:.0e}".format(0.005)

This will print: '5e-03'

Or,

def conv_to_sci(num):
    i = 0
    while int(num) != num:
        num *= 10
        i += 1
    return "{0} x 10^{1}".format(int(num), i)
conv_to_sci(0.005)

Will give: '5 x 10^3'

ErdoganOnal
  • 800
  • 6
  • 13