Empty (None)
None can be used to indicate that the value of a certain variable is missing, similar to null in other languages.
Like other null values: 0, [] and empty string, Boolean variables give False instead of True.
if None:print("None got interpreted as True")else:print("None got interpreted as False")
The result is:
None got interpreted as False
When a function does not return any value, it returns None:
def some_func():print("Hi") var=some_func()print(var)
The result is:


Hi NoneView Code
ages={"Dave":24,"Mary":42,"John":58}print(ages["Dave"])print(ages["Mary"])The result is:


24 42View Code
bad_dict={ [1,2,3]:"one two three"}The result is:


TypeError: unhashable type: 'list'View Code
squares={1:1,2:4,3:"error",4:16} squares[8]=64squares[3]=9print(squares)The result is:


{1: 1, 2: 4, 3: 9, 4: 16, 8: 64}View Code
nums={1:"one",2:"two",3:"three"}print(1 in nums)print("three"in nums)print(4 not in nums)The result is:


True False TrueView Code
paris={1:"apple","orange":[2,3,4], True:False, None:"True"}print(paris.get("orange"))print(paris.get(7))print(paris.get(12345,"not in dictionary"))get The second parameter means that if the keyword cannot be found, this value will be returned. The result is:

paris={1:"apple","orange":[2,3,4], True:False, None:"True"}print(paris.get("orange"))print(paris.get(7))print(paris.get(12345,"not in the dicrionary"))

Tuples are very similar to lists, but they cannot be changed. You can create a new tuple with parentheses, or without...:
words=("spam","eggs","sausages",)
words="spam","eggs","sausages",
空元组用()新建。
元组的运行速度比列表快
其他使用方法和列表类似。
列表切片(List Slices)
列表切片是一种检索列表值的高级方法。基本的切片方法是用两个被冒号分开的整数来索引列表。这样可以从旧列表返回一个新列表。
squares=[0,1,4,9,16,25,36,49,64,81]print(squares[2:6])print(squares[3:8])print(squares[0:1])
结果是:


[4, 9, 16, 25] [9, 16, 25, 36, 49] [0]
跟range的参数相似,第一的下标的值会包括,但不包括第二个下标的值。
如果第一个下标省略,默认从头开始,
如果第二个下标省略,默认到结尾结束。
切片同样可以用于元组。
切片也有第三个参数,决定了步长。第一二个分别决定了开头与结尾。
squares=[0,1,4,9,16,25,36,49,64,81] print(squares[:6:2]) print(squares[3::3]) print(squares[::3])
结果是:
[0, 4, 16] [9, 36, 81] [0, 9, 36, 81]
参数是复数的话就倒着走。-1是倒数第一,-2是倒数第二,第三个参数为负就会倒着切,这时候第一个参数和第二个参数就要倒着看了,也就是第二个参数变成了开始,第一个变成了结尾(因此-1会使整个列表倒序)
squares=[0,1,4,9,16,25,36,49,64,81]print(squares[:-1])print(squares[::-3])print(squares[-3::2])
结果是:


[0, 1, 4, 9, 16, 25, 36, 49, 64] [81, 36, 9, 0] [49, 81]
列表解析(List Comprehensions)
这是一种快速创建遵循某些规则的列表的方法:
cubes=[i**3 for i in range(5)]print(cubes)
结果是:


[0, 1, 8, 27, 64]
也可以包含if statement 加强限定条件。
evens=[i**2 for i in range(10) if i**2 % 2==0]print(evens)
结果是:


[0, 4, 16, 36, 64]
evens=[i**2 for i in range(10) if i**2 % 2==0]print(evens)
结果是:


[0, 4, 16, 36, 64]
range的范围过大会超出内存的容量引发MemoryError
String Formatting
为了使string和non-string结合,可以把non-string转化为string然后再连起来。
string formatting提供了一种方式,把non-string嵌入到string里,用string的format method来替换string里的参数。
nums=[4,5,6] msg="Numbers:{0} {1} {2}".format(nums[0],nums[1],nums[2])print(msg)
format里的参数和{}里的参数是对应的。{}的参数是format()里参数的下标
参数被命名这种情况也是可以的:
a="{x},{y}".format(x=5,y=12)print(a)
结果是:


5,12
Useful Functions
Python 内置了许多有用的函数
join ,用一个string充当分隔符把一个由string组成的列表连起来。
print(",".join(["spam","eggs","ham"]))
结果是:


spam,eggs,ham
replace,用一个string 取代另一个。
print("Hello ME".replace("ME","world"))
结果是:


Hello world
startwith和endwith,判断是否是由……开头或结束:
print("This is a sentence.".startswith("This"))print("This is a sentence.".endswith("sentence."))
结果是:


True True
lower和upper可以改变string的大小写
print("This is A sentence.".upper())print("THIS IS a SENTENCE..".lower())
结果是:


THIS IS A SENTENCE. this is a sentence.
split的作用于join 相反,他可以按某个string为分隔符将一串string分开并成为列表的形式。
print("apple,eggs,banana".split(","))
结果是:
['apple', 'eggs', 'banana']
有关数学的一些函数有:最大值max,最小值min,绝对值abs,约等数round(第二个参数可以决定保留几位小数),对列表里的数求和用sum等:
print(min(1,2,3,4,5,6,7))print(max(1,2,3,4,5,6,7))print(abs(-98))print(round(78.632453434,4))print(sum([2.12121,23232323]))
结果是:


1 7 98 78.6325 23232325.12121
all和any可以把列表当成参数,然后返回True或 False,
nums=[55,44,33,22,11]if all([i
nums=[55,44,33,22,11]if any([i
all和any的区别是,all需要所有的值都满足,any只需要有一个满足就行了。
枚举(enumerate),字面意思,把列表中的值按顺序一个一个列出来。
nums=[55,44,33,22,11]for v in enumerate(nums):print(v)
结果是:


(0, 55) (1, 44) (2, 33) (3, 22) (4, 11)
The above is the detailed content of Detailed introduction to python types (type). For more information, please follow other related articles on the PHP Chinese website!

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.

Python and C have significant differences in memory management and control. 1. Python uses automatic memory management, based on reference counting and garbage collection, simplifying the work of programmers. 2.C requires manual management of memory, providing more control but increasing complexity and error risk. Which language to choose should be based on project requirements and team technology stack.

Python's applications in scientific computing include data analysis, machine learning, numerical simulation and visualization. 1.Numpy provides efficient multi-dimensional arrays and mathematical functions. 2. SciPy extends Numpy functionality and provides optimization and linear algebra tools. 3. Pandas is used for data processing and analysis. 4.Matplotlib is used to generate various graphs and visual results.

Whether to choose Python or C depends on project requirements: 1) Python is suitable for rapid development, data science, and scripting because of its concise syntax and rich libraries; 2) C is suitable for scenarios that require high performance and underlying control, such as system programming and game development, because of its compilation and manual memory management.

Python is widely used in data science and machine learning, mainly relying on its simplicity and a powerful library ecosystem. 1) Pandas is used for data processing and analysis, 2) Numpy provides efficient numerical calculations, and 3) Scikit-learn is used for machine learning model construction and optimization, these libraries make Python an ideal tool for data science and machine learning.

Is it enough to learn Python for two hours a day? It depends on your goals and learning methods. 1) Develop a clear learning plan, 2) Select appropriate learning resources and methods, 3) Practice and review and consolidate hands-on practice and review and consolidate, and you can gradually master the basic knowledge and advanced functions of Python during this period.

Key applications of Python in web development include the use of Django and Flask frameworks, API development, data analysis and visualization, machine learning and AI, and performance optimization. 1. Django and Flask framework: Django is suitable for rapid development of complex applications, and Flask is suitable for small or highly customized projects. 2. API development: Use Flask or DjangoRESTFramework to build RESTfulAPI. 3. Data analysis and visualization: Use Python to process data and display it through the web interface. 4. Machine Learning and AI: Python is used to build intelligent web applications. 5. Performance optimization: optimized through asynchronous programming, caching and code

Python is better than C in development efficiency, but C is higher in execution performance. 1. Python's concise syntax and rich libraries improve development efficiency. 2.C's compilation-type characteristics and hardware control improve execution performance. When making a choice, you need to weigh the development speed and execution efficiency based on project needs.


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

MantisBT
Mantis is an easy-to-deploy web-based defect tracking tool designed to aid in product defect tracking. It requires PHP, MySQL and a web server. Check out our demo and hosting services.

VSCode Windows 64-bit Download
A free and powerful IDE editor launched by Microsoft

SublimeText3 Linux new version
SublimeText3 Linux latest version

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

Dreamweaver CS6
Visual web development tools