Home Backend Development Python Tutorial Python variable types

Python variable types

Nov 23, 2016 am 11:23 AM
python

Variables store the value in memory. This means that when a variable is created, a space is created in memory.

Based on the data type of the variable, the interpreter will allocate the specified memory and decide what data can be stored in the memory.

Thus, variables can specify different data types, and these variables can store integers, decimals, or characters.

Variable assignment

Variables in Python do not need to be declared. The assignment operation of variables is both a process of variable declaration and definition.

Each variable is created in memory and includes information such as the variable's identity, name and data.

Each variable must be assigned a value before use. The variable will not be created until the variable is assigned a value.

The equal sign (=) is used to assign values ​​to variables.

The left side of the equal sign (=) operator is a variable name, and the right side of the equal sign (=) operator is the value stored in the variable. For example:

#!/usr/bin/python
 
counter = 100 # An integer assignment
miles = 1000.0 # A floating point
name = "John" # A string
 
print counter
print miles
print name
Copy after login

In the above example, 100, 1000.0 and "John" are assigned to the counter, miles, and name variables respectively.

Executing the above program will output the following results:

100

1000.0

John

Multiple variable assignments

Python allows you to assign values ​​to multiple variables at the same time value. For example:

a = b = c = 1

In the above example, an integer object is created with a value of 1, and three variables are allocated to the same memory space.

You can also specify multiple variables for multiple objects. For example:

a, b, c = 1, 2, "john"

In the above example, two integer objects 1 and 2 are assigned to variables a and b, and string objects" john" is assigned to variable c.

Standard data types

The data stored in memory can be of many types.

For example, a person.s age is stored as a numeric value and his or her address is stored as alphanumeric characters.

Python has some standard types for defining operations on them and storage methods possible for each of them.

Python has five standard data types:

Numbers (Numbers)

String (String)

List (List)

Tuple (Tuple)

Dictionary (Dictionary)

Python numbers

Numeric data type is used to store numerical values.

They are immutable data types, which means changing the numeric data type will allocate a new object.

When you specify a value, a Number object is created:

var1 = 1

var2 = 10

You can also use the del statement to delete some object references. The syntax of

del statement is:

del var1[,var2[,var3[....,varN]]]]

You can delete single or multiple items by using del statement object. For example:

del var

del var_a, var_b

Python supports four different numerical types:

int (signed integer)

long (long integer [also available] Represents octal and hexadecimal])

float (float)

complex (plural)

instances

Some examples of numeric types:

int

long

float

complex

10 51924361L 0.0 3.14j

100 -0x19323L 15.20 45.j

-786 0122L -21.9 9.322e-36j

080 0xDEFABCECBDAECBFBAEl 32.3+e18 .876j

-0490 535633629843L -90. -.6545+0J

-0x260 -052318172735L -32.54e100 3e+26J

0x69 -4721885298529L 70.2-E12 4.53e-7j

You can also use lowercase "L" for long integers, but it is still recommended that you use uppercase "L" to avoid mixing it with numbers. 1" Confused. Python uses "L" to display long integers.

Python also supports complex numbers. Complex numbers are composed of real parts and imaginary parts. They can be represented by a + bj, or complex(a,b). The real part a and the imaginary part b of complex numbers are both floating point types

Python String

A string or string (String) is a string of characters composed of numbers, letters, and underscores.

is generally recorded as:

s="a1a2a3···"

It is a data type that represents text in programming languages.

Python's string list has two order of values:

The index from left to right starts with 0 by default, and the maximum range is 1 less than the length of the string

The index from right to left starts with -1 by default, and the maximum range is The beginning of the string

If you actually want to get a substring, you can use the variable [head subscript: tail subscript] to intercept the corresponding string, where the subscript starts from 0 and can be positive Number or negative number, the subscript can be empty to indicate getting to the beginning or end.

For example:

s = "ilovepython"

s[1:5]的结果是love。

当使用以冒号分隔的字符串,python返回一个新的对象,结果包含了以这对偏移标识的连续的内容,左边的开始是包含了下边界。

上面的结果包含了s[1]的值l,而取到的最大范围不包括上边界,就是s[5]的值p。

加号(+)是字符串连接运算符,星号(*)是重复操作。如下实例:

#!/usr/bin/python
 
str = "Hello World!"
 
print str # 输出完整字符串
print str[0] # 输出字符串中的第一个字符
print str[2:5] # 输出字符串中第三个至第五个之间的字符串
print str[2:] # 输出从第三个字符开始的字符串
print str * 2 # 输出字符串两次
print str + "TEST" # 输出连接的字符串
Copy after login

以上实例输出结果:

Hello World!

H

llo

llo World!

Hello World!Hello World!

Hello World!TEST

Python列表

List(列表) 是 Python 中使用最频繁的数据类型。

列表可以完成大多数集合类的数据结构实现。它支持字符,数字,字符串甚至可以包含列表(所谓嵌套)。

列表用[ ]标识。是python最通用的复合数据类型。看这段代码就明白。

列表中的值得分割也可以用到变量[头下标:尾下标],就可以截取相应的列表,从左到右索引默认0开始的,从右到左索引默认-1开始,下标可以为空表示取到头或尾。

加号(+)是列表连接运算符,星号(*)是重复操作。如下实例:

#!/usr/bin/python
 
List = [ "abcd", 786 , 2.23, "john", 70.2 ]
tinylist = [123, "john"]
 
print List # 输出完整列表
print List[0] # 输出列表的第一个元素
print List[1:3] # 输出第二个至第三个的元素 
print List[2:] # 输出从第三个开始至列表末尾的所有元素
print tinylist * 2 # 输出列表两次
print List + tinylist # 打印组合的列表
Copy after login

以上实例输出结果:

["abcd", 786, 2.23, "john", 70.200000000000003]

abcd

[786, 2.23]

[2.23, "john", 70.200000000000003]

[123, "john", 123, "john"]

["abcd", 786, 2.23, "john", 70.200000000000003, 123, "john"]

Python元组

元组是另一个数据类型,类似于List(列表)。

元组用"()"标识。内部元素用逗号隔开。但是元素不能二次赋值,相当于只读列表。

#!/usr/bin/python
 
Tuple = ( "abcd", 786 , 2.23, "john", 70.2 )
tinytuple = (123, "john")
 
print Tuple # 输出完整元组
print Tuple[0] # 输出列表的第一个元素
print Tuple[1:3] # 输出第二个至第三个的元素 
print Tuple[2:] # 输出从第三个开始至列表末尾的所有元素
print tinytuple * 2 # 输出元组两次
print Tuple + tinytuple # 打印组合的元组
Copy after login

以上实例输出结果:

("abcd", 786, 2.23, "john", 70.2)

abcd

(786, 2.23)

(2.23, "john", 70.2)

(123, "john", 123, "john")

("abcd", 786, 2.23, "john", 70.2, 123, "john")

以下是元组无效的,因为元组是不允许更新的。而列表是允许更新的:

#!/usr/bin/python
 
Tuple = ( "abcd", 786 , 2.23, "john", 70.2 )
List = [ "abcd", 786 , 2.23, "john", 70.2 ]
Tuple[2] = 1000 # 错误!元组中是非法应用
List[2] = 1000 # 正确!列表中是合法应用
Copy after login

Python元字典

字典(dictionary)是除列表意外python之中最灵活的内置数据结构类型。列表是有序的对象结合,字典是无序的对象集合。

两者之间的区别在于:字典当中的元素是通过键来存取的,而不是通过偏移存取。

字典用"{ }"标识。字典由索引(key)和它对应的值value组成。

#!/usr/bin/python
 
dict = {}
dict["one"] = "This is one"
dict[2] = "This is two"
 
tinydict = {"name": "john","code":6734, "dept": "sales"}
 
print dict["one"] # 输出键为"one" 的值
print dict[2] # 输出键为 2 的值
print tinydict # 输出完整的字典
print tinydict.keys() # 输出所有键
print tinydict.values() # 输出所有值
Copy after login

   

输出结果为:

This is one This is two {"dept": "sales", "code": 6734, "name": "john"} ["dept", "code", "name"] ["sales", 6734, "john"]

   

 

Python数据类型转换

有时候,我们需要对数据内置的类型进行转换,数据类型的转换,你只需要将数据类型作为函数名即可。

以下几个内置的函数可以执行数据类型之间的转换。这些函数返回一个新的对象,表示转换的值。

函数

描述

int(x [,base])

   

将x转换为一个整数

   

long(x [,base] )

   

将x转换为一个长整数

   

float(x)

   

将x转换到一个浮点数

   

complex(real [,imag])

   

创建一个复数

   

str(x)

   

将对象 x 转换为字符串

   

repr(x)

   

将对象 x 转换为表达式字符串

   

eval(str)

   

用来计算在字符串中的有效Python表达式,并返回一个对象

   

tuple(s)

   

将序列 s 转换为一个元组

   

list(s)

   

将序列 s 转换为一个列表

   

set(s)

   

转换为可变集合

   

dict(d)

Create a dictionary. d must be a sequence of (key, value) tuples.

frozenset(s)

Convert to immutable set

chr(x)

Convert an integer to a character

unichr(x)

Convert an integer to a Unicode character

hex(x)

Convert an integer to a hexadecimal string

oct(x)

Convert an integer to an octal string

Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

PHP and Python: Different Paradigms Explained PHP and Python: Different Paradigms Explained Apr 18, 2025 am 12:26 AM

PHP is mainly procedural programming, but also supports object-oriented programming (OOP); Python supports a variety of paradigms, including OOP, functional and procedural programming. PHP is suitable for web development, and Python is suitable for a variety of applications such as data analysis and machine learning.

Choosing Between PHP and Python: A Guide Choosing Between PHP and Python: A Guide Apr 18, 2025 am 12:24 AM

PHP is suitable for web development and rapid prototyping, and Python is suitable for data science and machine learning. 1.PHP is used for dynamic web development, with simple syntax and suitable for rapid development. 2. Python has concise syntax, is suitable for multiple fields, and has a strong library ecosystem.

Python vs. JavaScript: The Learning Curve and Ease of Use Python vs. JavaScript: The Learning Curve and Ease of Use Apr 16, 2025 am 12:12 AM

Python is more suitable for beginners, with a smooth learning curve and concise syntax; JavaScript is suitable for front-end development, with a steep learning curve and flexible syntax. 1. Python syntax is intuitive and suitable for data science and back-end development. 2. JavaScript is flexible and widely used in front-end and server-side programming.

Can vs code run in Windows 8 Can vs code run in Windows 8 Apr 15, 2025 pm 07:24 PM

VS Code can run on Windows 8, but the experience may not be great. First make sure the system has been updated to the latest patch, then download the VS Code installation package that matches the system architecture and install it as prompted. After installation, be aware that some extensions may be incompatible with Windows 8 and need to look for alternative extensions or use newer Windows systems in a virtual machine. Install the necessary extensions to check whether they work properly. Although VS Code is feasible on Windows 8, it is recommended to upgrade to a newer Windows system for a better development experience and security.

Can visual studio code be used in python Can visual studio code be used in python Apr 15, 2025 pm 08:18 PM

VS Code can be used to write Python and provides many features that make it an ideal tool for developing Python applications. It allows users to: install Python extensions to get functions such as code completion, syntax highlighting, and debugging. Use the debugger to track code step by step, find and fix errors. Integrate Git for version control. Use code formatting tools to maintain code consistency. Use the Linting tool to spot potential problems ahead of time.

PHP and Python: A Deep Dive into Their History PHP and Python: A Deep Dive into Their History Apr 18, 2025 am 12:25 AM

PHP originated in 1994 and was developed by RasmusLerdorf. It was originally used to track website visitors and gradually evolved into a server-side scripting language and was widely used in web development. Python was developed by Guidovan Rossum in the late 1980s and was first released in 1991. It emphasizes code readability and simplicity, and is suitable for scientific computing, data analysis and other fields.

How to run programs in terminal vscode How to run programs in terminal vscode Apr 15, 2025 pm 06:42 PM

In VS Code, you can run the program in the terminal through the following steps: Prepare the code and open the integrated terminal to ensure that the code directory is consistent with the terminal working directory. Select the run command according to the programming language (such as Python's python your_file_name.py) to check whether it runs successfully and resolve errors. Use the debugger to improve debugging efficiency.

Is the vscode extension malicious? Is the vscode extension malicious? Apr 15, 2025 pm 07:57 PM

VS Code extensions pose malicious risks, such as hiding malicious code, exploiting vulnerabilities, and masturbating as legitimate extensions. Methods to identify malicious extensions include: checking publishers, reading comments, checking code, and installing with caution. Security measures also include: security awareness, good habits, regular updates and antivirus software.

See all articles