Что такое float в python
Перейти к содержимому

Что такое float в python

  • автор:

Pythonista. Привет, Python

Доброго времени суток, Хабр. Запускаю короткий курс статей, который охватывает ключевые навыки Python, необходимые для изучения Data Science. Данные статьи подойдут для тех, кто уже имел опыт в программировании и хочет добавить Python в свою копилку навыков.

Привет, Python!

Python был назван в честь популярного британского комедийного телешоу 1970-х «Летающий цирк Монти Пайтона», поскольку автор был поклонником этого телешоу.

Просто ради удовольствия попробуйте прочитать приведенный ниже код и предсказать, что он будет делать при запуске. (Если вы не знаете, это нормально!) Он приурочен скетчу Монти Пайтона про спам.

But I don`t want ANY spam!

Spam Spam Spam Spam

Эта забавная программа демонстрирует многие важные аспекты того, как выглядит код Python и как он работает. Давайте подробнее рассмотрим код.

Присвоение переменной: здесь мы создаем переменную с именем spam_amount и присваиваем ей значение 0 используя = , что называется оператором присваивания.

Обратите внимание: если вы программировали на других языках (например, Java или C ++), вы могли заметить некоторые вещи, которые Python не требует от нас здесь:

• нам не нужно объявлять spam_amount перед присвоением ему значения

• нам не нужно указывать Python, на какой тип значения будет ссылаться spam_amount . Фактически, мы даже можем переназначить spam_amount для обозначения другого типа вещей, таких как строка или логическое значение.

Вызов функций: print — это функция Python, которая отображает на экране переданное ей значение. Мы вызываем функции, добавляя круглые скобки после их имени и помещая входные данные (или аргументы) функции в эти скобки.

Первая строка выше — это комментарий. В Python комментарии начинаются с символа # .

Далее мы видим пример переопределения. Переопределение значения существующей переменной выглядит так же, как создание новой переменной — по-прежнему используется оператор присваивания = .

В этом случае значение, которое мы присваиваем spam_amount , включает простое арифметическое действие с его предыдущим значением. Когда он встречает эту строку, Python оценивает выражение в правой части = (0 + 4 = 4), а затем присваивает это значение переменной в левой части.

Мы будем говорить об «условных выражениях» позже, но, даже если вы никогда раньше не программировали, вы, вероятно, можете догадаться, что тут происходит. Python ценится за его комфортность кода и простоту.

Обратите внимание, как мы указываем, какой код принадлежит if . «But I don’t want ANY spam! » выведется, только если spam_amount положительный. Но дальше (например, print (viking_song) ) код должен выполняться несмотря ни на что. Как мы (и Python) это различаем?

Двоеточие ( : ) в конце строки if указывает, что начинается новый «блок кода». Последующие строки с отступом являются частью этого блока кода. Некоторые другие языки используют < фигурные скобки >для обозначения начала и конца блоков кода. Использование в Python значимых пробелов может удивить программистов, которые привыкли к другим языкам, но на практике это приводит к более согласованному и читаемому коду, чем языки, которые не требуют отступов блоков кода.

Последующие строки, относящиеся к viking_song , не имеют отступа с дополнительными 4 пробелами, поэтому они не являются частью блока кода if . Мы увидим больше примеров блоков кода с отступом позже, когда мы будем определять функции и использовать циклы.

Этот фрагмент кода также является нашим первым знакомством со строками в ​​Python:

Строки можно помечать двойными или одинарными кавычками. (Но поскольку эта конкретная строка содержит символ одинарной кавычки, мы можем запутать Python, пытаясь заключить ее в строку, если мы не будем осторожны.)

Оператор * можно использовать для умножения двух чисел ( 3 * 3 равно 9), но, что довольно интересно, мы также можем умножить строку на число, чтобы получить версию, которая повторяется столько раз. Python разрешает несколько маленьких трюков, подобных этому, где операторы типа * и + имеют разное значение в зависимости от того, к чему они применяются. (Технический термин для этого — перегрузка оператора)

Числа и арифметика в Python

Мы уже видели пример переменной, содержащей число выше:

«Число» — неформальное название для такого рода вещей, но если мы хотим быть более техническими, мы можем спросить Python, как он описывает тип вещи, которым является spam_amount :

Здесь int — сокращение от integer. Есть еще один вид чисел, с которым мы часто сталкиваемся в Python:

float — это число с плавающей точкой, которое очень полезно для представления таких вещей, как вес или пропорции.

type() — еще одна встроенная функция, которую мы встречаем (после print() ), и ее следует запомнить. Очень полезно иметь возможность спросить Python «к какому типу вещей относиться это?».

Естественное желание действий с числами — выполнять арифметические операции. Мы видели оператор + для сложения и оператор * для умножения. Python также покрывает остальные основные кнопки вашего калькулятора:

What is a Float in Python and How Does it Benefit Programmers

Business Analyst Salary

Guido Van Rossum, the creator of the Python programming language, said, “Python is an experiment in how much freedom programmers need. Too much freedom and nobody can read another’s code; too little and expressiveness is endangered.” No wonder Python is so popular. According to Statista, it is the fourth-most utilized programming language by developers worldwide in 2022. Here’s why. It offers flexibility and high scalability and has numerous in-built libraries and functions that make it easier for software developers. One of the most commonly used in-built functions in Python is float. You’re probably wondering: What is a float in Python and why is it used? Let’s dive in and find out.

explore online courses

What is a Float in Python?

Float is a function or reusable code in the Python programming language that converts values into floating point numbers. Floating point numbers are decimal values or fractional numbers like 133.5, 2897.11, and 3571.213, whereas real numbers like 56, 2, and 33 are called integers. Using the float function in Python on a specific value will convert it into a decimal number or fractional form. In simple terms, the purpose of the float function in Python is to convert real numbers or integers into floating point numbers.

Here is an example to help you better understand a float() function.

And run the program, the value of x will be 56.0.

Float() Syntax

Syntax in a programming language is the rule that defines how symbols or characters should be arranged to create a correct statement and run the code. Just like we have different characters for writing different languages, programming languages use their own symbols called syntax. It is a predefined set of rules that explains how developers should write and interpret a program in Python. These rules are essential to determine the structure of the language and maintain uniformity.

The syntax of float in Python is float(value). Here, value is a number or a string that you want to convert into a decimal. So, when you want to use the float function to convert integers into floating numbers, you must type float and add the numerical value. However, you will have to add single or double quotation marks inside the bracket for strings (arrays of bytes representing Unicode characters).

Float() Parameters

Programming parameters are variables used at different places and refer to a specific input or value. Float() parameters mean the name given to the float function in Python. For example, if you type float function: float(x) in the program, x is the variable or the parameter with a specific integer, string, or floating value. Its value keeps on changing depending on the input you provide.

Float() Return Value

Simply put, the float() return value is the result or output of the float function. If you don’t use a parameter or value while performing the float function, you will get a 0.0 return value. For example if you type print(float(248)), the output will be 248.0 which is the float() return value.

How Does Float() Work with Python?

Now that you know what is a float in Python, you can run the code by yourself to see how it works. Here are the different types of outputs you can expect:

What is Float in Python Output For Integers?

Professional Certificate in Coding: Full Time Coding Bootcamp at MIT xPRO

Integers, represented by int in Python, are real numbers with no decimal values. Most of the time, to run a program, programmers use real values or integers. However, when the number is too big, the input string or the integer value is converted into floating numbers to get an accurate value. This helps in running mathematical programs successfully, as float values give more precise results. Float() converts integers into decimal values.

What is a Float in Python: Output for Float Values

Floating values are decimal values or fractional numbers. Using float() on floating values gives the same output as the input.

What is a Float in Python: Output for Infinity and Not a Number (NaN)

Since infinity cannot be represented by a number in programming languages, the float() function is used to represent an infinite integer in the form of float(inf). It converts the string infinity value to a floating infinity value. This is how float() in Python works for infinity.

NaN or not, a number in Python is the text that represents an undefined numeric value. One of the best examples of NaN is 0/0. 0/0’s value is not undefined. Programmers prefer NaN as o/o’s representation in a programming language is not feasible. You can understand NaN as a placeholder for unrefined values. The program mostly shows NaN when there are missing values in the data. Whenever you want to use NaN, you must use float() in a string format to convert it into a floating value.

What is a Float in Python: Output for String Floats

what-is-agile

Strings in python are a series of characters within single or double quotes. These characters come back as inputs when you perform file operations. However, if you want to run an operation on the input, you will have to convert the string object into a floating value. This is where the float() function plays an integral role. However, you must remember that float() only converts numerical values into floating points. Characters do not shift from strings to floating points. Here are a few examples to help you use float to convert strings to floating points using the float() function.

print(“Float Value =”, f)

Output = value error.

The string is not converted to float ‘xyz’

Given Python’s easy-to-use and efficient framework, it is the preferred programming language for large-scale companies like Google, IBM, Intel, Goldman Sachs, Facebook, and Netflix. As a result, professionals with expert knowledge of Python, Java, and other programming languages are in high demand. Therefore, if you want to build a career in software development or programming, knowledge of Python is necessary. To help you kickstart or upskill your career in software development, dive into Emeritus’ online coding courses and make the most of this clear and present opportunity.

Data types

Каждое значение в Python имеет тип. Поскольку всё в Python — объекты, типы являются классами, а значения — экземплярами (объектами) этих классов.

Числа

Целые числа, числа с плавающей запятой и комплексные числа относятся к группе чисел. В Python они представлены классами int, float и complex.

Мы можем использовать функцию type(), чтобы узнать класс переменной или значения, и функцию isinstance() для проверки принадлежности объекта определённому классу:

Целые числа могут быть любой длины, они ограничиваются лишь доступной памятью в 4 байта.

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

Комплексные числа записываются в форме x+yj, где x — действительная часть числа, а y — мнимая.

Списки

Список представляет собой упорядоченную последовательность элементов. Он очень гибкий и является одним из самых используемых типов в Python. Элементы списка необязательно должны быть одного типа.

Объявить список довольно просто. Внутрь квадратных скобок помещаются элементы списка, разделённые запятой:

Мы можем использовать оператор [] для извлечения элемента (такая операция называется «доступ по индексу») или диапазона элементов (такая операция называется «извлечение среза») из списка. В Python индексация начинается с нуля:

Списки являются изменяемым типом, т.е. значения его элементов можно изменить:

Кортежи

Так же как и список, кортеж (tuple) является упорядоченной последовательностью элементов. Вся разница заключается в том, что кортежи неизменяемы.

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

Для создания кортежа нужно поместить внутрь круглых скобок элементы, разделённые запятой:

Строки

Строка представляет собой последовательность символов. Мы можем использовать одинарные или двойные кавычки для создания строки. Многострочные строки можно обозначить тройными кавычками, »’ или «»»:

Как и в случае со списками и кортежами, мы можем использовать оператор [] и со строками. Стоит отметить, что строки в Python относятся к категории неизменяемых последовательностей, то есть все функции и методы могут лишь создавать новую строку.

Множества

Множество является неупорядоченной уникализированной последовательностью. Объявляется множество с помощью элементов, разделённых запятой, внутри фигурных скобок:

Над множествами можно выполнять такие операции, как объединение и пересечение. Т.к. элементы в множестве должны быть уникальны, они автоматически удаляют дубликаты:

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

Словари

Словари — неупорядоченные наборы пар ключ-значение.

Они используются, когда нужно сопоставить каждому из ключей значение и иметь возможность быстро получать доступ к значению, зная ключ. В других языках словари обычно называются map, hash или object. Словари оптимизированы для извлечения данных. Чтобы извлечь значение, нужно знать ключ.

Словарь объявляется парами элементов в форме ключ:значение, заключенными в фигурные скобки:

Значение может быть любого типа, а вот ключ — только неизменяемого.

Мы используем ключ, чтобы получить соответствующее ему значение. Но не наоборот:

Преобразование типов данных

Мы можем преобразовывать значения из одного типа в другой с помощью таких функций, как int(), float(), str() и т.д. Для преобразования из/в строку должны использоваться совместимые значения:

Можно даже преобразовывать одну последовательность в другую:

Для преобразования в словарь каждый элемент последовательности должен быть парой:

Basic Data Types in Python

Now you know how to interact with the Python interpreter and execute Python code. It’s time to dig into the Python language. First up is a discussion of the basic data types that are built into Python.

Here’s what you’ll learn in this tutorial:

  • You’ll learn about several basic numeric, string, and Boolean types that are built into Python. By the end of this tutorial, you’ll be familiar with what objects of these types look like, and how to represent them.
  • You’ll also get an overview of Python’s built-in functions. These are pre-written chunks of code you can call to do useful things. You have already seen the built-in print() function, but there are many others.

Free PDF Download: Python 3 Cheat Sheet

Take the Quiz: Test your knowledge with our interactive “Basic Data Types in Python” quiz. Upon completion you will receive a score so you can track your learning progress over time:

Integers

In Python 3, there is effectively no limit to how long an integer value can be. Of course, it is constrained by the amount of memory your system has, as are all things, but beyond that an integer can be as long as you need it to be:

Python interprets a sequence of decimal digits without any prefix to be a decimal number:

The following strings can be prepended to an integer value to indicate a base other than 10:

Prefix Interpretation Base
0b (zero + lowercase letter ‘b’ )
0B (zero + uppercase letter ‘B’ )
Binary 2
0o (zero + lowercase letter ‘o’ )
0O (zero + uppercase letter ‘O’ )
Octal 8
0x (zero + lowercase letter ‘x’ )
0X (zero + uppercase letter ‘X’ )
Hexadecimal 16

For more information on integer values with non-decimal bases, see the following Wikipedia sites: Binary, Octal, and Hexadecimal.

The underlying type of a Python integer, irrespective of the base used to specify it, is called int :

Note: This is a good time to mention that if you want to display a value while in a REPL session, you don’t need to use the print() function. Just typing the value at the >>> prompt and hitting Enter will display it:

Many of the examples in this tutorial series will use this feature.

Note that this does not work inside a script file. A value appearing on a line by itself in a script file will not do anything.

Floating-Point Numbers

The float type in Python designates a floating-point number. float values are specified with a decimal point. Optionally, the character e or E followed by a positive or negative integer may be appended to specify scientific notation:

Deep Dive: Floating-Point Representation

The following is a bit more in-depth information on how Python represents floating-point numbers internally. You can readily use floating-point numbers in Python without understanding them to this level, so don’t worry if this seems overly complicated. The information is presented here in case you are curious.

Almost all platforms represent Python float values as 64-bit “double-precision” values, according to the IEEE 754 standard. In that case, the maximum value a floating-point number can have is approximately 1.8 ⨉ 10 308 . Python will indicate a number greater than that by the string inf :

The closest a nonzero number can be to zero is approximately 5.0 ⨉ 10 -324 . Anything closer to zero than that is effectively zero:

Floating point numbers are represented internally as binary (base-2) fractions. Most decimal fractions cannot be represented exactly as binary fractions, so in most cases the internal representation of a floating-point number is an approximation of the actual value. In practice, the difference between the actual value and the represented value is very small and should not usually cause significant problems.

Further Reading: For additional information on floating-point representation in Python and the potential pitfalls involved, see Floating Point Arithmetic: Issues and Limitations in the Python documentation.

Complex Numbers

Complex numbers are specified as <real part>+<imaginary part>j . For example:

Strings

Strings are sequences of character data. The string type in Python is called str .

String literals may be delimited using either single or double quotes. All the characters between the opening delimiter and matching closing delimiter are part of the string:

A string in Python can contain as many characters as you wish. The only limit is your machine’s memory resources. A string can also be empty:

What if you want to include a quote character as part of the string itself? Your first impulse might be to try something like this:

As you can see, that doesn’t work so well. The string in this example opens with a single quote, so Python assumes the next single quote, the one in parentheses which was intended to be part of the string, is the closing delimiter. The final single quote is then a stray and causes the syntax error shown.

If you want to include either type of quote character within the string, the simplest way is to delimit the string with the other type. If a string is to contain a single quote, delimit it with double quotes and vice versa:

Escape Sequences in Strings

Sometimes, you want Python to interpret a character or sequence of characters within a string differently. This may occur in one of two ways:

  • You may want to suppress the special interpretation that certain characters are usually given within a string.
  • You may want to apply special interpretation to characters in a string which would normally be taken literally.

You can accomplish this using a backslash ( \ ) character. A backslash character in a string indicates that one or more characters that follow it should be treated specially. (This is referred to as an escape sequence, because the backslash causes the subsequent character sequence to “escape” its usual meaning.)

Let’s see how this works.

Suppressing Special Character Meaning

You have already seen the problems you can come up against when you try to include quote characters in a string. If a string is delimited by single quotes, you can’t directly specify a single quote character as part of the string because, for that string, the single quote has special meaning—it terminates the string:

Specifying a backslash in front of the quote character in a string “escapes” it and causes Python to suppress its usual special meaning. It is then interpreted simply as a literal single quote character:

The same works in a string delimited by double quotes as well:

The following is a table of escape sequences which cause Python to suppress the usual special interpretation of a character in a string:

Escape
Sequence
Usual Interpretation of
Character(s) After Backslash
“Escaped” Interpretation
\’ Terminates string with single quote opening delimiter Literal single quote ( ‘ ) character
Terminates string with double quote opening delimiter Literal double quote ( » ) character
\<newline> Terminates input line Newline is ignored
\\ Introduces escape sequence Literal backslash ( \ ) character

Ordinarily, a newline character terminates line input. So pressing Enter in the middle of a string will cause Python to think it is incomplete:

To break up a string over more than one line, include a backslash before each newline, and the newlines will be ignored:

To include a literal backslash in a string, escape it with a backslash:

Applying Special Meaning to Characters

Next, suppose you need to create a string that contains a tab character in it. Some text editors may allow you to insert a tab character directly into your code. But many programmers consider that poor practice, for several reasons:

  • The computer can distinguish between a tab character and a sequence of space characters, but you can’t. To a human reading the code, tab and space characters are visually indistinguishable.
  • Some text editors are configured to automatically eliminate tab characters by expanding them to the appropriate number of spaces.
  • Some Python REPL environments will not insert tabs into code.

In Python (and almost all other common computer languages), a tab character can be specified by the escape sequence \t :

The escape sequence \t causes the t character to lose its usual meaning, that of a literal t . Instead, the combination is interpreted as a tab character.

Here is a list of escape sequences that cause Python to apply special meaning instead of interpreting literally:

Escape Sequence “Escaped” Interpretation
\a ASCII Bell ( BEL ) character
\b ASCII Backspace ( BS ) character
\f ASCII Formfeed ( FF ) character
\n ASCII Linefeed ( LF ) character
\N

Character from Unicode database with given <name>
\r ASCII Carriage Return ( CR ) character
\t ASCII Horizontal Tab ( TAB ) character
\uxxxx Unicode character with 16-bit hex value xxxx
\Uxxxxxxxx Unicode character with 32-bit hex value xxxxxxxx
\v ASCII Vertical Tab ( VT ) character
\ooo Character with octal value ooo
\xhh Character with hex value hh

This type of escape sequence is typically used to insert characters that are not readily generated from the keyboard or are not easily readable or printable.

Raw Strings

A raw string literal is preceded by r or R , which specifies that escape sequences in the associated string are not translated. The backslash character is left in the string:

Triple-Quoted Strings

There is yet another way of delimiting strings in Python. Triple-quoted strings are delimited by matching groups of three single quotes or three double quotes. Escape sequences still work in triple-quoted strings, but single quotes, double quotes, and newlines can be included without escaping them. This provides a convenient way to create a string with both single and double quotes in it:

Because newlines can be included without escaping them, this also allows for multiline strings:

You will see in the upcoming tutorial on Python Program Structure how triple-quoted strings can be used to add an explanatory comment to Python code.

Boolean Type, Boolean Context, and “Truthiness”

Python 3 provides a Boolean data type. Objects of Boolean type may have one of two values, True or False :

As you will see in upcoming tutorials, expressions in Python are often evaluated in Boolean context, meaning they are interpreted to represent truth or falsehood. A value that is true in Boolean context is sometimes said to be “truthy,” and one that is false in Boolean context is said to be “falsy.” (You may also see “falsy” spelled “falsey.”)

The “truthiness” of an object of Boolean type is self-evident: Boolean objects that are equal to True are truthy (true), and those equal to False are falsy (false). But non-Boolean objects can be evaluated in Boolean context as well and determined to be true or false.

You will learn more about evaluation of objects in Boolean context when you encounter logical operators in the upcoming tutorial on operators and expressions in Python.

Built-In Functions

The Python interpreter supports many functions that are built-in: sixty-eight, as of Python 3.6. You will cover many of these in the following discussions, as they come up in context.

For now, a brief overview follows, just to give a feel for what is available. See the Python documentation on built-in functions for more detail. Many of the following descriptions refer to topics and concepts that will be discussed in future tutorials.

Function Description
abs() Returns absolute value of a number
divmod() Returns quotient and remainder of integer division
max() Returns the largest of the given arguments or items in an iterable
min() Returns the smallest of the given arguments or items in an iterable
pow() Raises a number to a power
round() Rounds a floating-point value
sum() Sums the items of an iterable

Type Conversion

Function Description
ascii() Returns a string containing a printable representation of an object
bin() Converts an integer to a binary string
bool() Converts an argument to a Boolean value
chr() Returns string representation of character given by integer argument
complex() Returns a complex number constructed from arguments
float() Returns a floating-point object constructed from a number or string
hex() Converts an integer to a hexadecimal string
int() Returns an integer object constructed from a number or string
oct() Converts an integer to an octal string
ord() Returns integer representation of a character
repr() Returns a string containing a printable representation of an object
str() Returns a string version of an object
type() Returns the type of an object or creates a new type object

Iterables and Iterators

Function Description
all() Returns True if all elements of an iterable are true
any() Returns True if any elements of an iterable are true
enumerate() Returns a list of tuples containing indices and values from an iterable
filter() Filters elements from an iterable
iter() Returns an iterator object
len() Returns the length of an object
map() Applies a function to every item of an iterable
next() Retrieves the next item from an iterator
range() Generates a range of integer values
reversed() Returns a reverse iterator
slice() Returns a slice object
sorted() Returns a sorted list from an iterable
zip() Creates an iterator that aggregates elements from iterables

Composite Data Type

Function Description
bytearray() Creates and returns an object of the bytearray class
bytes() Creates and returns a bytes object (similar to bytearray , but immutable)
dict() Creates a dict object
frozenset() Creates a frozenset object
list() Creates a list object
object() Creates a new featureless object
set() Creates a set object
tuple() Creates a tuple object

Classes, Attributes, and Inheritance

Function Description
classmethod() Returns a class method for a function
delattr() Deletes an attribute from an object
getattr() Returns the value of a named attribute of an object
hasattr() Returns True if an object has a given attribute
isinstance() Determines whether an object is an instance of a given class
issubclass() Determines whether a class is a subclass of a given class
property() Returns a property value of a class
setattr() Sets the value of a named attribute of an object
super() Returns a proxy object that delegates method calls to a parent or sibling class

Input/Output

Function Description
format() Converts a value to a formatted representation
input() Reads input from the console
open() Opens a file and returns a file object
print() Prints to a text stream or the console

Variables, References, and Scope

Function Description
dir() Returns a list of names in current local scope or a list of object attributes
globals() Returns a dictionary representing the current global symbol table
id() Returns the identity of an object
locals() Updates and returns a dictionary representing current local symbol table
vars() Returns __dict__ attribute for a module, class, or object

Miscellaneous

Function Description
callable() Returns True if object appears callable
compile() Compiles source into a code or AST object
eval() Evaluates a Python expression
exec() Implements dynamic execution of Python code
hash() Returns the hash value of an object
help() Invokes the built-in help system
memoryview() Returns a memory view object
staticmethod() Returns a static method for a function
__import__() Invoked by the import statement

Conclusion

In this tutorial, you learned about the built-in data types and functions Python provides.

The examples given so far have all manipulated and displayed only constant values. In most programs, you are usually going to want to create objects that change in value as the program executes.

Head to the next tutorial to learn about Python variables.

Take the Quiz: Test your knowledge with our interactive “Basic Data Types in Python” quiz. Upon completion you will receive a score so you can track your learning progress over time:

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

Ваш адрес email не будет опубликован. Обязательные поля помечены *