Python multiply int and float

Работа с числами в Python

В этом материале рассмотрим работу с числами в Python. Установите последнюю версию этого языка программирования и используйте IDE для работы с кодом, например, Visual Studio Code.

В Python достаточно просто работать с числами, ведь сам язык является простым и одновременно мощным. Он поддерживает всего три числовых типа:

Хотя int и float присутствуют в большинстве других языков программирования, наличие типа комплексных чисел — уникальная особенность Python. Теперь рассмотрим в деталях каждый из типов.

Целые и числа с плавающей точкой в Python

В программирование целые числа — это те, что лишены плавающей точкой, например, 1, 10, -1, 0 и так далее. Числа с плавающей точкой — это, например, 1.0, 6.1 и так далее.

Создание int и float чисел

Для создания целого числа нужно присвоить соответствующее значение переменной. Возьмем в качестве примера следующий код:

Читайте также:  Сортировка в php sort

Здесь мы присваиваем значение 25 переменной var1 . Важно не использовать одинарные или двойные кавычки при создании чисел, поскольку они отвечают за представление строк. Рассмотрим следующий код.

В этих случаях данные представлены как строки, поэтому не могут быть обработаны так, как требуется. Для создания числа с плавающей точкой, типа float , нужно аналогичным образом присвоить значение переменной.

Здесь также не стоит использовать кавычки.

Проверить тип данных переменной можно с помощью встроенной функции type() . Можете проверить результат выполнения, скопировав этот код в свою IDE.

 
var1 = 1 # создание int
var2 = 1.10 # создание float
var3 = "1.10" # создание строки
print(type(var1))
print(type(var2))
print(type(var3))

В Python также можно создавать крупные числа, но в таком случае нельзя использовать запятые.

 
# создание 1,000,000
var1 = 1,000,000 # неправильно

Если попытаться запустить этот код, то интерпретатор Python вернет ошибку. Для разделения значений целого числа используется нижнее подчеркивание. Вот пример корректного объявления.

 
# создание 1,000,000
var1 = 1_000_000 # правильно
print(var1)

Значение выведем с помощью функции print :

Арифметические операции над целыми и числами с плавающей точкой

Используем такие арифметические операции, как сложение и вычитание, на числах. Для запуска этого кода откройте оболочку Python, введите python или python3 . Терминал должен выглядеть следующим образом:

Python IDLE

Сложение

В Python сложение выполняется с помощью оператора + . В терминале Python выполните следующее.

Результатом будет сумма двух чисел, которая выведется в терминале.

Работа с числами в Python

Теперь запустим такой код.

В нем было выполнено сложение целого и числа с плавающей точкой. Можно обратить внимание на то, что результатом также является число с плавающей точкой. Таким образом сложение двух целых чисел дает целое число, но если хотя бы один из операндов является числом с плавающей точкой, то и результат станет такого же типа.

Вычитание

В Python для операции вычитания используется оператор -. Рассмотрим примеры.

>>> 3 - 1 2 >>> 1 - 5 -4 >>> 3.0 - 4.0 -1.0 >>> 3 - 1.0 2.0

Положительные числа получаются в случае вычитания маленького числа из более крупного. Если же из маленького наоборот вычесть большое, то результатом будет отрицательно число. По аналогии с операцией сложения при вычитании если один из операндов является числом с плавающей точкой, то и весь результат будет такого типа.

Умножение

Для умножения в Python применяется оператор * .

>>> 8 * 2 16 >>> 8.0 * 2 16.0 >>> 8.0 * 2.0 16.0

Если перемножить два целых числа, то результатом будет целое число. Если же использовать число с плавающей точкой, то результатом будет также число с плавающей точкой.

Деление

В Python деление выполняется с помощью оператора / .

>>> 3 / 1 3.0 >>> 4 / 2 2.0 >>> 3 / 2 1.5

В отличие от трех предыдущих операций при делении результатом всегда будет число с плавающей точкой. Также нужно помнить о том, что на 0 делить нельзя, иначе Python вернет ошибку ZeroDivisionError . Вот пример такого поведения.

>>> 1 / 0 Traceback (most recent call last): File "", line 1, in ZeroDivisionError: division by zero

Деление без остатка

При обычном делении с использованием оператора / результатом будет точное число с плавающей точкой. Но иногда достаточно получить лишь целую часть операции. Для этого есть операции интегрального деления. Стоит рассмотреть ее на примере.

Результатом такой операции становится частное. Остаток же можно получить с помощью модуля, о котором речь пойдет дальше.

Остаток от деления

Для получения остатка деления двух чисел используется оператор деления по модулю % .

>>> 5 % 2 1 >>> 4 % 2 0 >>> 3 % 2 1 >>> 5 % 3 2

На этих примерах видно, как это работает.

Возведение в степень

Число можно возвести в степень с помощью оператора ** .

Комплексные числа

Комплексные числа — это числа, которые включают мнимую часть. Python поддерживает их «из коробки». Их можно запросто создавать и использовать. Пример:

Источник

How to Multiply in Python

In mathematics, we use the symbol × to multiply numbers. It is the standard symbol for multiplication and it is called the multiplication sign. When we put the Python programming language into the picture, the symbol disappears but the multiplication fundamentals remain the same. In this post, you’ll learn how to multiply in Python.

To multiply numbers in Python, we use the multiplication operator *. It is made up of just an asterisk. If it appears between two numbers in Python, those numbers will multiply each other.

For example, if we type 3 * 5 in the Python Interactive Shell, we will get 15 as the output. It does not matter if these numbers are of different types, they can still multiply each other. For example, a float can multiply an integer, and vice versa.

If you want to learn more about how to use the multiplication operator to perform multiplication operations in Python, stick around because this post will exhaust everything you need to know to perform meaningful multiplication programs in your code.

Table of Contents

What is the multiplication operator in python?

What is the multiplication operator in python?

In Python, the multiplication operator is an asterisk ( * ). If it appears between two numbers of any type in Python, those numbers will multiply each other.

In the order of precedence, it comes after parentheses and exponentiation according to the PEMDAS rule. This means that if they appear together in the same mathematical expression, the first two will be calculated first then the multiplication. The multiplication operator has the same precedence as the division operator.

In the following sections, we will look at different case scenarios where the multiplication operator can be of great use.

>>>2 * 3 6 >>>4.0 * 2 8.0 >>> 2 * 6 * 3 * 5 * 7 1260 >>> 4 * 4 * 4 64 >>> 4 ** 3 64 

Multiply in Python: Numbers by Numbers

How to Multiply in Python. What is 3 times 9

In this section, we will put the Python multiplication operator to the test by creating a few Python programs that multiply numbers.

Python program to multiply numbers

In this section, we create a Python program that multiplies two numbers. These numbers are stored in variables. Then the Python multiplication operator is used to multiply them.

factor1 = 21 factor2 = 3 print(factor1 * factor2)

Python program to multiply numbers from User Input

In this section, we create a Python program that multiplies numbers from User Input. In other words, we create a multiplication calculator because it multiplies numbers that have been inputted by the user.

➊factor1 = input('Enter the multiplicand: ') ➋factor2 = input('Enter the multiplier: ') ➌product = float(factor1) * float(factor2) ➍print(f' times is: ')
> Enter the multiplicand: 21 > Enter the multiplier: 3 21 times 3 is 63.0

At ➊ and ➋, we use the input() function to get 2 numbers from the input. We just used 2 numbers here for simplicity, but in Python, just as in High school math, you can multiply as many numbers as you want.

At ➌, we convert the given number into a floating point number using the float() function. We convert the input into numbers because the input() function returns strings and yet we can not perform real mathematical multiplication on strings. We also convert these numbers specifically into float types to increase the accuracy of multiplication operations. If we use int() , it will round off the numbers to the nearest whole number and remove all numbers after the comma. That way, the calculation will not be correct if a user inputs a decimal number.

We then perform the multiplication using the Python multiplication operator and we store it in the product variable.

At ➍, we print out the value of the product variable. If you look at the output you see the nicely formatted 21 times 3 is 63.0 . We did this with the help of Python f strings. Of their many uses, f strings allow us to insert variables inside strings. You can learn more about them from FreeCodeCamp’s guide on f strings.

Create a Python function to multiply two numbers

A function is a block of code that performs a specified task. Functions can be used over and over without repeating the same code. In this section, we create a Python function that multiplies two numbers. It takes in two numbers and returns the product of those numbers. Below is a simplified function that does that:

def multiply( num1, num2): return num1 * num2

We use the def keyword to create a function called multiply . This is a good name because it is not a Python keyword and it describes concisely what our function does which is to multiply two numbers together. The function takes two arguments. The function then returns the product of these numbers.

We can then use the above function in many different cases in the same file. Let’s take a look at some case scenarios:

We can call it multiple times without rewriting the same code.

print(multiply(3, 5)) print(multiply(5, 8)) print(multiply(3, 9))

We can use it in other code blocks like for loops and if statements.

How to Improve the Python function to multiply two numbers

You can improve the above function by:

  1. Giving errors if the parameters used are not valid numbers.
  2. Converting the arguments into the preferred number types.
  3. Allow unlimited parameters to be entered.

FAQs on How to Multiply In Python

Does Python do multiplication first?

No. Python does not do the multiplication first. According to the PEMDAS rule which stands for Parentheses, Exponentiation, Multiplication, Division, Addition, and Subtraction, you can see that multiplication comes third after Parentheses and Exponentiation. This means that if a math expression contains all arithmetic operations, multiplication will be done after operations in brackets and exponentiation has been done first.

How do you multiply multiple numbers in Python?

The Python multiplication operator ( * ) is not limited to multiplying two numbers only at the same time. You can use it for as many numbers as you want in a single multiplication expression. So to multiply multiple numbers in Python, just use the multiplication operator for as many numbers as you want. For example, 2*6*3*5*7 is the same as 2 times 3 times 4 times 5 times 6 and the answer will be 1260.

How do you multiply a number by itself in Python?

To multiply a number by itself in Python, you can use the multiplication operator on the same number as many times as you want. For example, 4*4*4 is multiplying the number 4 by itself 3 times which gives us 64. Alternatively, you can use the exponentiation operator ( ** ) between two numbers. The number on the left is the one that is multiplying itself and the number on the right is the number of times that the number on the left should multiply itself. So 4*4*4 can also be written as 4**3 . The latter can be read as 4 to the exponent of 3.

Wrap up on How to multiply in Python.

That was it for this tutorial. I hope you learned a lot. To wrap this up, we said we use the multiplication operator which is made of a single asterisk in Python to perform multiplication operations. Multiplication operations come after parentheses and exponentiation but it has the same precedence as division. You can multiply as many numbers as you want in a single multiplication operation; they are not limited to two numbers only. You can use the exponentiation operator (**) to multiply a number by itself. And that’s it. I’ll see you in other CodingGear tutorials. Peace!

Источник

Оцените статью