Clear, practical technology insights BSOD Code Lookup · Windows Error Code Lookup · Wi-Fi Troubleshooting · PC Troubleshooting Checklist

Basic Data Types in Python: What to Know

Explore Basic Data Types in Python, with the main facts, background, specifications, and practical implications explained clearly for readers.

Table of Contents

How are data types in Python: string, number, list, tuple, set and dictionary used? Let's find out with TipsMake.com!

Key Takeaways About Python String

  • How are data types in Python: string, number, list, tuple, set and dictionary used?
  • The details are explained below. with TipsMake.com!
  • Data types are ways of classifying data items.

Data types are ways of classifying data items. It represents a type of value that indicates what operations can be performed on a particular data. Since everything is an object in Python programming, data types are actually classes, and variables are objects of these classes.

Python has many different data types. If you want to program good applications, you should definitely know them.

When taking tests, you easily come across questions like in python, what is the output of the following function? float(' -12345 ') note: the number of spaces before the number is 5… So how to answer these questions accurately? The answer is very simple. That is, you must master Python data types.

Python is a special programming language with many data types that help you create a useful program. Some of the most common data types are:

  • Integer: is a type of scalar numeric data, such as 1, 2, 3, 4, 5.
  • Real number (float): is a type of numeric data with a decimal point, such as 1.5, 2.7, 3.14.
  • String: is a data type containing a string of characters, such as "hello", "goodbye".
  • Boolean: is a data type with two values: True or False.
  • List: is a data type containing a set of values, for example [1, 2, 3, 4, 5].
  • Dictionary: is a data type that contains key-value pairs, for example {"name": "John", "age": 30}.

For example, you can use a function typeto check the data type of a variable as follows:

x = 1 print(type(x)) # in ra "
 
 " y = 1.5 print(type(y)) # in ra "
 
 " z = "hello" print(type(z)) # in ra "
 
 "
 
 
 

Because the article will list the most important contents of all data types in Python, it will be quite long. Each data type comes with specific examples for you to easily visualize.

Be sure to save this Python Documentation page to update the latest articles. Don't forget to do the Python exercises to reinforce your knowledge.

1. Variables in Python

A variable is a location in memory used to store data (value). Variables are given unique names to distinguish between different memory locations. The rules for writing a variable name are the same as the rules for writing identifiers in Python.

In Python, you don't need to declare a variable before using it, just assign the variable a value and it will exist. There is also no need to declare the variable type, the variable type will be automatically determined based on the value you assigned to the variable.

Assign value to variable:

To assign a value to a variable we use the = operator. Any type of value can be assigned to a valid variable.

For example:

hoa = "H?ng" la = 3 canh = 5.5

Above are 3 assignment statements, " Hong " is a string of characters, assigned to a capital variable , 3 is an integer and assigned to la , 5.5 is a decimal number and assigned to canh .

Assign multiple values:

In Python you can assign multiple values ??in one command like this:

hoa, la, canh = "H?ng", 3, 5.5

If you want to assign the same value to multiple variables, you can write the command as follows:

hoa, la, canh = 3

The above command will assign the value 3 to all 3 variables: hoa, la and canh.

2. Numeric Data Type in Python

Numeric Data Types in Python

Python supports integers, decimals, and complex numbers, which are respectively defined as int, float, and complex classes in Python. Integers and decimal numbers are distinguished by the presence or absence of a decimal point.

For example: 5 is an integer, 5.0 is a decimal number. Python also supports complex numbers and uses the suffix jor Jto indicate the imaginary part. For example: 3+5j. In addition to intand float, Python supports two more types of numbers: Decimaland Fraction.

We will use functions type()to check to see which numeric class a variable or value belongs to, and functions isinstance()to check if they belong to a specific class.

a = 9 # Output: 
 
 print(type(a)) # Output: 
 
 print(type(5.0)) # Output: (10+2j) b = 8 + 2j print(b + 2) # Ki?m tra xem b có ph?i là s? ph?c không # Output: True print(isinstance(b, complex)) 
 
 

Integers in Python are not limited in length, decimals are limited to 16 numbers after the decimal point.

The numbers we work with every day are usually base 10, but computer programmers (usually embedded programmers) need to work with binary, hexadecimal and octal number systems. To represent these coefficients in Python, we place an appropriate prefix before the number.

Coefficient prefix for Python numbers:

Number system Prefix
Binary system '0b' or '0B'
Octal system '0o' or '0O'
Hexadecimal system '0x' or '0X'

(You can put the prefix without the ' ').

This is an example of using coefficient prefixes in Python, and when we use the function print()to print their value to the screen, we will get the corresponding number in the coefficient of 10.

# Output: 187 print(0b10111011) # Output: 257 (250 + 7) print(0xFA + 0b111) # Output: 15 print(0o17)

Convert Between Numeric Types in Python

We can convert one number type to another number type. This is also known as coercion. Operations such as addition and subtraction will implicitly convert integers to decimals (automatically) if there is an operator in the operation that is a decimal number.

For example : If you perform addition between the integer 2 and the decimal number 3.0, then 2 will be forcibly converted to decimal 2.0 and the returned result will be decimal 5.0.

>>> 2 + 3.0 5.0

We can use built-in Python functions like int(), float()and complex()to convert between numeric types explicitly. These functions can even convert from strings.

>>> int(3.6) 3 >>> int(-1.2) -1 >>> float(7) 7.0 >>> complex('2+8j') (2+8j)

When converting from decimal to integer, the number will be omitted, only the integer part will be taken.

Decimal Module in Python

The class float built into Python may surprise us a bit. Normally, if we calculate the sum of 1.1 and 2.2, we think the result will be 3.3, but that seems not to be the case. If you check the correctness of this math operation in Python, the result will be False.

>>> (1.1 + 2.2) == 3.3 False

What happened?

This is because, decimal numbers are implemented in computer hardware as binary fractions, since computers only understand binary numbers (0 and 1) so most of the decimal fractions we know , cannot be stored correctly in the computer.

For example, we cannot represent the fraction 1/3 as a decimal, because it is an infinite repeating decimal, with the numbers after the decimal point infinitely long, so we can only evaluate it. .

When converting the decimal part 0.1, it results in an infinitely long binary part of 0.000110011001100110011. and the computer only stores a finite part of the number after the . its only. Therefore, the number stored is only approximately 0.1 and never equal to 0.1. That's why the addition we talked about above doesn't give the results we expected. That is a limitation of computer hardware, not Python's fault.

Now try typing the above addition into Python to see what the return result is:

>>> 1.1+2.2 3.3000000000000003

To overcome this problem, we can use the Decimal module in Python. While float numbers only take 16 numbers after the decimal point, the Decimal module allows customizing the length of the number.

import decimal # Output: 0.1 print(0.1) # Output: 0.1000000000000000055511151231257827021181583404541015625 print(decimal.Decimal(0.1))

This module is used when we want to perform mathematical operations in decimal numbers to get results like we learned in school.

This is also quite important, for example 25.50kg will be more accurate than 25.5kg, because 2 decimal places are still more accurate than 1 digit.

from decimal import Decimal # Output: 3.3 print(Decimal('1.1') + Decimal('2.2')) # Output: 10.000 print(Decimal('4.0') * Decimal('2.50'))

If you want more concise code, you can import the Decimal module and change the module name to D.

from decimal import Decimal as D # Output: 3.3 print(D('1.1') + D('2.2')) # Output: 10.000 print(D('4.0') * D('2.50'))

In this code we import the Decimal module and change its name to D, the result is unchanged from the above code.

You may wonder in the multiplication section, why not use Decimal numbers to multiply but have to add 0 after 4 and 2.5. The answer is efficiency, float operations are performed faster than Decimal operations.

When Should Decimal Be Used Instead of Float?

We often use Decimal in the following cases:

  • When creating financial applications, precise decimal representation is essential.
  • When you want to control the precision of numbers.
  • When you want to perform math operations like you learned in school.

Fractions in Python

Python provides mathematical operations involving fractions through the fractions module. A fraction has a numerator and a denominator, both of which are integers. We can create Fraction objects in many different ways:

import fractions # T?o phân s? t? s? th?p phân print(fractions.Fraction(4.5)) # Output: 9/2 # T?o phân s? t? s? nguyên # Code by TipsMake.com print(fractions.Fraction(9)) # Output: 9 # T?o phân s? b?ng cách khai báo t?, m?u s? print(fractions.Fraction(2,5)) # Output: 2/5

When creating fractions from floats, we may get unusual results, which is due to computer hardware limitations as discussed in the decimal module section.

In particular, you can initialize a fraction from string. This is the preferred initialization when using decimal numbers.

import fractions # Kh?i t?o phân s? t? float print(fractions.Fraction(0.1)) # Output: 3602879701896397/36028797018963968 # Kh?i t?o phân s? t? string # Code by TipsMake.com print(fractions.Fraction('0.1')) # Output: 1/10

The fraction data type fully supports basic mathematical operations such as addition, subtraction, multiplication, division, and logic:

# Output: 1 print(F(2,5) + F(3,5)) # Output: 3/5 print(F(2,5) + F(1,5)) # Output: 7/1 print(1 / F(3,7)) # Output: False print(F(-2,9) > 0) # Output: True print(F(-2,9) < 0)

Mathematics in Python

Python provides math and random modules to solve other mathematical problems such as trigonometry, logarithms, probability and statistics, etc. Because the math module has quite a lot of functions and properties, I calculated Will make a separate post to list them. Below is an example of math in Python.

from fractions import Fraction as F import math # Output: 3.141592653589793 print(math.pi) # Output: -1.0 print(math.cos(math.pi)) # Output: 22026.465794806718 print(math.exp(10)) # Output: 2.0 print(math.log2(4)) # Output: 1.1752011936438014 print(math.sinh(1)) # Output: 40320 print(math.factorial(8))

Use the Interpreter as a Calculator

The interpreter works like a simple calculator: You can enter a calculation and it writes out the value. The expression syntax is quite simple: operators like +, -, * and / work the same as in most other programming languages ??(Pascal, C), parentheses () can be used for grouping . For example:

>>> 2 + 2 4 >>> 50 - 5*6 20 >>> (50 - 5*6) / 4 5.0 >>> 8 / 5 # phép chia luôn tr? v? m?t s? d?ng th?p phân v?i d?u ch?m 1.6

Integers (like 2, 4, 20) have type int, decimal numbers (like 5.0, 1.6) have type float.

Division ( /) always returns a float. To perform integer division (removing numbers after the decimal point) you can use the operator //; To calculate the remainder, use %the example below:

>>> 17 / 3 # phép chia th??ng tr? v? s? th?p phân 5.666666666666667 >>> >>> 17 // 3 # phép chia l?y s? nguyên, lo?i b? ph?n sau d?u th?p phân 5 >>> 17 % 3 # toán t? % tr? v? s? d? c?a phép chia 2 >>> 5 * 3 + 2 # th??ng * s? chia + s? d? 17

With Python, you can use operators **to calculate exponents:

>>> 5 ** 2 # 5 bình ph??ng 25 >>> 2 ** 7 # 2 m? 7 128

The equal sign =is used to assign a value to a variable. Then no results are displayed before the next command prompt:

>>> width = 20 >>> height = 5 * 9 >>> width * height 900

If a variable is not defined (assigned a value), try to use it and you will receive the following error:

>>> n # b?n ?ang c? truy c?p vào bi?n n ch?a ???c gán giá tr? Traceback (most recent call last): File "", line 1, in NameError: name 'n' is not defined

Python fully supports floating point, calculations with both integers and decimals, the result will be returned as a decimal number (sic: operators with mixed type operands convert integer operands to decimal):

>>> 4 * 3.75 - 1 14.0

In interactive mode, the last printed expression will be assigned to the variable _, making it easier to perform subsequent calculations. For example:

>>> tax = 12.5 / 100 >>> price = 100.50 >>> price * tax 12.5625 >>> price + _ 113.0625 >>> round(_, 2) 113.06

You should consider this variable as read-only, do not assign a value to it - because if you create a variable with the same name it will take over this default variable and no longer be able to do the cool things above.

3. String

String in Python is a sequence of characters. Computers don't deal with characters, they only work with binary numbers. Although you can see characters on the screen, they are stored and processed internally as combinations of 0s and 1s. Converting characters to numbers is called encoding, and the process is the reverse. is called decoding. ASCII and Unicode are two of the popular encodings commonly used.

In Python, a string is a sequence of Unicode characters. Unicode covers every character in all languages ??and provides uniformity in encoding.

How to Create Strings in Python

Besides numbers, Python can also manipulate strings, represented in many ways. '.'They can be enclosed in single ( ) or double ( ) quotes "."with the same result. is used to "escape" these two quotes.

>>> 'spam eggs' # d?u nháy ??n 'spam eggs' >>> 'doesn't' # s? d?ng ' ?? vi?t d?u nháy ??n. "doesn't" >>> "doesn't" # .ho?c s? d?ng d?u nháy kép "doesn't" >>> '"Yes," he said.' '"Yes," he said.' >>> ""Yes," he said." '"Yes," he said.' >>> '"Isn't," she said.' '"Isn't," she said.'

In the interactive interpreter, the resulting string includes the quotation marks and special characters that are "hidden" using . Although the output may look slightly different from the input (enclosing quotes may vary), the two strings are equivalent. Strings are written in double quotes when the string contains single quotes and no double quotes), otherwise it is written in single quotes. The print() function creates a more readable output string, by ignoring the accompanying quotes and printing special characters that "escape" the quotes:

>>> '"Isn't," she said.' '"Isn't," she said.' >>> print('"Isn't," she said.') "Isn't," she said. >>> s = 'First line.nSecond line.' # n ngh?a là dòng m?i >>> s # không có print(), n s? ???c vi?t trong k?t qu? ??u ra 'First line.nSecond line.' >>> print(s) # có print(), n s? t?o ra dòng m?i First line. Second line.

If you do not want the characters added by to be interpreted as special characters by the interpreter, use the raw string by prefixing the rfirst quote:

>>> print('C:somename') # ? ?ây n là dòng m?i! C:some ame >>> print(r'C:somename') # thêm r tr??c d?u nháy C:somename

String characters can be written on multiple lines using three quotes: """."""or '''.'''. Line endings are automatically included in the string, but this can be prevented by appending to the end of the line. For example:

print(""" Usage: thingy [OPTIONS] -h Display this usage message -H hostname Hostname to connect to """)

Here is the result (the original newline is not counted):

Basic data types in Python Picture 1 - Python String

Here is a list of all escape sequences supported by Python:

Escape Sequence Describe
newline Backslashes and newlines are ignored
  Backslash
' Apostrophe
" Quotation marks
a

ASCII Bell

b ASCII Backspace
f ASCII Formfeed
n ASCII Linefeed
r ASCII Carriage Return
t ASCII Horizontal Tab
v ASCII Vertical Tab
ooo The character with octal value is ooo
xHH The character with hexadecimal value is HH

For example: Let's run each command individually right in the compiler to see the results.

>>> print("C:Python32TipsMake.com") C:Python32TipsMake.com >>> print("In dòng nàynthành 2 dòng") In dòng này thành 2 dòng >>> print("In giá tr? x48x45x58") In giá tr? HEX >>> 

How to Access Elements of a String

Strings can be indexed with the first character numbered 0. There is no separate character type, each character is simply a number:

>>> word = 'Python' >>> word[0] # ký t? ? v? trí s? 0 'P' >>> word[5] # ký t? ? v? trí s? 5 'n' 

The index can also be negative, starting from the right:

>>> word[-1] # last character 'n' >>> word[-2] # second-last character 'o' >>> word[-6] 'P'

Note that because -0 is the same as 0, negative indices start at -1.

In addition to numbering, slicing is also supported. While index is used to get individual characters, slicing will allow you to get substrings:

>>> word[0:2] # các ký t? t? v? trí 0 (bao g?m) ??n 2 (lo?i tr?) 'Py' >>> word[2:5] # các ký t? t? v? trí 2 (bao g?m) ??n 5 (lo?i tr?) 'tho'

Pay attention to how characters are retained and excluded. It always ensures that s[:i] + s[i:]by s:

>>> word[:2] + word[2:] 'Python' >>> word[:4] + word[4:] 'Python'

The indices in string slicing have a pretty useful default setting, there are 2 indices that are ignored by default, which are 0 and the size of the string to be cut.

>>> word[:2] # các ký t? t? ??u ??n v? trí th? 2 (lo?i b?) 'Py' >>> word[4:] # các ký t? t? v? trí th? 4(l?y) ??n h?t 'on' >>> word[-2:] # các ký t? th? hai tính t? cu?i lên (l?y) ??n h?t 'on'

Another way to remember how string slicing works is to visualize the subscripts as separators between characters, with the leftmost character numbered 0. Then, the last character on the right, in A string of n characters will have index n, for example:

+---+---+---+---+---+---+ | P | y | t | h | o | n | +---+---+---+---+---+---+ 0 1 2 3 4 5 6 -6 -5 -4 -3 -2 -1

The first row of numbers gives the position of the index from 0 to 6 in the string. The second row is the corresponding negative indices. Cutting from i to j will include all characters between i and j, respectively.

For non-negative indices, the length of a slice is the difference of the indices, if both are within the bounds. For example, the length of word[1:3] is 2.

Attempting to use an index that is too large will return an error:

>>> word[42] # t? ch? có 6 ký t? Traceback (most recent call last): File "", line 1, in IndexError: string index out of range

However, indexes outside the slice range are still handled neatly when used for slicing:

>>> word[4:42] # c?t ký t? t? v? trí th? 4 ??n 42 'on' >>> word[42:] # c?t ký t? sau v? trí 42 ''

Change or Delete a String

Python strings cannot change - they are fixed. Therefore, if you intentionally assign a certain character to an indexed location, you will receive an error message:

>>> word[0] = 'J' . TypeError: 'str' object does not support item assignment >>> word[2:] = 'py' . TypeError: 'str' object does not support item assignment

If another string is needed, it's best to create a new one:

>>> 'J' + word[1:] 'Jython' >>> word[:2] + 'py' 'Pypy'

You cannot delete or remove characters from a string, but like a tuple, you can delete an entire string, using the del keyword:

qtm_string = 'TipsMake.com' del qtm_string # Output: NameError: name 'qtm_string' is not defined qtm_string

String Concatenation

Strings can be concatenated using the operator +and replaced with *:

>>> # thêm 3 'un' vào sau 'ium' >>> 3 * 'un' + 'ium' 'unununium'

Two or more string characters (i.e. characters within quotation marks) next to each other are automatically concatenated.

>>> 'Py' 'thon' 'Python'

The above feature only works with literal strings, does not apply to variables or expressions:

>>> prefix = 'Py' >>> prefix 'thon' # không th? n?i m?t bi?n v?i m?t chu?i . SyntaxError: invalid syntax >>> ('un' * 3) 'ium' . SyntaxError: invalid syntax

If you want to concatenate variables together or variables with strings, use +:

>>> prefix + 'thon' 'Python'

This feature is especially useful when you want to break long strings into shorter strings:

>>> text = ('Put several strings within parentheses ' . 'to have them joined together.') >>> text 'Put several strings within parentheses to have them joined together.'

If you want to concatenate strings in different lines, use parentheses:

>>> # s? d?ng () >>> s = ('Xin ' . 'chào!') >>> s 'Xin chào!'

Iterate and Check Elements of the String

Like lists and tuples, you also use a for loop when you need to iterate over a string, like in the example below to count the number of "i" characters in the string:

count = 0 for letter in 'TipsMake.com': if(letter == 'i'): count += 1 # Output: Có 1 ch? i ???c tìm th?y print('Có', count,'ch? i ???c tìm th?y')

To check whether a substring is present in a string, use the in keyword, like this:

>>> 'TipsMake' in 'TipsMake.com' True >>> 'python' in 'TipsMake.com' False >>> 

Built-in Python Function for Working with Strings

There are two most commonly used functions when working with strings in Python: enumerate() and len().

Function len()built into Python, which returns the length of the string:

>>> s = 'supercalifragilisticexpialidocious' >>> len(s) 34

The enumerate() function returns an enumeration object, containing the value pair and index of the element in the string, quite useful during iteration.

qtm_str = 'Python' # enumerate() qtm_enum = list(enumerate(qtm_str)) # Output: list(enumerate(qtm_str) = [(0, 'P'), (1, 'y'), (2, 't'), (3, 'h'), (4, 'o'), (5, 'n')] print('list(enumerate(qtm_str) = ', qtm_enum)

Format() Method to Format the String

The format() method is very flexible and powerful when used to format strings. String format containing {} as a placeholder or replacement field to receive an alternative value. You can also use positional arguments or keywords to specify the order.

# default(implicit) order thu_tu_mac_dinh = "{}, {} và {}".format('Qu?n','Tr?','M?ng') print('n--- Th? t? m?c ??nh ---') print(thu_tu_mac_dinh) # s? d?ng ??i s? v? trí ?? s?p x?p th? t? vi_tri_thu_tu= "{1}, {0} và {2}".format('Qu?n','Tr?','M?ng') print('n--- Th? t? theo v? trí ---') print(vi_tri_thu_tu) # s? d?ng t? khóa ?? s?p x?p th? t? tu_khoa_thu_tu = "{s}, {b} và {j}".format(j='Qu?n',b='Tr?',s='M?ng') print('n--- Th? t? theo t? khóa ---') print(tu_khoa_thu_tu)

We have the following result when running the above code:

--- Th? t? m?c ??nh --- Qu?n, Tr? và M?ng --- Th? t? theo v? trí --- Tr?, Qu?n và M?ng --- Th? t? theo t? khóa --- M?ng, Tr? và Qu?n

The format() method can have optional format specifications. They are separated from the field name by a :. For example, it is possible to left-align <, right-align >, or center ^ a string in the given space. Can format integers as binary or hexadecimal numbers; Decimal numbers can be rounded or displayed as an exponent. There are many formats you can use.

>>> # ??nh d?ng s? nguyên >>> "Khi chuy?n {0} sang nh? phân s? là {0:b}".format(12) 'Khi chuy?n 12 sang nh? phân s? là 1100' >>> # ??nh d?ng s? th?p phân >>> "S? th?p phân {0} ? d?ng m? s? là {0:e}".format(1566.345) 'S? th?p phân 1566.345 ? d?ng m? s? là 1.566345e+03' >>> # Làm tròn s? th?p phân >>> "1 ph?n 3 là: {0:.3f}".format(1/3) '1 ph?n 3 là: 0.333' >>> # c?n ch?nh chu?i >>> "|{:<10}|{:^10}|{:>10}|".format('Qu?n','Tr?','M?ng') '|Qu?n | Tr? | M?ng|'

Old-style string format:

You can format a string in Python to the sprintf() style used in the C programming language using the %.

>>> x = 15.1236789 >>> print('Giá tr? c?a x là %3.2f' %x) Giá tr? c?a x là 15.12 >>> print('Giá tr? c?a x là %3.4f' %x) Giá tr? c?a x là 15.123712.3457

The Method Is Commonly Used in String

There are many built-in methods in Python for working with strings. In addition to format() mentioned above, there are also lower(), upper(), join(), split(), find(), replace(), etc.

4. List (List)

Python provides a series of complex data, often called sequences, used to group different values. The most versatile is the list.

How to Create Lists in Python

In Python, a list is represented by a sequence of values, separated by commas, enclosed in []. Lists can contain multiple items of different types, but typically the items are of the same type.

>>> squares = [1, 4, 9, 16, 25] >>> squares [1, 4, 9, 16, 25]
list1 = [] # list r?ng list2 = [1, 2, 3] # list s? nguyên list3 = [1, "Hello", 3.4] # list v?i ki?u d? li?u h?n h?p
a = ['a', 'b', 'c'] n = [1, 2, 3] x = [a, n] print (x) # Output: [['a', 'b', 'c'], [1, 2, 3]] print (x[0]) # Output: ['a', 'b', 'c'] print(x[0][1]) # Output: b

Ho?c khai báo list l?ng nhau t? ??u:

list4 = [mouse", [8, 4, 6], ['a']]

Truy C?p Vào Ph?n T? C?a List

Index (ch? m?c) c?a list:

qtm_list = ['q','u','a','n','t','r','i','m','a','n','g','.','c','o','m'] # TypeError: list indices must be integers or slices, not float # TypeError: index c?a list ph?i là s? nguyên ho?c slice, không ph?i s? th?p phân qtm_list[2.0]

List l?ng nhau có th? truy c?p b?ng index l?ng nhau:

qtm_list = ['q','u','a','n','t','r','i','m','a','n','g','.','c','o','m'] # Output: q print(qtm_list[0]) # Output: a print(qtm_list[2]) # Output: t print(qtm_list[4]) # List l?ng nhau ln_list = ["Happy", [1,3,5,9]] # Index l?ng nhau # Output: a print(ln_list[0][1]) # Output: 9 print(ln_list[1][3])

Index âm:

qtm_list = ['q','u','a','n','t','r','i','m','a','n','g','.','c','o','m'] # Code by TipsMake.com # Output: m print(qtm_list[-1]) # Output: i print(qtm_list[-9])

C?t Lát (Slice) List Trong Python

qtm_list = ['q','u','a','n','t','r','i','m','a','n','g','.','c','o','m'] # Code by TipsMake.com # Output: ['u', 'a', 'n', 't'] print(qtm_list[1:5]) # Output: ['q', 'u', 'a', 'n', 't', 'r', 'i'] print(qtm_list[:-8]) # Output: ['n', 'g', '.', 'c', 'o', 'm'] print(qtm_list[9:])
qtm_list = ['q','u','a','n','t','r','i','m','a','n','g','.','c','o','m'] # Output: ['q', 'u', 'a', 'n', 't', 'r', 'i', 'm', 'a', 'n', 'g', '.', 'c', 'o', 'm'] print(qtm_list[:])

Thay ??I Ho?c Thêm Ph?n T? Vào List

List c?ng h? tr? các ho?t ??ng nh? n?i list:

>>> squares + [36, 49, 64, 81, 100] [1, 4, 9, 16, 25, 36, 49, 64, 81, 100]
>>> cubes = [1, 8, 27, 65, 125] # có v? sai sai >>> 4 ** 3 # l?p ph??ng c?a 4 là 64, không ph?i 65! 64 >>> cubes[3] = 64 # thay th? giá tr? sai >>> cubes [1, 8, 27, 64, 125]
>>> cubes.append(216) # thêm l?p ph??ng c?a 6 >>> cubes.append(7 ** 3) # và l?p ph??ng c?a 7 >>> cubes [1, 8, 27, 64, 125, 216, 343]
>>> letters = ['a', 'b', 'c', 'd', 'e', 'f', 'g'] >>> letters ['a', 'b', 'c', 'd', 'e', 'f', 'g'] >>> # thay th? vài giá tr? >>> letters[2:5] = ['C', 'D', 'E'] >>> letters ['a', 'b', 'C', 'D', 'E', 'f', 'g'] >>> # gi? thì xóa chúng >>> letters[2:5] = [] >>> letters ['a', 'b', 'f', 'g'] >>> # xóa list b?ng cách thay t?t c? các ph?n t? b?ng m?t list r?ng >>> letters[:] = [] >>> letters []

Hàm len() c?ng có th? áp d?ng v?i list:

>>> letters = ['a', 'b', 'c', 'd'] >>> len(letters) 4

Xóa Ho?c Lo?i B? Ph?n T? Kh?i List Trong Python

my_list = ['q','u','a','n','t','r','i','m','a','n','g','.','c','o','m'] # xóa ph?n t? có index là 2 del my_list[2] # Output: ['q', 'u', 'n', 't', 'r', 'i', 'm', 'a', 'n', 'g', '.', 'c', 'o', 'm'] print(my_list) # xóa ph?n t? có index t? 1 ??n 7 del my_list[1:7] # Output: ['q', 'a', 'n', 'g', '.', 'c', 'o', 'm'] print(my_list) # xóa toàn b? list my_list del my_list # Error: NameError: name 'my_list' is not defined print(my_list)
my_list = ['q','u','a','n','t','r','i','m','a','n','g','.','c','o','m'] my_list.remove('.') # Output: ['q', 'u', 'a', 'n', 't', 'r', 'i', 'm', 'a', 'n', 'g', 'c', 'o', 'm'] print(my_list) # Output: n print(my_list.pop(3)) # Output: ['q', 'u', 'a', 't', 'r', 'i', 'm', 'a', 'n', 'g', 'c', 'o', 'm'] print(my_list) # Output: m print(my_list.pop()) # Output: ['q', 'u', 'a', 't', 'r', 'i', 'm', 'a', 'n', 'g', 'c', 'o'] print(my_list) my_list.clear() # Output: [] (list r?ng) print(my_list)
>>> my_list = ['q','u','a','n','t','r','i','m','a','n','g','.','c','o','m'] >>> my_list[11:15]=[] >>> my_list ['q', 'u', 'a', 'n', 't', 'r', 'i', 'm', 'a', 'n', 'g']

Ph??ng Th?c List Trong Python

  • append() : Thêm ph?n t? vào cu?i list.
  • extend() : Thêm t?t c? ph?n t? c?a list hi?n t?i vào list khác.
  • remove() : Xóa ph?n t? kh?i list.
  • clear() : Xóa t?t c? ph?n t? c?a list.
  • index() : Tr? v? index c?a ph?n t? phù h?p ??u tiên.
  • copy() : Tr? v? b?n sao c?a list.

Ví d?:

QTM = [9,8,7,6,8,5,8] # Output: 2 print(QTM.index(7)) # Output: 3 print(QTM.count(8)) QTM.sort() # Output: [5, 6, 7, 8, 8, 8, 9] print(QTM) QTM.reverse() # Output: [9, 8, 8, 8, 7, 6, 5] print(QTM)

Ví d? 2:

QTM = ['q','u','a','n','t','r','i','m','a','n','g','.','c','o','m'] # Output: 3 print(QTM.index('n')) # Output: 2 print(QTM.count('a')) QTM.sort() # Output: ['.', 'a', 'a', 'c', 'g', 'i', 'm', 'm', 'n', 'n', 'o', 'q', 'r', 't', 'u'] print(QTM) QTM.reverse() # Output: ['u', 't', 'r', 'q', 'o', 'n', 'n', 'm', 'm', 'i', 'g', 'c', 'a', 'a', '.'] print(QTM)

List Comprehension: Cách T?o List M?i Ng?n G?n

Ví d?:

cub3 = [3 ** x for x in range(9)] # Output: [1, 3, 9, 27, 81, 243, 729, 2187, 6561] print(cub3)

Code trên t??ng ???ng v?i:

cub3 = [] for x in range (9): cub3.append(3**x) print(cub3)
cub3 = [3 ** x for x in range(9) if x > 4] # Output: [243, 729, 2187, 6561] print(cub3) so_le = [x for x in range (18) if x % 2 == 1] # Output: [1, 3, 5, 7, 9, 11, 13, 15, 17] print(so_le) noi_list = [x+y for x in ['Ngôn ng? ','L?p trình '] for y in ['Python','C++']] # Output: ['Ngôn ng? Python', 'Ngôn ng? C++', 'L?p trình Python', 'L?p trình C++'] print(noi_list)

Ki?m Tra Ph?n T? Có Trong List Không

QTM = ['q','u','a','n','t','r','i','m','a','n','g','.','c','o','m'] # Output: True print('q' in QTM) # Output: True print('.' in QTM) # Output: False print('z' in QTM)

Vòng L?p for Trong List

for ngon_ngu in ['Python','Java','C']: print("Tôi thích l?p trình",ngon_ngu)

K?t qu? tr? v? s? nh? sau:

Tôi thích l?p trình Python Tôi thích l?p trình Java Tôi thích l?p trình C

Các Hàm Python Tích H?p V?i List

  • any() : Tr? v? True khi b?t k? ph?n t? nào trong list là true. N?u list r?ng hàm tr? v? giá tr? False.
  • len() : Tr? v? ?? dài (s? l??ng ph?n t?) c?a list.
  • list() : Chuy?n ??i m?t ??i t??ng có th? l?p (tuple, string, set, dictionary) thành list.
  • max() : Tr? v? ph?n t? l?n nh?t trong list.
  • min() : Tr? v? ph?n t? nh? nh?t trong list.
  • sorted() : Tr? v? list m?i ?ã ???c s?p x?p.

5. Tuple

Ví d?:

t = (10, "tips make", 2j)
t = (10, "tips make", 2j) #t[0:2] = (10, 'tips make') print("t[0:2] = ", t[0:2])

Ch?y code trên ta ???c k?t qu?:

t[0:2] = (10, 'tips make')

Tuple H?n List ? ?I?m Nào?

T?o M?t Tuple

# Tuple r?ng # Output: () my_tuple = () print(my_tuple) # tuple s? nguyên # Output: (2, 4, 16, 256) my_tuple = (2, 4, 16, 256) print(my_tuple) # tuple có nhi?u ki?u d? li?u # Output: (10, "TipsMake.com", 3.5) my_tuple = (10, "TipsMake.com", 3.5) print(my_tuple) # tuple l?ng nhau # Output: ("QTM", [2, 4, 6], (3, 5, 7)) my_tuple = ("QTM", [2, 4, 6], (3, 5, 7)) print(my_tuple) # tuple có th? ???c t?o mà không c?n d?u () # còn g?i là ?óng gói tuple # Output: (10, "TipsMake.com", 3.5) my_tuple = 10, "TipsMake.com", 3.5 print(my_tuple) # m? gói (unpacking) tuple c?ng có th? làm ???c # Output: # 10 # TipsMake.com # 3.5 a, b, c = my_tuple print(a) print(b) print(c) 
# t?o tuple ch? v?i () # Output: 
 
 my_tuple = ("TipsMake.com") print(type(my_tuple)) # khi thêm d?u ph?y vào cu?i # Output: 
 
 my_tuple = ("TipsMake.com",) print(type(my_tuple)) # d?u () là tùy ch?n, b?n có th? b? n?u thích # Output: 
 
 my_tuple = "TipsMake.com", print(type(my_tuple))
 
 
 

Truy C?p Vào Các Ph?n T? C?a Tuple

# tuple l?ng nhau n_tuple = ("TipsMake.com", [2, 6, 8], (1, 2, 3)) # index l?ng nhau # Output: 'r' print(n_tuple[0][5]) # index l?ng nhau # Output: 8 print(n_tuple[1][2])

Thay ??I M?t Tuple

my_tuple = (1, 3, 5, [7, 9]) # không th? thay ??i ph?n t? c?a tuple # N?u b?n b? d?u # ? dòng 8 # B?n s? nh?n ???c l?i: # TypeError: 'tuple' object does not support item assignment #my_tuple[1] = 9 # Nh?ng ph?n t? có index 3 trong tuple là list # list có th? thay ??i, nên ph?n t? ?ó có th? thay ??i # Output: (1, 3, 5, [8, 9]) my_tuple[3][0] = 8 print(my_tuple) # N?u c?n thay ??i tuple hãy gán l?i giá tr? cho nó # Output: ('q', 'u', 'a', 'n', 't', 'r', 'i', 'm', 'a', 'n', 'g') my_tuple = ('q', 'u', 'a', 'n', 't', 'r', 'i', 'm', 'a', 'n', 'g') print(my_tuple)
# N?i 2 tuple # Output: (2, 4, 6, 3, 5, 7) print((2, 4, 6) + (3, 5, 7)) # L?p l?i tuple # Output: ('TipsMake.com', 'TipsMake.com', 'TipsMake.com') print(("TipsMake.com",) * 3)

Xóa Tuple

QTM = ('q','u','a','n','t','r','i','m','a','n','g','.','c','o','m') # Không th? xóa ph?n t? c?a tuple # N?u b?n ch?y l?nh del QTM[3] # s? t?o ra l?i: # TypeError: 'tuple' object doesn't support item deletion # Có th? xóa toàn b? tuple del QTM # Sau ?ó th? ch?y print (QTM) s? tr? v? l?i # NameError: name 'QTM' is not defined 

Ph??ng Th?c Và Hàm Dùng V?i Tuple Trong Python

  • count(x) : ??m s? ph?n t? x trong tuple.
QTM = ['q','u','a','n','t','r','i','m','a','n','g','.','c','o','m'] # Count # Output: 2 print(QTM.count('m')) # Index # Output: 3 print(QTM.index('n'))
  • any() : Tr? v? True n?u b?t k? ph?n t? nào c?a tuple là true, n?u tuple r?ng tr? v? False.
  • len() : Tr? v? ?? dài (s? ph?n t?) c?a tuple.
  • max() : Tr? v? ph?n t? l?n nh?t c?a tuple.
  • min() : Tr? v? ph?n t? nh? nh?t c?a tuple.
  • tuple() : Chuy?n ??i nh?ng ??i t??ng có th? l?p (list, string, set, dictionary) thành tuple.

Ki?m Tra Ph?n T? Trong Tuple

QTM = ['q','u','a','n','t','r','i','m','a','n','g','.','c','o','m'] # Ki?m tra ph?n t? # Output: True print('a' in QTM) # Output: False print('b' in QTM) # Not in operation # Output: False print('g' not in QTM)

L?p Qua Các Ph?n T? C?a Tuple Trong Python

for ngon_ngu in ('Python','C++','Web'): print("Tôi thích l?p trình",ngon_ngu)

K?t qu? tr? v? s? nh? sau:

Tôi thích l?p trình Python Tôi thích l?p trình C++ Tôi thích l?p trình Web

6. Set

Cách T?o Set

Ví d? v? set:

a = {5,2,3,1,4}

N?u th?c hi?n l?nh in nh? sau:

print("a=", a)
a = {1, 2, 3, 4, 5}

Set v?i nhi?u ki?u d? li?u h?n h?p nh? sau:

my_set = {1.0, "Xin chào", (1, 2, 3)} #Output: QTM_Set= {'Xin chào', 1.0, (1, 2, 3)} print("QTM_Set=",my_set)
# initialize a with {} qtm = {} # Ki?m tra ki?u d? li?u c?a qtm # Output: 
 
 print(type(qtm)) # Kh?i t?o qtm v?i set() qtm = set() # Ki?m tra ki?u d? li?u c?a qtm # Output: 
 
 print(type(qtm))
 
 

Làm Sao ?? Thay ??I Set Trong Python

>>> a[1] Traceback (most recent call last): File "
 
 ", line 1, in a[1] TypeError: 'set' object does not support indexing
 
# Kh?i t?o my_set my_set = {1,3} print(my_set) # N?u b? d?u # ? dòng 9, # B?n s? nh?n ???c l?i # TypeError: 'set' object does not support indexing #my_set[0] # Thêm ph?n t? # Output: {1, 2, 3} my_set.add(2) print(my_set) # Thêm nhi?u ph?n t? vào set # Output: {1, 2, 3, 4} my_set.update([2,3,4]) print(my_set) # Thêm list và set # Output: {1, 2, 3, 4, 5, 6, 8} my_set.update([4,5], {1,6,8}) print(my_set)

Xóa Ph?n T? Kh?i Set

# Kh?i t?o my_set my_set = {1, 3, 4, 5, 6} print(my_set) # Xóa ph?n t? b?ng discard() # Output: {1, 3, 5, 6} my_set.discard(4) print(my_set) # Xóa b?ng remove() # Output: {1, 3, 5} my_set.remove(6) print(my_set) # Xóa ph?n t? không có # trong set b?ng discard() # Output: {1, 3, 5} my_set.discard(2) print(my_set) # Xóa ph?n t? không có # trong set b?ng remove() # N?u b?n b? d?u # ? dòng 27, # b?n s? nh?n ???c l?i. # Output: KeyError: 2 #my_set.remove(2)
# Kh?i t?o my_set # Output: set of unique elements my_set = set("TipsMake.com") print(my_set) # xóa ph?n t? b?ng pop() # Output: ph?n t? b? xóa ng?u nhiên print(my_set.pop()) # xóa ph?n t? khác b?ng pop() # Output: ph?n t? b? xóa ng?u nhiên my_set.pop() print(my_set) # clear my_set #Output: set() my_set.clear() print(my_set)

Các Toán T? Set Trong Python

Ta s? s? d?ng 2 t?p h?p d??i ?ây:

>>> A = {1, 2, 3, 4, 5} >>> B = {4, 5, 6, 7, 8}
# Kh?i t?o A và B A = {1, 2, 3, 4, 5} B = {4, 5, 6, 7, 8} # s? d?ng toán t? | # Output: {1, 2, 3, 4, 5, 6, 7, 8} print(A | B) # s? d?ng hàm union() # Output: Nh? trên print(A.union(B)) print(B.union(A))
# kh?i t?o A và B A = {1, 2, 3, 4, 5} B = {4, 5, 6, 7, 8} # s? d?ng & # Output: {4, 5} print(A & B) # s? d?ng intersection() # Output: {4, 5} print(A.intersection(B)) print(B.intersection(A))
# Kh?i t?o A và B A = {1, 2, 3, 4, 5} B = {4, 5, 6, 7, 8} # S? d?ng toán t? - trên A # Output: {1, 2, 3} print(A - B) # S? d?ng hàm difference() trên A # Output: {1, 2, 3} print(A.difference(B)) # S? d?ng toán t? - trên B # Output: {8, 6, 7} print(B - A) # S? d?ng difference() trên B # Output: {8, 6, 7} print(B.difference(A))
# Kh?i t?o A và B A = {1, 2, 3, 4, 5} B = {4, 5, 6, 7, 8} # S? d?ng toán t? ^ # Output: {1, 2, 3, 6, 7, 8} print(A ^ B) # S? d?ng symmetric_difference() trên A # Output: {1, 2, 3, 6, 7, 8} print(A.symmetric_difference(B))

Các Ph??ng Th?c Dùng Trên Set

Ph??ng th?c Mô t?
add() Thêm m?t ph?n t? vào set.
clear() Xóa t?t c? ph?n t? c?a set.
copy() Tr? v? b?n sao chép c?a set.
difference() Tr? v? set m?i ch?a nh?ng ph?n t? khác nhau c?a 2 hay nhi?u set.
difference_update() Xóa t?t c? các ph?n t? c?a set khác t? set này.
discard() Xóa ph?n t? n?u nó có m?t trong set.
intersection() Tr? v? set m?i ch?a ph?n t? chung c?a 2 set.
intersection_update() C?p nh?t set v?i ph?n t? chung c?a chính nó và set khác.
isdisjoint() Tr? v? True n?u 2 set không có ph?n t? chung.
issubset() Tr? v? True n?u set khác ch?a set này.
issuperset() Tr? v? True n?u set này ch?a set khác.
pop() Xóa và tr? v? ph?n t? ng?u nhiên, báo l?i KeyError n?u set r?ng.
remove() Xóa ph?n t? t? set. N?u ph?n t? ?ó không có trong set s? báo l?i KeyError.
symmetric_difference() Tr? v? set m?i ch?a nh?ng ph?n t? không ph?i là ph?n t? chung c?a 2 set.
symmetric_difference_update() C?p nh?t set v?i nh?ng ph?n t? khác nhau c?a chính nó và set khác.
union() Tr? v? set m?i là h?p c?a 2 set.
update() C?p nh?t set v?i h?p c?a chính nó và set khác.

Ki?m Tra Ph?n T? Trong Set

# Kh?i t?o my_set my_set = set("TipsMake.com") # Ki?m tra xem Q có trong my_set không # Output: True print('Q' in my_set) # Ki?m tra xem q có trong my_set không # Output: False print('q' in my_set)

L?p Qua Ph?n T? C?a Set

for letter in set("Python"): print(letter)
t y P h o n

Hàm Th??ng Dùng Trên Set

Hàm

Mô t?

all()

Tr? v? True n?u t?t c? thành ph?n c?a set ??u là true (ho?c n?u set là empty).

any()

Tr? v? True n?u ph?n t? b?t k? ???c thi?t l?p là true. N?u set là empty, tr? v? False .

enumerate()

 

len()

 

max()

Tr? v? m?c l?n nh?t trong set.

min()

Tr? v? m?c nh? nh?t trong set.

sorted()

 

sum()

 

Frozenset Trong Python

7. Dictionary

Cách T?o Dictionary Trong Python

Ví d?:

dict1 = {} #dictionary r?ng #dict2 là dictionary v?i các khóa nguyên dict2 = {1: 'TipsMake.com',2: 'Công ngh?'} #T?o dictionary v?i khóa h?n h?p dict3 = {'tên': 'QTM', 1: [1, 3, 5]} #T?o dictionary b?ng dict() dict4 = dict({1:'apple', 2:'ball'}) #T?o dictionary t? chu?i v?i m?i m?c là m?t c?p dict5 = dict([(1,'QTM'), (2,'CN')])
>>> type(dict2) 
 

Trích Xu?t M?ng

users = {'firstname': 'John', 'lastname': 'Smith', 'age': 27} print(users.keys()) # prints ['lastname', 'age', 'firstname']

Truy C?p Ph?n T? C?a Dictionary

S? d?ng khóa ?? trích xu?t d? li?u:

#khai báo và gán giá tr? dict2 dict2 = {1: 'TipsMake.com','TipsMake': 'Công ngh?'} print(type(dict2)) #in ki?u d? li?u c?a dict2 #trích xu?t d? li?u b?ng khóa r?i in print("dict2[1] = ", dict2[1]) print("dict2[TipsMake] = ",dict2['TipsMake'])

Ch?y ?o?n code trên ta s? ???c k?t qu?:


 
 dict2[1] = TipsMake.com dict2[TipsMake] = Công ngh?
 

Truy c?p khóa - giá tr? trong dictionary

# Ví d? l?p trình Python minh h?a cách truy c?p m?t ph?n t? t? dictionary # T?o m?t Dictionary Dict = {1: 'Geeks', 'name': 'For', 3: 'Geeks'} # Truy c?p ph?n t? b?ng key print("Accessing a element using key:") print(Dict['name']) # Truy c?p ph?n t? b?ng get() # Ph??ng th?c print("Accessing a element using get:") print(Dict.get(3))

K?t qu?:

Truy c?p m?t ph?n t? b?ng key: For Truy c?p m?t ph?n t? b?ng get: Geeks

Thay ??I, Thêm Ph?n T? Cho Dictionary

dict2 = {1: 'TipsMake.com','TipsMake': 'Công ngh?'} #c?p nh?t giá tr? dict2['TipsMake'] = 'Tips Make' #output: {1: 'TipsMake.com', 'TipsMake': 'Tips Make'} print(dict2) #thêm ph?n t? m?i dict2[2] = 'Python' #output: {1: 'TipsMake.com', 'TipsMake': 'Tips Make', 2: 'Python'} print(dict2)

Xóa Ph?n T? T? Dictionary

# t?o dictionary binh_phuong = {1:1, 2:4, 3:9, 4:16, 5:25} # xóa ph?n t? s? 4 # Output: 16 print(binh_phuong.pop(4)) # Output: {1: 1, 2: 4, 3: 9, 5: 25} print(binh_phuong) # xóa ph?n t? c? th? del binh_phuong[2] # output: {1: 1, 3: 9, 5: 25} print(binh_phuong) # xóa ph?n t? b?t k? # Output: (5, 25) print(binh_phuong.popitem()) # Output: {1: 1, 3: 9} print(binh_phuong) # xóa t?t c? ph?n t? binh_phuong.clear() # output: {} print(binh_phuong) # xóa dictionary binh_phuong del binh_phuong # t?o l?i n?u b? # ? l?nh sau # print(squares)

Các Ph??ng Th?c Và Hàm Cho Dictionary

Method Mô t?
clear() Xóa t?t c? ph?n t? c?a dictionary.
copy() Tr? v? m?t b?n sao shollow copy c?a dictionary.
fromkeys(seq[,v]) Tr? v? dictionary m?i v?i key t? seq và value b?ng v (default là None).
get(key[,d]) Tr? v? giá tr? c?a key, n?u key không t?n t?i, tr? v? d. (default là None).
items() Tr? l?i ki?u xem m?i c?a các ph?n t? trong dictionary (key, value).
keys() Tr? v? ki?u xem m?i c?a các key trong dictionary.
pop(key[,d]) Xóa ph?n t? b?ng key và tr? v? giá tr? ho?c d n?u key không tìm th?y. N?u d không ???c c?p, key không t?n t?i thì s? t?o l?i KeyError.
popitem() Xóa và tr? v? ph?n t? b?t k? ? d?ng (key, value). T?o l?i KeyError n?u dictionary r?ng.
setdefault(key,[,d]) N?y key t?n t?i tr? v? value c?a nó, n?u không thêm key v?i value là d và tr? v? d (default là None).
update([other]) C?p nh?t dictionary v?i c?p key/value t? other, ghi ?è lên các key ?ã có.
values() Tr? v? ki?u view m?i c?a value trong dictionary.

Dictionary Comprehension Trong Python

lap_phuong = {x: x*x*x for x in range(6)} # Output: {0: 0, 1: 1, 2: 8, 3: 27, 4: 64, 5: 125} print(lap_phuong)

Ch??ng trình trên t??ng ???ng v?i

lap_phuong = {} for x in range(6): lap_phuong[x] = x*x*x print(lap_phuong)
lap_phuong_chan = {x: x*x*x for x in range (10) if x%2==0} # output: {0: 0, 2: 8, 4: 64, 6: 216, 8: 512} print(lap_phuong_chan)

Ki?m Tra Và L?p Qua Ph?n T? Trong Dictionary

lap_phuong = {0: 0, 1: 1, 2: 8, 3: 27, 4: 64, 5: 125} #output: True print (2 in lap_phuong) #output: False print (9 in lap_phuong) #output: False print (5 not in lap_phuong)
lap_phuong = {0: 0, 1: 1, 2: 8, 3: 27, 4: 64, 5: 125} for i in lap_phuong print(lap_phuong[i])

8. Chuy?n ??I Gi?a Các Ki?u D? Li?u

Chúng ta có th? chuy?n ??i gi?a các ki?u d? li?u khác nhau b?ng cách s? d?ng hàm chuy?n ??i ki?u khác nhau nh? int() (ki?u s? nguyên), float() s? th?p phân, str() chu?i,.

Ví d?:

>>> float(11) 11.0

Ví d?:

int(18.6) 18

Chuy?n ??i t? string sang ho?c ng??c l?i ph?i có các giá tr? t??ng thích.

B?n có th? th?c hi?n chuy?n ??i chu?i này sang chu?i khác:

>>> set([2,4,6]) {2,4,6} >>> tuple({3,5,7}) (3,5,7) >>> list('TipsMake') ['q', 'u', 'a', 'n', 't', 'r', 'i', 'm', 'a', 'n', 'g']

?? chuy?n ??i sang dictionary, m?i ph?n t? ph?i là m?t c?p nh? ví d? d??i ?ây:

>>> dict([[2,4],[1,3]]) {2: 4, 1: 3} >>> dict([(3,9),(4,16)]) {3: 9, 4: 16}

9. B??c ??U Tiên H??ng T?i L?p Trình

>>> # Dãy Fibonacci: . # t?ng c?a hai ph?n t? t?o nên ph?n t? ti?p theo . a, b = 0, 1 >>> while b < 10: . print(b) . a, b = b, a+b . 1 1 2 3 5 8

Ví d? này gi?i thi?u m?t s? tính n?ng m?i:

>>> i = 256*256 >>> print('The value of i is', i) The value of i is 65536
>>> a, b = 0, 1 >>> while b < 1000: . print(b, end=',') . a, b = b, a+b . 1,1,2,3,5,8,13,21,34,55,89,144,233,377,610,987,

FAQ

What is the main update about Python String?

How are data types in Python: string, number, list, tuple, set and dictionary used?

Why does Python String matter?

Let's find out with TipsMake.com!

What should readers know about Python String?

Data types are ways of classifying data items.

Discussion

Reader Comments 0

Sign in with email or Google to join the discussion.