Python变量和数据类型
一、整数
int = 20 print int print 45678 + 0x12fd2
二、浮点数
float = 2.3 print float
三、字符串
a、使用单引号(') 用单引号括起来表示字符串,例如: str = 'this is string' print str b、使用双引号(") 双引号中的字符串与单引号中的字符串用法完全相同,例如: str = "this is string"; print str c、使用三引号(''') 利用三引号,表示多行的字符串,可以在三引号中自由的使用单引号和双引号,例如: str = '''this is string this is pythod string this is string''' print str
四、布尔值
and:与运算,只有所有都为True,and运算结果才是True。 or:或运算,只要其中有一个为True,or运算结果就是True。 not:非运算,它是一个单目运算符,把True变成False,False 变成True。 bool = False print bool bool = True print bool
五、空值
空值是Python里一个特殊的值,用None表示。 None不能理解为0,因为0是有意义的,而None是一个特殊的空值。
六、列表
# -*- coding:utf-8 -*- lst = ['A', 'B', 1996, 2017] nums = [1, 3, 5, 7, 8, 13, 20] # 访问列表中的值 print "nums[0]:", nums[0] # 1 print "nums[2:5]:", nums[2:5] # [5, 7, 8] print "nums[1:]:", nums[1:] # [3, 5, 7, 8, 13, 20] print "nums[:-3]:", nums[:-3] # [1, 3, 5, 7] print "nums[:]:", nums[:] # [1, 3, 5, 7, 8, 13, 20] # 更新列表 nums[0] = "ljq" print nums[0] # 删除列表元素 del nums[0] '''nums[:]: [3, 5, 7, 8, 13, 20]''' print "nums[:]:", nums[:] # 列表脚本操作符 print len([1, 2, 3]) # 3 print [1, 2, 3] + [4, 5, 6] # [1, 2, 3, 4, 5, 6] print ['Hi!'] * 4 # ['Hi!', 'Hi!', 'Hi!', 'Hi!'] print 3 in [1, 2, 3] # True for x in [1, 2, 3]: print x, # 1 2 3 # 列表截取 L = ['spam', 'Spam', 'SPAM!'] print L[2] # 'SPAM!' print L[-2] # 'Spam' print L[1:] # ['Spam', 'SPAM!'] # 列表函数&方法 lst.append('append') # 在列表末尾添加新的对象 lst.insert(2, 'insert') # 将对象插入列表 lst.remove(1996) # 移除列表中某个值的第一个匹配项 lst.reverse() # 反向列表中元素,倒转 print lst.sort() # 对原列表进行排序 print lst.pop(1) # 移除列表中的一个元素(默认最后一个元素),并且返回该元素的值 print lst print lst.count('obj') # 统计某个元素在列表中出现的次数 lst.index('append') # 从列表中找出某个值第一个匹配项的索引位置,索引从0开始 lst.extend(lst) # 在列表末尾一次性追加另一个序列中的多个值(用新列表扩展原来的列表) print 'End:', lst
七、字典
字典(dictionary)是除列表之外python中最灵活的内置数据结构类型。列表是有序的对象结合,字典是无序的对象集合。两者之间的区别在于:字典当中的元素是通过键来存取的,而不是通过偏移存取。
# -*- coding:utf-8 -*- dit = {'name': 'Zara', 'age': 7, 'class': 'First'} dict1 = {'abc': 456} dict2 = {'abc': 123, 98.6: 37} seq = ('name', 'age', 'sex') # 访问字典里的值 print "dit['name']: ", dit['name'] print "dit['age']: ", dit['age'] # 修改字典 dit["age"] = 27 # 修改已有键的值 dit["school"] = "wutong" # 增加新的键/值对 print "dict['age']: ", dit['age'] print "dict['school']: ", dit['school'] # 删除字典 del dit['name'] # 删除键是'name'的条目 dit.clear() # 清空词典所有条目 del dit # 删除词典 dit = {'name': 'Zara', 'age': 7, 'class': 'First'} # 字典内置函数&方法 cmp(dict1, dict2) # 比较两个字典元素。 len(dit) # 计算字典元素个数,即键的总数。 str(dit) # 输出字典可打印的字符串表示。 type(dit) # 返回输入的变量类型,如果变量是字典就返回字典类型。 dit.copy() # 返回一个字典的浅复制 dit.fromkeys(seq) # 创建一个新字典,以序列seq中元素做字典的键,val为字典所有键对应的初始值 dit.get(dit['name']) # 返回指定键的值,如果值不在字典中返回default值 dit.has_key('class') # 如果键在字典dict里返回true,否则返回false dit.items() # 以列表返回可遍历的(键, 值) 元组数组 dit.keys() # 以列表返回一个字典所有的键 dit.setdefault('subject', 'Python') # 和get()类似, 但如果键不已经存在于字典中,将会添加键并将值设为default dit.update(dict2) # 把字典dict2的键/值对更新到dict里 dit.values() # 以列表返回字典中的所有值 dit.clear() # 删除字典内所有元素
八、元祖
Python的元组(tuple)与列表类似,不同之处在于元组的元素不能修改;元组使用小括号(),列表使用方括号[];元组创建很简单,只需要在括号中添加元素,并使用逗号(,)隔开即可.
# -*- coding:utf-8 -*- tup1 = ('physics', 'chemistry', 1997, 2000) tup2 = (1, 2, 3, 4, 5) tup3 = "a", "b", "c", "d" # 访问元组 print "tup1[0]: ", tup1[0] # physics print "tup1[1:3]: ", tup1[1:3] # ('chemistry', 1997) # 修改元组 tup4 = tup1 + tup2 print tup4 # (12, 34.56, 'abc', 'xyz') # 删除元组 tup = ('tup3', 'tup', 1997, 2000) print tup del tup # 元组索引&截取 L = ('spam', 'Spam', 'SPAM!') print L[0] # spam print L[1] # Spam print L[2] # 'SPAM!' print L[-2] # 'Spam' print L[1:] # ['Spam', 'SPAM!'] # 元组内置函数 print cmp(tup3, tup2) # 比较两个元组元素。 len(tup3) # 计算元组元素个数。 max(tup3) # 返回元组中元素最大值。 min(tup3) # 返回元组中元素最小值。 L = [1, 2, 3, 4] print L print tuple(L) # 将列表转换为元组。
九、定义字符串
\n 表示换行 \t 表示一个制表符 \\ 表示 \ 字符本身
十、Unicode字符串
Python默认编码ASCII编码 # -*- coding: utf-8 -*-
十一、数字类型转换
int(x [,base]) 将x转换为一个整数 float(x ) 将x转换到一个浮点数 complex(real [,imag]) 创建一个复数 str(x) 将对象x转换为字符串 repr(x) 将对象x转换为表达式字符串 eval(str) 用来计算在字符串中的有效Python表达式,并返回一个对象 tuple(s) 将序列s转换为一个元组 list(s) 将序列s转换为一个列表 chr(x) 将一个整数转换为一个字符 unichr(x) 将一个整数转换为Unicode字符 ord(x) 将一个字符转换为它的整数值 hex(x) 将一个整数转换为一个十六进制字符串 oct(x) 将一个整数转换为一个八进制字符串
The above is the detailed content of Detailed introduction to Python variables and data types. For more information, please follow other related articles on the PHP Chinese website!

Python and C each have their own advantages, and the choice should be based on project requirements. 1) Python is suitable for rapid development and data processing due to its concise syntax and dynamic typing. 2)C is suitable for high performance and system programming due to its static typing and manual memory management.

Choosing Python or C depends on project requirements: 1) If you need rapid development, data processing and prototype design, choose Python; 2) If you need high performance, low latency and close hardware control, choose C.

By investing 2 hours of Python learning every day, you can effectively improve your programming skills. 1. Learn new knowledge: read documents or watch tutorials. 2. Practice: Write code and complete exercises. 3. Review: Consolidate the content you have learned. 4. Project practice: Apply what you have learned in actual projects. Such a structured learning plan can help you systematically master Python and achieve career goals.

Methods to learn Python efficiently within two hours include: 1. Review the basic knowledge and ensure that you are familiar with Python installation and basic syntax; 2. Understand the core concepts of Python, such as variables, lists, functions, etc.; 3. Master basic and advanced usage by using examples; 4. Learn common errors and debugging techniques; 5. Apply performance optimization and best practices, such as using list comprehensions and following the PEP8 style guide.

Python is suitable for beginners and data science, and C is suitable for system programming and game development. 1. Python is simple and easy to use, suitable for data science and web development. 2.C provides high performance and control, suitable for game development and system programming. The choice should be based on project needs and personal interests.

Python is more suitable for data science and rapid development, while C is more suitable for high performance and system programming. 1. Python syntax is concise and easy to learn, suitable for data processing and scientific computing. 2.C has complex syntax but excellent performance and is often used in game development and system programming.

It is feasible to invest two hours a day to learn Python. 1. Learn new knowledge: Learn new concepts in one hour, such as lists and dictionaries. 2. Practice and exercises: Use one hour to perform programming exercises, such as writing small programs. Through reasonable planning and perseverance, you can master the core concepts of Python in a short time.

Python is easier to learn and use, while C is more powerful but complex. 1. Python syntax is concise and suitable for beginners. Dynamic typing and automatic memory management make it easy to use, but may cause runtime errors. 2.C provides low-level control and advanced features, suitable for high-performance applications, but has a high learning threshold and requires manual memory and type safety management.


Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

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

Hot Article

Hot Tools

Notepad++7.3.1
Easy-to-use and free code editor

Dreamweaver Mac version
Visual web development tools

ZendStudio 13.5.1 Mac
Powerful PHP integrated development environment

SAP NetWeaver Server Adapter for Eclipse
Integrate Eclipse with SAP NetWeaver application server.

DVWA
Damn Vulnerable Web App (DVWA) is a PHP/MySQL web application that is very vulnerable. Its main goals are to be an aid for security professionals to test their skills and tools in a legal environment, to help web developers better understand the process of securing web applications, and to help teachers/students teach/learn in a classroom environment Web application security. The goal of DVWA is to practice some of the most common web vulnerabilities through a simple and straightforward interface, with varying degrees of difficulty. Please note that this software