e (Euler’s number) in Python


In today’s post, we’ll look at two different methods to get the value of e (a.k.a. Euler’s number) in Python.

For our practice question, we’ll work on a function for evaluating Mathematical expressions that contain the Euler’s number. For instance, the function is capable of evaluating strings like '2 + 5e' and '-e + 7'.

Here are some topics we’ll cover in this post:

  • What is the Euler’s number
  • How to get the Euler’s number in Python
  • How to use math.e in Python
  • How to use the built-in exp() function in Python
  • How to ensure that a string only contains certain characters
  • How to use the built-in eval() function in Python

Key Concepts

What is the Euler’s number

The Euler’s number is an irrational constant (approximately equal to 2.71828) named after the Swiss mathematician Leonhard Euler.

It is typically represented as e and has many special properties in Mathematics.

For instance, it is the base of the natural logarithm and the limit of (1 + 1/n)n as n approaches infinity. The exponential function f(x) = ex is also the only function whose derivative is equal to the original function.

A full discussion of the Euler’s number is beyond the scope of this post. If you are interested in finding out more, you can check out the following site: https://www.mathsisfun.com/numbers/e-eulers-number.html.

Due to the importance of e in Mathematics, Python provides us with numerous ways to get its value.

The two main ways to get the value of e in Python is:

  • using math.e, and
  • using the built-in exp() function

Using math.e

The first way is to use the e constant in the math module. This module includes various constants (such as pi and e) that we can use in our Python scripts.

To get the value of e, we type math.e. Let’s look at some examples:

import math

# print the value of e (approximately 2.71828)
print(math.e)

# print the value of e, raised to the power of 2
print(math.e**2)
print(pow(math.e, 2))

Here, we first import the math module on line 1.

Next, we access the constant e by typing math.e, and use the print() function to print its value on line 4.

On line 7, we use the ** operator to raise math.e to the power of 2. This gives us the value of e2 (approximately 7.389).

On line 8, we use the built-in pow() function to do the same, by passing math.e and 2 as arguments to the pow() function.

If you run the code above, you’ll get the following output:

2.718281828459045
7.3890560989306495
7.3890560989306495

Using the built-in exp() function

Besides using math.e to get the value of e, we can use the built-in exp() function in Python. This function is also in the math module. According to the Python documentation, this function is usually more accurate than using the math.e constant.

The syntax is as follows:

math.exp(x)

where x is the power we want to raise e to. For instance, if we want to get the value of e5, we write math.exp(5).

Let’s look at some examples:

import math

# print the value of e to the power of 1
print(math.exp(1))

# print the value of e, raised to the power of 2
print(math.exp(2))

If you run the code above, you’ll get the following output:

2.718281828459045
7.38905609893065

Practice Question

Today’s practice question requires us to write a function called evalExp() that accepts a string containing only spaces, numbers, the letter e, and the ‘+’ and ‘-‘ symbols.

This function first checks if the string contains any invalid character. If it does not, the function treats the string as a mathematical expression and tries to evaluate it. The letter e is evaluated as the Euler’s number.

If the function manages to evaluate the string, it returns the result of the evaluation. Else, it returns False.

Expected Results

To test your function, you can try running the statements below:

print(evalExp('Hello'))
print(evalExp('2 + 5 -'))
print(evalExp('2 + 5'))
print(evalExp('2 + 5e'))
print(evalExp('- e + 7'))

In the fourth statement above, 5e stands for 5 times e.

-e + 7, on the other hand, stands for negative e plus 7.

If you run the code above, you should get the following output:

False
False
7
15.591409142295225
4.281718171540955

Additional Notes

The Python eval() function

An easy way to evaluate a Mathematical expression in Python is to use the built-in eval() function. This function accepts a string and evaluates it as Python code.

For instance, if we want to evaluate the value of 2 + 5, we can pass this Mathematical expression as a string to the eval() function as shown below:

eval('2+5')

If we run the code above, we’ll get 7 as the output.

The eval() function is a very convenient function for evaluating mathematical expressions.

However, it is only able to evaluate valid Python expressions. For instance, it is unable to evaluate the string '2 + 5e', as ‘e’ is not a predefined keyword in Python (we need to write math.e or math.exp(1) if we want the Euler’s number) and multiplication in Python must be indicated with the * symbol.

Hence, if we want to use the eval() function to evaluate the value of '2 + 5e' (where e stands for the Euler’s number), we need to pass '2 + 5*math.e' or '2 + 5*math.exp(1)' as argument to the function.

In addition, the eval() function can be exploited to run malicious code on our system. This is because the function allows us (or our users) to dynamically execute arbitrary Python code. If the string passed to the function contains malicious code, our system can be compromised. Hence, the rule of thumb is to never use it with untrusted input.

With the above in mind, try using the eval() function (or other methods) to complete today’s practice question.

Suggested Solution

The suggested solution for today’s practice question is as follows:

Click to see the suggested solution
import math

def evalExp(s):
    symbols = ' +-'
    numbers = 'e0123456789'
    mathExp = ''
    
    for i in range(len(s)):
        if s[i] not in symbols and s[i] not in numbers:
            return False
        elif s[i] == 'e':
            if i > 0 and s[i-1] in numbers:
                mathExp += '*math.exp(1)'                
            else:
                mathExp += 'math.exp(1)'
        else:
            mathExp += s[i]

    try:
        return eval(mathExp)
    except:
        return False

On line 1, we first import the math module.

Next, we define a function called evalExp() that has one parameter s.

Inside the function, we declare and initialize three strings – symbols, numbers and mathExp.

symbols stores a string that contains all the acceptable symbols for the function. In other words, this string contains a space, a ‘+’ symbol and a ‘-‘ symbol.

numbers, on the other hand, stores all the characters representing acceptable numbers for the function (i.e. the digits 0 to 9 and the constant e).

Last but not least, mathExp stores an empty string.

After initializing our variables, we use a for loop to iterate through s one character at a time.

For each character in s (i.e. s[i]), we use the in keyword to check if it is inside symbols or numbers.

The in keyword checks if a value is present in a sequence (such as a list, tuple or string) and returns True if the value is found. For instance, 't' in 'Python' gives us True as 't' is found in the string 'Python'.

'g' in 'Python', on the other hand, gives us False.

In our evalExp() function, we use the in keyword to check if the current character is a valid character. If it is not in symbols and not in numbers, we know that it is an invalid character. When that happens, the if condition on line 9 evaluates to True and the function returns False (on line 10).

On the other hand, if the character is a valid character, we check if it equals 'e' (line 11). If it equals, we check if there is any number before the letter 'e' (using the if condition on line 12). If there is, the if condition on line 12 evaluates to True and we concatenate '*math.exp(1)' to the variable mathExp (on line 13).

For instance, suppose the expression in s is '5e'. When we encounter the letter 'e', we check if the character before it is a number. In this case, it is the number 5. Hence, we concatenate '*math.exp(1)' with mathExp, which stores the value '5‘ at the moment.

'5e' thus becomes '5*math.exp(1)', which is a valid mathematical expression in Python.

On the other hand, if the character before 'e' is not a number, we concatenate 'math.exp(1)' (without the * sign) with mathExp on line 15.

Last but not least, we move on to the else block (on lines 16 and 17) if the current character is not 'e'. The else block simply concatenates the current character in s to mathExp.

Once we finish iterating through s, mathExp contains an expression where any multiplication in s is represented by the * symbol and any 'e' in s is changed to 'math.exp(1)'.

For instance, if s equals '3e + 6', mathExp equals '3*math.exp(1) + 6'.

Next, we use the try-except statement to try evaluating mathExp. If this is successful, we return the result of the eval() function (in the try block). Else, we return False (in the except block).

With that, the function is complete.

Written by Jamie | Last Updated September 28, 2020

Recent Posts