To be a good programmer, mathematical prowess is not required. The fact of the matter is that most programmers can get away with knowing just elementary algebra. Obviously, the kind of application you are working on will determine the level of mathematical expertise required from you. If you want to become a programmer, you won’t need nearly as much math knowledge as you may think. In general. Although though there isn’t as strong of a connection between math and computer programming as some people would think, numbers are an essential component of any programming language, and Python is not an exception to this rule. You will learn how to do the following at the end of this guide:

Create
integers
and
floatingpoint numbers

Round numbers
to a given number of decimal places 
Format and display numbers in
strings
Let’s get started! Please take note that this walkthrough was based from the section of Python Basics: A Practical Introduction to Python 3 titled “Numbers and Arithmetic.” Check out the video tutorial Python Basics: Numbers and Arithmetic if you’d rather learn the language via a visual medium.
As a result of the fact that the book utilizes Python’s builtin IDLE editor to create and edit Python files as well as communicate with the Python shell, you will notice references to IDLE’s builtin debugging tools throughout the whole of this course. You should, however, not have any difficulty executing the sample code from the editor and environment of your
choice.
Integers and FloatingPoint Numbers
Integers, floatingpoint numbers, and complex numbers are the three kinds of numeric data that are native to the Python programming language. Integers and floatingpoint numbers, which are the two forms of numbers that are used the most often, will be covered in this area of the lesson plan. Complex numbers are covered in the next chapter, so stay tuned for that!
.
Integers
An integer is a whole number that does not have any decimal places after it. To give you an example, the number 1 is an integer, but the number 1.0 is not. You can identify the integer data type by its name, int, which is shown alongside the type symbol ()
:
>>>
>>> type(1)
<class 'int'>
Just entering in the required number will result in the creation of an integer. The expression that follows, for example, will designate the variable num with the number 25.
:
>>>
>>> num = 25
When the number 25 is actually put into the code to produce the integer, this value is referred to as a “integer literal.” When you build an integer in this manner, it is termed an integer literal.
It’s possible that you are already aware with the process of using the int() function to convert a string that contains an integer to a number. For instance, the text “25” may be converted into the number 25 using the following.
:
>>>
>>> int("25")
25
int(“25”) is not a valid example of an integer literal since the value of the integer is derived from a string.
When writing down big numbers by hand, the digits are often arranged in groups of three, with each group being separated by either a comma or a decimal point. The number one million is more simpler to read than the figure one million thousand.
To group digits in an integer literal in Python, you may use underscores (_) instead of commas, since commas cannot be used in this context. The number one million may be expressed as an integer in both of the following ways; each one is legal.
literal:
>>>
>>> 1000000
1000000
>>> 1_000_000
1000000
It may come as a surprise to learn that the size of an integer is not constrained in any way, given that computers only have a limited amount of memory available to them. Try entering the highest number that comes to mind into the interactive window of IDLE and see what happens. Python is able to process it without any problems.
problem!
FloatingPoint Numbers
A number that has a decimal point is referred to as a floatingpoint number, abbreviated as float for short. Both 1.0 and 2.75 are examples of floatingpoint numbers. float is the name of the data type that represents floatingpoint values.
:
>>>
>>> type(1.0)
<class 'float'>
In the same way that integers may be formed from floatingpoint literals, floats can be made by converting strings to floats using the float function ()
:
>>>
>>> float("1.25")
1.25
One may express a floatingpoint literal in one of three different ways. The following each produce a floatingpoint literal with a value of one:
million:
>>>
>>> 1000000.0
1000000.0
>>> 1_000_000.0
1000000.0
>>> 1e6
1000000.0
The first two approaches are very much like the two methods that may be used to create integer literals. The final strategy involves generating a float literal via the use of E notation. Nota bene: E notation is an abbreviation for
exponential notation . You have probably come across this notation, which is used by calculators to express values that are too large to fit on the display screen.
In E notation, a float literal is composed by typing a number, then the letter e, and then another number at the appropriate spot. Python multiplies the number to the left of the e by 10 to the power of the number that comes after the e. This produces the final result. Therefore 1e6 is comparable to 1×10⁶.
In addition, Python makes use of the E notation in order to show huge floatingpoint numbers.
numbers:
>>>
>>> 200000000000000000.0
2e+17
The value that is presented for the float 200000000000000000.0 is 2e+17. The plus sign (plus sign) denotes that the exponent 17 is an integer in the positive range. There is also the option of using negative integers as the
exponent:
>>>
>>> 1e4
0.0001
The literal value of 1e4 is understood as 10 raised to the power 4, which is the same as saying 0.0001 or 1/10000.
Unlike integers, floats do have a maximum size. Your computer’s capabilities will determine the largest floatingpoint number that it can handle, however a figure such as 2e400 should be much beyond the capability of most computers. 2e400 is equal to 2 10400, which is a quantity that is much more than the total number of atoms in the universe.
Python will return a special float value called inf after you have reached the highest possible floatingpoint integer.
:
>>>
>>> 2e400
inf
The message “inf” simply indicates that the number you attempted to generate exceeds the highest possible floatingpoint value that can be stored on your machine. inf is an abbreviation for the word “infinity.” The inf type is still float as of right now.
:
>>>
>>> n = 2e400
>>> n
inf
>>> type(n)
<class 'float'>
inf, which stands for negative infinity and represents a negative floatingpoint number that is greater than the lowest allowed floatingpoint number on your system, is another operator that can be used with Python.
computer:
>>>
>>> 2e400
inf
If you don’t often deal with really big numbers as a programmer, you probably won’t come across the inf and inf operators very frequently. Verify That You Have Comprehended
To validate your comprehension, please expand the following section:
You may see a potential answer by expanding the following section:
You may go to the following step whenever you feel ready to do so.
section.
Arithmetic Operators and Expressions
You are going to learn how to do fundamental arithmetic operations with numbers in Python, such as addition, subtraction, multiplication, and division, in the next part. Along the process, you’ll pick up some guidelines for expressing mathematical expressions in different formats.
code.
Addition
The plus sign is used to indicate addition.
operator:
>>>
>>> 1 + 2
3
The terms “operands” refer to the two numerical values that may be found on each side of the plus sign. Both of the operands in the above example are integers, but it is not required that the types of the operands be the same.
There is no loss of precision when adding an integer to a float.
problem:
>>>
>>> 1.0 + 2
3.0
Take note that the answer to the calculation 1.0 + 2.0 yields the value 3.0, which is a float. When a float is added to a number, the outcome is another float regardless of the size of the original number. When you add two integers together, you will always receive an int as a result. Notice that the recommendation made in PEP 8 is to insert a space between an operator and both of the operands.
Although though Python is perfectly capable of evaluating 1+1, the style 1+1 is recommended since it is often simpler to understand. This general guideline is applicable to each of the operators in this context.
section.
Subtraction
To get the difference between two integers, just place a minus sign () between them.
them:
>>>
>>> 1  1
0
>>> 5.0  3
2.0
When you subtract two numbers, you will always end up with an integer, just as when you add two integers. The result is always a float, regardless of whether or not any of the operands were a float.
The negative sign is also shown by using the minus sign ().
numbers:
>>>
>>> 3
3
You are able to deduct a negative number from another number, but as you will see in the examples that follow, this may not always appear correct.
confusing:
>>>
>>> 1  3
4
>>> 1 3
4
>>> 1 3
4
>>> 13
4
The first example is the one that adheres to PEP 8 the most closely out of the four that were shown. Having said that, you may enclose 3 in parentheses if you want to make it even more obvious that the second – is changing the number 3.
:
>>>
>>> 1  (3)
4
Using parenthesis in your code is a smart move since it helps make the code more clear. Computers execute code, but people read code. Everything that can be done to make your code simpler and easier to comprehend is a step in the right direction.
thing.
Multiplication
Use the asterisk (*) to multiply two integers together.
operator:
>>>
>>> 3 * 3
9
>>> 2 * 8.0
16.0
When you multiply two numbers together, you end up with a new form of number that is subject to the same principles as addition and subtraction. When you multiply two numbers together, you get another integer, and when you multiply a number by a float, you get another float.
.
Division
To divide two numbers, you would use the / operator.
numbers:
>>>
>>> 9 / 3
3.0
>>> 5.0 / 2
2.5
When doing division with the / operator, the result is always a float, in contrast to addition, subtraction, and multiplication. You may use the int() function to convert a number to an integer if you want to be sure that the result of splitting two numbers is an integer.
result:
>>>
>>> int(9 / 3)
3
It is important to keep in mind that the int() function throws away any fractional element of the
number:
>>>
>>> int(5.0 / 2)
2
5.0 divided by 2 yields the floatingpoint value 2.5, whereas int(2.5) yields the integer 2 followed by.5 as the result.
removed.
Integer Division
Python has a second division operator that you may use if writing int(5.0 / 2) sounds too complicated to you. This operator is called the integer division operator (//), which is also known as the floor division.
operator:
>>>
>>> 9 // 3
3
>>> 5.0 // 2
2.0
>>> 3 // 2
2
After performing a division on the number on the left by the number on the right, the / operator rounds the result down to the nearest integer. When one of the integers is negative, the answer you get from this may not be the value you anticipate.
For example, 3 / 2 produces 2 . Secondly, we take 3 and divide it by 2, which gives us 1.5. After that, the value of 1.5 is rounded down to 2. On the other hand, the result of 3 divided by 2 is 1, as both of these numbers are positive.
In addition, the above example demonstrates that / returns a number with floatingpoint precision whenever one of the operands is a float. Because of this, the expression 9 / 3 produces the integer 3, but the expression 5.0 / 2 returns the float 2.0.
Let’s find out what happens if we attempt to divide a number by zero in this example.
:
>>>
>>> 1 / 0
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
ZeroDivisionError: division by zero
You have just attempted to violate a basic rule of the programming language Python, thus the language alerts you with a ZeroDivisionError.
universe.
Exponents
You can take an integer and raise it to a power by using the notation.
operator:
>>>
>>> 2 ** 2
4
>>> 2 ** 3
8
>>> 2 ** 4
16
Exponents don’t have to be integers. They are also able to be.
floats:
>>>
>>> 3 ** 1.5
5.196152422706632
>>> 9 ** 0.5
3.0
That is the same as taking the square root of a number if you raise it to the power of 0.5, but it is important to note that although though the square root of 9 is an integer, Python gives the value 3.0 as the result.
The ** operator will return an integer for positive operands if both operands are integers, but it will return a floatingpoint number if any one of the operands is a floatingpoint number.
One other option is to make the numbers negative.
powers:
>>>
>>> 2 ** 1
0.5
>>> 2 ** 2
0.25
Taking a number to its positive power and then raising that number to its negative power is the same as dividing the positive power number by one. Because of this, 2 ** 1 is equivalent to 1 / (2 ** 1), which in turn is equivalent to 1 / 2, or 0.5. In a similar vein, 2 ** 2 is equivalent to 1 / (2 ** 2), which is equivalent to 1 / 4, which is equal to 0.25.
.
The Modulus Operator
The residual that is obtained by dividing the left operand by the right is the value that is returned by the % operator, also known as the modulus.
operand:
>>>
>>> 5 % 3
2
>>> 20 % 7
6
>>> 16 % 8
0
Since 3 divides 5 once and leaves a leftover of 2, the value of 5% of 3 is 2. In a similar manner, 7 is needed to divide 20 twice, leaving a leftover of 6. In the previous example, 16 may be divided by 8, therefore 16 percent of 8 is 0. The result is always 0 if the number to the left of the percent sign is divisible by the number to the right of the sign.
One of the most prevalent use of the percentage symbol is in the process of determining whether or not one number may be divided by another. For instance, the value of the variable n% 2 must be zero for the integer n to be considered even. What are your thoughts on the 1% with no returns? Try it out with me.
out:
>>>
>>> 1 % 0
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
ZeroDivisionError: integer division or modulo by zero
This makes perfect sense when you consider that 1% 0 represents the fraction that is obtained when 1 is divided by 0. Nevertheless, because 1 cannot be divided by zero, Python throws a ZeroDivisionError in this case. Note: Errors such as ZeroDivisionError don’t really provide much of a challenge while you’re working in the interactive window provided by IDLE. The error is shown, and then a new prompt appears, which enables you to go on writing code despite the problem.
The Python interpreter will halt the execution of a script if it discovers an error while it is being executed. To put it another way, the software
fails to launch. The eighth chapter of
You will learn how to manage mistakes in Python Basics so that your applications do not crash for no apparent reason.
When you employ the % operator with negative values, things may become a little bit complicated.
numbers:
>>>
>>> 5 % 3
1
>>> 5 % 3
1
>>> 5 % 3
2
These outcomes are the end result of a welldefined behavior in Python, which may seem to be surprising at first look. Python makes use of the equation r = x – (y * (x / y)) in order to determine the residual that is left over after dividing an integer by another number.
For instance, in order to find 5% 3, Python first locates the value (5 / 3). If we take 5 / 3 to be about 1.67, then 5 / 3 must equal 2. Now, Python will multiply it by 3 in order to reach the number 6. At the end, Python takes 6 away from 5, which results in 1.
.
Arithmetic Expressions
You may create more complicated expressions by combining different operators. Python can take an expression and calculate it, also known as evaluating it, in order to produce a result. An expression consists of a mix of integers, operators, and parenthesis.
The following are some examples of arithmetic.
expressions:
>>>
>>> 2*3  1
5
>>> 4/2 + 2**3
10.0
>>> 1 + (3*2 + 4)
3
When it comes to evaluating expressions, the rules are exactly the same as those used in regular arithmetic. These laws, which you undoubtedly learnt in school under the term order of operations, are surely still fresh in your mind.
In an expression, the operators *, /, //, and % all have the same precedence, also known as priority; moreover, each of these operators has a greater precedence than the plus and minus operators. This is the reason why the result of 2*3 – 1 is 5, and not 4. Since the operator * has a greater precedence than the – operator, the expression 2*3 is evaluated first.
It’s possible that you’ve noticed that the expressions in the preceding example do not adhere to the rule that states there should be a space on each side of all of the operators. The following is what whitespace in complicated expressions is referred to as in PEP 8:
If several types of operators with varying priorities are employed, placing whitespace around the operators with the lowest priority could be a good idea (ies). Make use of your best judgment, but remember that you should never use more than one space, and that there should always be the same amount of whitespace on both sides of a binary operator. (
) Original Source
The use of parenthesis to indicate the sequence in which operations should be executed is another excellent practice that should be followed, even if the parentheses themselves aren’t required. For example, the result of (2 * 3) – 1 might be understood better than the result of 2*3 – 1.
1.
Make Python Lie to You
What do you suppose the sum of 0.1 and 0.2 is? Is it correct that the answer is 0.3? Let’s hear what the Python programming language has to say about this. Check this out in the interactive
window:
>>>
>>> 0.1 + 0.2
0.30000000000000004
There, there you have it. . . close to being accurate. What the heck is going on at this location? Is Python displaying a problem here?
That’s not a bug, by any means! It’s a problem with the way that Python handles floatingpoint representations, and it has nothing to do with Python. It has something to do with the manner that floatingpoint numbers are stored in the memory of a computer. Please take note that this walkthrough was based from the section of Python Basics: A Practical Introduction to Python 3 titled “Numbers and Arithmetic.” If what you are now reading is interesting to you, I highly recommend that you continue reading the book.
The fraction 1/10 is equivalent to the decimal representation of the value 0.1. The number 0.1 and its fractional representation, 1/10, are both examples of representations in decimal form, often known as representations in base 10. Floatingpoint numbers are stored in computers using a form known as binary representation, which is a more popular name for base2 representation.
The decimal value 0.1 takes on a form that is both recognizable and maybe surprising when it is converted to its binary representation. There is no exact representation of the fraction 1/3 in decimal form. That is, one third is equal to 0.3333… with an endlessly large number of threes after the decimal point. In binary, the fraction 1/10 is represented in exactly the same way.
The following sequence is an indefinitely repeating binary representation of the number 1/10.
fraction:
0.00011001100110011001100110011...
Since there is a limit to the amount of memory that can be kept on a computer, the value 0.1 must be saved as an estimate rather than as its exact value. The amount that is recorded as an estimate is a little bit greater than the real number, and it appears as
this:
0.1000000000000000055511151231257827021181583404541015625
You may have observed, on the other hand, that when you ask Python to print 0.1, it writes 0.1 and not the value that it estimates it should be.
above:
>>>
>>> 0.1
0.1
Python does not just remove the digits from the binary representation of 0.1; it does much more than that. The reality of the situation is a little bit more nuanced.
Since the binary representation of 0.1 is just an approximation, it is quite feasible that more than one decimal number has the same binary approximation. This is because the binary representation of 0.1 is merely an approximation.
As an illustration, the binary approximation of the numbers 0.1 and 0.10000000000000001 are identical. Python will output the decimal value that is the shortest possible and yet shares the approximation.
Because of this, the first example in this section, in which 0.1 and 0.2 are added together, does not equal 0.3. Python performs an operation in which it adds the binary approximations for 0.1 and 0.2, which results in the production of a value that is not the binary approximation for 0.3.
Do not worry if all of this is beginning to make your brain hurt or feel like it is about to explode! You don’t need to be concerned with the imprecision of floatingpoint calculations unless you’re creating applications for the financial industry or scientific computers.
arithmetic.
Math Functions and Number Methods
You can perform a variety of operations on numbers with the help of Python’s builtin functions. You are going to get knowledge on three of the most important
common:

round()
, for rounding numbers to some number of decimal places 
abs()
, for getting the absolute value of a number 
pow()
, for raising a number to some power
You will also get familiar with a technique that may be used with floatingpoint values to determine whether or not they have an integer value.
value.
Round Numbers With
round() is a function that may be used to round a number to the closest whole number.
integer:
>>>
>>> round(2.3)
2
>>> round(2.7)
3
round() exhibits some behavior that is not anticipated when the integer being rounded ends in.5
:
>>>
>>> round(2.5)
2
>>> round(3.5)
4
Two and a half are rounded down to two, whereas three and a half are rounded up to four. Let’s take a closer look at what’s going on here since most people anticipate that a number that ends in.5 will be rounded up to the next whole number.
Python 3 use a method referred to as “rounding ties to even” when it rounds numerical values. Any number whose last digit is the number five is considered to be a tie. There are ties for 2.5 and 3.1415, but not for 1.37.
When rounding numbers that are tied to even, you should begin by examining the digit that is located one decimal place to the left of the last digit in the tie. When that digit is even, it is necessary to round the value down. When the digit is an odd number, you should round the value up. Because of this, 2.5 rounds were reduced to 2, and 3.5 rounds were increased to 4. Note that the rounding approach for floatingpoint values that rounds ties to even is the one that is suggested by the.
Since it helps to lessen the influence that rounding has on operations involving a large number of integers, the IEEE rounding algorithm is recommended by the Institute of Electrical and Electronics Engineers (IEEE).
The IEEE manages a standard that is referred as as
The standard for working with floatingpoint numbers on a computer is known as IEEE 754. It was first published in 1985, but hardware makers continue to make extensive use of it today.
By providing a second parameter to the round function, you may cause a number to be rounded to a specified number of decimal places ()
:
>>>
>>> round(3.14159, 3)
3.142
>>> round(2.71828, 2)
2.72
The number 3.14159 is rounded to three decimal places, which results in the value 3.142, whereas the number 2.71828 is rounded to two decimal places, which results in the value 2.72.
The round() function requires an integer to be sent as its second parameter. In the event that it isn’t, Python throws a TypeError.
:
>>>
>>> round(2.65, 1.4)
Traceback (most recent call last):
File "<pyshell#0>", line 1, in <module>
round(2.65, 1.4)
TypeError: 'float' object cannot be interpreted as an integer
There are situations when round() does not provide the correct result.
right:
>>>
>>> # Expected value: 2.68
>>> round(2.675, 2)
2.67
Since it is precisely in the middle between the numbers 2.67 and 2.68, the value 2.675 is tied for first place. Given that Python rounds tied numbers down to the next even number, you would anticipate that round(2.675, 2) would return 2.68; instead, it actually returns 2.67. This issue is not due to a flaw in the round() function; rather, it is the consequence of a problem with the encoding of floatingpoint numbers.
Working with numbers that are represented by a floating point may be quite unpleasant, but this discomfort is not exclusive to Python. C/C++, Java, and JavaScript, along with any other languages that implement the IEEE floatingpoint standard, are all plagued by the same problems.
Yet, in the majority of situations, the inaccuracies that are caused by floatingpoint values are insignificant, and the outcomes of the round() function are entirely accurate.
useful.
Find the Absolute Value With
If n is a positive integer, then the absolute value of that number is simply n, but if n is a negative number, then the absolute value is n. The absolute value of the number three, for instance, is three, whereas the absolute value of the negative five is five.
Python’s abs function is what you’ll need to utilize in order to determine a number’s absolute value ()
:
>>>
>>> abs(3)
3
>>> abs(5.0)
5.0
abs() will never return a negative number and will always return a number of the same type as its input. To put it another way, the absolute value of an integer is always a positive integer, and the absolute value of a float is always a positive number.
float.
Raise to a Power With
Earlier on, you gained knowledge on how to use the ** operator to take an integer and increase it to a power. You may easily do the same thing by using the pow() function.
pow() requires two parameters to be sent in. The first argument is referred to as the base, which is the number that is going to be raised to a certain power, and the second argument is referred to as the exponent, which is the power to which the number is going to be raised.
The following is an example of using the pow() function to increase 2 to the exponent 3:
:
>>>
>>> pow(2, 3)
8
The exponent in pow() may be anything, just as it is with **.
negative:
>>>
>>> pow(2, 2)
0.25
So, what’s the difference between the pow() function and the ** operator?
The pow() function allows for a third argument to be sent in as an optional parameter. When this parameter is present, the function first calculates the first number multiplied by the power of the second number and then takes the modulo with regard to the third number. To put it another way, the expression (x ** y)% z is the same as pow(x, y, z).
In the following illustration, x equals 2, y equals 3, and z equals 2:
:
>>>
>>> pow(2, 3, 2)
0
To begin, 8 is calculated by raising 2 to the power of 3. After that, 8% of 2 is computed, which equals 0, given that 2 cannot divide 8 without a remainder.
remainder.
Check if a Float Is Integral
It’s possible that you are already acquainted with string operations such as.lower(),.upper(), and.find(). Methods may be used to integers as well as floatingpoint quantities.
The use of numerical approaches is not particularly common, but there is at least one that may be helpful. Floatingpoint numbers include a method called.is integer(), which returns Yes if the number is integral, which means it does not have any fractional parts, and False if the number does contain fractional parts.
:
>>>
>>> num = 2.5
>>> num.is_integer()
False
>>> num = 2.0
>>> num.is_integer()
True
Validating user input is one of the many applications for the.is integer() function. If you were developing an app for a pizza parlor that allowed customers to place orders online, for instance, you would want to ensure that the number of pizzas ordered by the consumer is always a whole number.
Since the round(), abs(), and pow() functions are builtin, you do not need to import anything in order to use them in your code. Yet, these three methods are just the tip of the iceberg when it comes to all of the functions that are available in Python for dealing with numbers.
Check also the article The Python math Module: All You Need to Know for much more exciting mathematical content! Verify That You Have Comprehended
To validate your comprehension, please expand the following section:
You may see a potential answer by expanding the following section:
You may go to the following step whenever you feel ready to do so.
section.
Print Numbers in Style
To be able to show a user numbers, it is necessary to put the numbers into a string. With fstrings, you may do this by enclosing a variable that is assigned to a number with curly brackets.
braces:
>>>
>>> n = 7.125
>>> f"The value of n is {n}"
'The value of n is 7.125'
These curly brackets provide support for a simple formatting language, which you may use to modify the way the value appears in the formatted string after it has been created.
For instance, to format the value of n in the preceding example to include two decimal places, change the contents of the curly brackets in the fstring with n:.2f. This may be done by following the steps outlined above.
:
>>>
>>> n = 7.125
>>> f"The value of n is {n:.2f}"
'The value of n is 7.12'
After the variable n, there is a colon (:), which signifies that anything that comes after it is a part of the formatting specification. In this particular example, the formatting standard is written as.2f.
The number is rounded to two decimal places because of the.2 in the notation, and Python is instructed to represent n as a fixedpoint integer because of the f. This indicates that the number is presented with precisely two decimal places, despite the fact that the actual value may have less decimal places than this.
The answer given by “n:.2f” is 7.12 when n is equal to 7.125. When formatting integers inside strings, Python rounds ties to even, much as it does with the round() function. So, if you change the value of n from 7.125 to 7.126, the answer to the “n:.2f” equation will be 7.13.
:
>>>
>>> n = 7.126
>>> f"The value of n is {n:.2f}"
'The value of n is 7.13'
Replace.2 with.1 to round the number to the nearest whole number.
:
>>>
>>> n = 7.126
>>> f"The value of n is {n:.1f}"
'The value of n is 7.1'
When you choose the fixed point format for a number, the number will always be presented with the exact number of decimal places that you choose.
specify:
>>>
>>> n = 1
>>> f"The value of n is {n:.2f}"
'The value of n is 1.00'
>>> f"The value of n is {n:.3f}"
'The value of n is 1.000'
You may use commas to group the integer portion of huge numbers by the thousands by inserting them before the, symbol.
option:
>>>
>>> n = 1234567890
>>> f"The value of n is {n:,}"
'The value of n is 1,234,567,890'
Use a comma before the to round to a certain number of decimal places and also group the result by thousands. in the manner of your formatting
specification:
>>>
>>> n = 1234.56
>>> f"The value of n is {n:,.2f}"
'The value of n is 1,234.56'
Displaying currency correctly requires the inclusion of the specifier,.2f.
values:
>>>
>>> balance = 2000.0
>>> spent = 256.35
>>> remaining = balance  spent
>>> f"After spending ${spent:.2f}, I was left with ${remaining:,.2f}"
'After spending $256.35, I was left with $1,743.65'
Another helpful choice is %, which represents a percentage when it is employed in a sentence. A number is multiplied by 100 before being shown in fixedpoint format and accompanied by a percentage sign when the % option is selected.
You are not allowed to combine the f option with the % option, since the % option must always come at the very end of your formatting specification. For instance, 1% shows a number as a percentage with precisely one decimal place after the integer.
place:
>>>
>>> ratio = 0.9
>>> f"Over {ratio:.1%} of Pythonistas say 'Real Python rocks!'"
"Over 90.0% of Pythonistas say 'Real Python rocks!'"
>>> # Display percentage with 2 decimal places
>>> f"Over {ratio:.2%} of Pythonistas say 'Real Python rocks!'"
"Over 90.00% of Pythonistas say 'Real Python rocks!'"
The micro language for formatting is quite robust and comprehensive. You have just been exposed to the fundamentals so far. Check out the official documentation if you need any further information. Verify That You Have Comprehended
To validate your comprehension, please expand the following section:
You may see a potential answer by expanding the following section:
You may go to the following step whenever you feel ready to do so.
section.
Complex Numbers
Complex numbers can be handled natively in Python, making it one of the few programming languages that can make that claim. Python’s support for complex numbers is one of the programming language’s strengths, despite the fact that complex numbers seldom arise outside of the realms of scientific computing and computer graphics.
If you’ve ever attended a math lesson as advanced as precalculus or higherlevel algebra, you may recall that a complex number is a number that consists of two different components: a real portion and an imaginary part.
Just writing the real portion of the number, followed by a plus sign, then the imaginary component with the letter j at the end will result in the creation of a complex number in Python.
end:
>>>
>>> n = 1 + 2j
If you look closely, you’ll see that Python encloses the number in brackets when you investigate the value of n.
parentheses:
>>>
>>> n
(1+2j)
Because of this standard, there is less chance of misunderstanding over whether the output being presented is a string or a mathematical equation.
Imaginary numbers have two properties built into them:.real and.imag. These properties, which return the real and imaginary parts of the number, are called.real and.imag respectively.
respectively:
>>>
>>> n.real
1.0
>>> n.imag
2.0
It is important to note that even though the real and imaginary components were both supplied as integers, Python nevertheless delivers them as floats.
In addition, complex numbers include a function called.conjugate(), which returns the complex conjugate of the number.
number:
>>>
>>> n.conjugate()
(12j)
The conjugate of any complex number is another complex number that has the same real portion but an imaginary part that is equal in absolute value but has the opposite sign. This means that the conjugate of every complex number has the same real part. Thus, the complex conjugate of 1 plus 2j is 1 minus 2j in this instance.
The.real and.imag properties, unlike the.conjugate() method, do not need the addition of parentheses after their names.
The.conjugate() method is a function that does an operation on a complex number. In contrast, the.real and.imag methods do not execute any operations; instead, they just return some information on the number.
The difference between methods and properties is an essential part of objectoriented programming, thus it’s crucial to make the distinction between the two.
All of the arithmetic operators that operate with floats and integers will also function with complex numbers; the only exception is the floor division operator (//), which does not work with complex numbers. We won’t get into the specifics of how to do complicated arithmetic here since this isn’t a lesson on advanced mathematics. Instead, I will demonstrate several applications of arithmetic using complex numbers below.
operators:
>>>
>>> a = 1 + 2j
>>> b = 3  4j
>>> a + b
(42j)
>>> a  b
(2+6j)
>>> a * b
(11+2j)
>>> a ** b
(932.1391946432212+95.9465336603415j)
>>> a / b
(0.2+0.4j)
>>> a // b
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: can't take floor of complex number.
Curiously, while this shouldn’t come as a surprise from a mathematical standpoint, int and float objects both have the.real and.imag attributes, in addition to the.conjugate property ()
method:
>>>
>>> x = 42
>>> x.real
42
>>> x.imag
0
>>> x.conjugate()
42
>>> y = 3.14
>>> y.real
3.14
>>> y.imag
0.0
>>> y.conjugate()
3.14
When used to floats and integers, the.real and.conjugate() functions will always return the actual value, while.imag will always return 0. n.real and n.imag both return an integer if n is already an integer, but they return a float if n is already a float. This is something to keep in mind.
After going through the fundamentals of complex numbers with me, you’re probably wondering why you’d ever need to make use of them in the real world. Whether you are studying Python for web development, data research, or generalpurpose programming, the fact is that you may never need to utilize complex numbers. This is especially true if you are learning Python for generalpurpose programming.
On the other hand, complex numbers play a vital role in a variety of computerrelated fields, including scientific computing and computer graphics. Should you ever find yourself working in any of these fields, you may find that Python’s inbuilt support for complex numbers comes in handy.