0% found this document useful (0 votes)
18 views8 pages

Understanding Python Literals and Types

Personal Python Learning Note

Uploaded by

brian07151992
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
18 views8 pages

Understanding Python Literals and Types

Personal Python Learning Note

Uploaded by

brian07151992
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd

Python Note 2

30/12/2023

Literals - the data in itself

A literal is data whose values are determined by the literal itself.


You use literals to encode data and to put them into your code. We're
now going to show you some conventions you have to obey when using
Python.

print("2")
print(2)

you encounter two different types of literals:


 a string, which you already know,
 and an integer number, something completely new.

The print() function presents them in exactly the same way - this example is
obvious, as their human-readable representation is also the same. Internally,
in the computer's memory, these two values are stored in completely
different ways - the string exists as just a string - a series of letters.

The number is converted into machine representation (a set of bits).


The print() function is able to show them both in a form readable to
humans.

Integers

binary system
it's the system computers use for storing numbers, and that they can perform
any operation upon them.

The numbers handled by modern computers are of two types:


 integers, that is, those which are devoid of the fractional part;
 and floating-point numbers (or simply floats), that contain (or are
able to contain) the fractional part.
Both of these kinds of numbers differ significantly in how they're stored in a
computer memory and in the range of acceptable values.

The characteristic of the numeric value which determines its kind, range, and
application, is called the type.

If you encode a literal and place it inside Python code, the form of the literal
determines the representation (type) Python will use to store it in the
memory.

What Python does allow, though, is the use of underscores in numeric


literals.*

Therefore, you can write this number either like this: 11111111 , or like
that: 11_111_111 .

And how do we code negative numbers in Python? As usual - by adding


a minus. You can write: -11111111, or -11_111_111.

Integers: octal and hexadecimal numbers(八进制

和十六进制)

The first allows us to use numbers in an octal representation.

If an integer number is preceded by an 0O or 0o prefix (zero-o), it will be


treated as an octal value. This means that the number must contain digits
taken from the [0..7] range only.

0o123 is an octal number with a (decimal) value equal to 83 .

1 * 8^2 + 2 * 8^1 + 3 * 8^0 = 83


The print() function does the conversion automatically. Try this:

print(0o123)

The second convention allows us to use hexadecimal numbers. Such


numbers should be preceded by the prefix 0x or 0X (zero-x).

0x123 is a hexadecimal number with a (decimal) value equal to 291 . The


print() function can manage these values too. Try this:

print(0x123)

Floats

Whenever we use a term like two and a half or minus zero point four, we think
of numbers which the computer considers floating-point numbers:

2.5
-0.4

Note: two and a half looks normal when you write it in a program, although if
your native language prefers to use a comma instead of a point in the
number, you should ensure that your number doesn't contain any
commas at all.
Ints vs. floats

The decimal point is essentially important in recognizing floating-point


numbers in Python.

Look at these two numbers:

4
4.0

You may think that they are exactly the same, but Python sees them in a
completely different way.

4 is an integer number, whereas 4.0 is a floating-point number.

The point is what makes a float.

On the other hand, it's not only points that make a float. You can also use the
letter e .

When you want to use any numbers that are very large or very small, you can
use scientific notation.

Take, for example, the speed of light, expressed in meters per second.
Written directly it would look like this: 300000000 .

To avoid writing out so many zeros, physics textbooks use an abbreviated


form, which you have probably already seen: 3 x 108 .

It reads: three times ten to the power of eight.

In Python, the same effect is achieved in a slightly different way - take a look:

3E8

The letter E (you can also use the lower-case letter e - it comes from the
word exponent) is a concise record of the phrase times ten to the power of.
Note:

 the exponent (the value after the E) has to be an integer;


 the base (the value in front of the E) may be an integer.

Coding floats

Let's see how this convention is used to record numbers that are very small
(in the sense of their absolute value, which is close to zero).

A physical constant called Planck's constant (and denoted as h), according to


the textbooks, has the value of: 6.62607 x 10-34.

If you would like to use it in a program, you should write it this way:

6.62607E-34

Note: the fact that you've chosen one of the possible forms of coding float
values doesn't mean that Python will present it the same way.

Python may sometimes choose different notation than you.

For example, let's say you've decided to use the following float literal:

0.0000000000000000000001

When you run this literal through Python:

print(0.0000000000000000000001)

this is the result:

1e-22

Python always chooses the more economical form of the number's


presentation, and you should take this into consideration when creating
literals.
Strings

Strings are used when you need to process text (like names of all kinds,
addresses, novels, etc.), not numbers.

You already know a bit about them, e.g., that strings need quotes the way
floats need points.

This is a very typical string: "I am a string."

However, there is a catch. The catch is how to encode a quote inside a string
which is already delimited by quotes.

Let's assume that we want to print a very simple message saying:

I like "Monty Python"

How do we do it without generating an error? There are two possible


solutions.

The first is based on the concept we already know of the escape character,
which you should remember is played by the backslash. The backslash can
escape quotes too. A quote preceded by a backslash changes its meaning -
it's not a delimiter, but just a quote. This will work as intended:

print("I like \"Monty Python\"")

Note: there are two escaped quotes inside the string - can you see them both?

The second solution may be a bit surprising. Python can use an apostrophe
instead of a quote. Either of these characters may delimit strings, but you
must be consistent.

If you open a string with a quote, you have to close it with a quote.

If you start a string with an apostrophe, you have to end it with an


apostrophe.
This example will work too:

print('I like "Monty Python"')

Note: you don't need to do any escaping here.

Boolean values

To conclude with Python's literals, there are two additional ones.

They're not as obvious as any of the previous ones, as they're used to


represent a very abstract value - truthfulness.

Each time you ask Python if one number is greater than another, the question
results in the creation of some specific data - a Boolean value.

The name comes from George Boole (1815-1864), the author of the
fundamental work, The Laws of Thought, which contains the definition
of Boolean algebra - a part of algebra which makes use of only two distinct
values: True and False, denoted as 1 and 0.

Python, then, is a binary reptile.

These two Boolean values have strict denotations in Python:

True
False

You cannot change anything - you have to take these symbols as they are,
including case-sensitivity.

Key takeaways

1. Literals are notations for representing some fixed values in code. Python
has various types of literals - for example, a literal can be a number (numeric
literals, e.g., 123 ), or a string (string literals, e.g., "I am a literal.").
2. The binary system is a system of numbers that employs 2 as the base.
Therefore, a binary number is made up of 0s and 1s only, e.g., 1010 is 10 in
decimal.

Octal and hexadecimal numeration systems, similarly, employ 8 and 16 as


their bases respectively. The hexadecimal system uses the decimal numbers
and six extra letters.

3. Integers (or simply ints) are one of the numerical types supported by
Python. They are numbers written without a fractional component, e.g., 256 ,
or -1 (negative integers).

4. Floating-point numbers (or simply floats) are another one of the


numerical types supported by Python. They are numbers that contain (or are
able to contain) a fractional component, e.g., 1.27 .

5. To encode an apostrophe or a quote inside a string you can either use the
escape character, e.g., 'I\'m happy.' , or open and close the string using an
opposite set of symbols to the ones you wish to encode, e.g., "I'm happy." to
encode an apostrophe, and 'He said "Python", not "typhoon"' to encode a
(double) quote.

6. Boolean values are the two constant objects True and False used to
represent truth values (in numeric contexts 1 is True , while 0 is False .

EXTRA

There is one more, special literal that is used in Python: the None literal. This
literal is a so-called NoneType object, and it is used to represent the absence
of a value. We'll tell you more about it soon.

Common questions

Powered by AI

Python represents numeric literals in different forms such as integers and floating-point numbers, impacting their storage in memory by using distinct binary systems. Integers are stored as binary numbers without a fractional part, while floats, which can contain fractions, are stored in a more complex manner using scientific notation for efficiency, e.g., 4 is an integer, while 4.0 is a float. This distinction is important because it affects operations and performance due to how these numbers are processed and stored in memory .

Integers in Python represent whole numbers without fractional parts, using straightforward binary representation, while floating-point types accommodate fractions and scientific notation for precision over a wider range of values. Operations on these types differ; integer operations preserve exact values whenever possible, but floats are subject to precision errors due to their complexity in accommodating decimals. This distinction affects performance and application areas, requiring careful type management in calculations involving both .

Python may reformat floating-point literals into more economical forms to enhance precision and performance, converting verbose notation to a compact scientific format. For example, coding a small float like 0.0000000001 might be automatically changed by Python to 1e-10. This automatic optimization ensures higher precision by utilizing significant digits and maintaining efficiency in memory and processing resources .

In Python, the letter 'e' denotes exponential notation, making it crucial for representing very large or small floating-point numbers compactly. The 'e' indicates 'times ten to the power of', allowing for a concise representation, e.g., scientific notation transforms 300000000 into 3E8, representing 3 * 10^8. This notation is essential for reducing error in handling significant digits and optimizing performance in computing large magnitudes efficiently .

Challenges in representing string literals in Python include encoding quotes within strings and ensuring proper delimiter usage. Python addresses these with escape sequences like backslashes (\) for quotes, e.g., "He said \"Hello\"", and using different quote types for delimiters, e.g., 'She said "Hi"'. These solutions prevent syntax errors and ensure that literal text is correctly interpreted by the Python interpreter, facilitating text processing and output .

Python differentiates floating-point numbers from integers primarily by the presence of a decimal point or 'e' notation in floats. For example, 4 is an integer while 4.0 is a float. This distinction affects arithmetic operations and data types handling because integers are used for discrete values without fractions, while floats handle continuous data and fractional operations, impacting precision, memory usage, and processing requirements .

Boolean literals in Python represent truth values, used for logical operations and control flow in programming. They are represented by the keywords True and False, corresponding to numerical values 1 and 0, respectively. These values are case-sensitive and central to condition evaluations, allowing program logic decisions based on truthiness, such as in conditional statements or loops .

In Python, underscores in numeric literals are used to improve the readability of large numbers by separating groups of digits, similar to commas in traditional numeric notation. For example, the number 11111111 can be expressed as 11_111_111 for clarity. Similarly, negative numbers can be formatted in this way, e.g., -11_111_111, enhancing code readability without affecting the numeric value .

Including quotes within strings in Python can be achieved using escape characters or alternating quote types. The backslash (\) is used as an escape character to include quotes, e.g., "I like \"Monty Python\"". Alternatively, using single quotes to enclose a string allows double quotes inside without escaping, e.g., 'I like "Monty Python"'. These methods prevent syntax errors by distinguishing quote delimiters from literal quotes in the string .

Python handles octal numbers by using a prefix of 0O or 0o, which allows digits from the range [0..7]. For instance, 0o123 represents the decimal number 83, calculated as 1 * 8^2 + 2 * 8^1 + 3 * 8^0. Hexadecimal numbers are prefixed with 0x or 0X, allowing digits 0-9 and letters A-F, where 0x123 is equivalent to the decimal number 291. These prefixes signal Python to interpret these literals in their respective base systems .

You might also like