百度360必应搜狗淘宝本站头条
当前位置:网站首页 > 技术资源 > 正文

python快速入门(Python快速入门第三版 中文PDF)

off999 2024-10-04 18:51 23 浏览 0 评论

python 快速入门

python简介

Python 是一个高层次的结合了解释性、编译性、互动性和面向对象的脚本语言。

  1. Python 是一种解释型语言: 这意味着开发过程中没有了编译这个环节。类似于PHP和Perl语言。
  2. Python 是交互式语言: 这意味着,您可以在一个 Python 提示符 >>> 后直接执行代码。
  3. Python 是面向对象语言: 这意味着Python支持面向对象的风格或代码封装在对象的编程技术。

python版本

python目前支持两个大的版本Python, 2.7 and 3.5. 令人疑惑的是python的2和3的版本不兼容,因此使用2的版本的代码在3中可能会出现不兼容的现象,目前推荐使用python 3+的版本作为开放和学习。

基本的数据类型

像大多数语言一样,Python具有许多基本类型,包括整数,浮点数,布尔值和字符串。这些数据类型以其他编程语言所熟悉的方式运行。
数值:
整数和浮点数可以像其他语言一样使用:

x = 3
print(type(x)) # Prints "<class 'int'>"
print(x)       # Prints "3"
print(x + 1)   # Addition; prints "4"
print(x - 1)   # Subtraction; prints "2"
print(x * 2)   # Multiplication; prints "6"
print(x ** 2)  # Exponentiation; prints "9"
x += 1
print(x)  # Prints "4"
x *= 2
print(x)  # Prints "8"
y = 2.5
print(type(y)) # Prints "<class 'float'>"
print(y, y + 1, y * 2, y ** 2) # Prints "2.5 3.5 5.0 6.25"

python不像其他编程语言,其不支持x++和x—这种操作。
布尔值:
不同于其他编程语言,python使用英文代替(||, &&等):

t = True
f = False
print(type(t)) # Prints "<class 'bool'>"
print(t and f) # Logical AND; prints "False"   与
print(t or f)  # Logical OR; prints "True"     或
print(not t)   # Logical NOT; prints "False"   非
print(t != f)  # Logical XOR; prints "True"

字符串
python对字符串的支持是很强大的:

hello = 'hello'    # 单引号
world = "world"    # 双引号也可
print(hello)       # Prints "hello"
print(len(hello))  # String length; prints "5"
hw = hello + ' ' + world  # String concatenation
print(hw)  # prints "hello world"
hw12 = '%s %s %d' % (hello, world, 12)  # sprintf style string formatting
print(hw12)  # prints "hello world 12"

容器

Python包含几种内置的容器类型: lists, dictionaries, sets和tuples.

Lists

列表与数组的Python等效,但可调整大小,并且可以包含不同类型的元素:

xs = [3, 1, 2]    # Create a list
print(xs, xs[2])  # Prints "[3, 1, 2] 2"
print(xs[-1])     # Negative indices count from the end of the list; prints "2"
xs[2] = 'foo'     # Lists can contain elements of different types
print(xs)         # Prints "[3, 1, 'foo']"
xs.append('bar')  # Add a new element to the end of the list
print(xs)         # Prints "[3, 1, 'foo', 'bar']"
x = xs.pop()      # Remove and return the last element of the list
print(x, xs)      # Prints "bar [3, 1, 'foo']"

切片: 除了一次访问一个列表元素,Python还提供了简洁的语法来访问子列表。这称为切片

nums = list(range(5))     # range is a built-in function that creates a list of integers
print(nums)               # Prints "[0, 1, 2, 3, 4]"
print(nums[2:4])          # Get a slice from index 2 to 4 (exclusive); prints "[2, 3]"
print(nums[2:])           # Get a slice from index 2 to the end; prints "[2, 3, 4]"
print(nums[:2])           # Get a slice from the start to index 2 (exclusive); prints "[0, 1]"
print(nums[:])            # Get a slice of the whole list; prints "[0, 1, 2, 3, 4]"
print(nums[:-1])          # Slice indices can be negative; prints "[0, 1, 2, 3]"
nums[2:4] = [8, 9]        # Assign a new sublist to a slice
print(nums)               # Prints "[0, 1, 8, 9, 4]"

循环:

animals = ['cat', 'dog', 'monkey']
for animal in animals:
    print(animal)

如果要访问循环体内每个元素的索引,请使用内置的枚举函数enumerate:

animals = ['cat', 'dog', 'monkey']
for idx, animal in enumerate(animals):
    print('#%d: %s' % (idx + 1, animal))

列表推导式(List comprehensions):
列表推导式可以将循环这种方式表达的更为简洁,如下所示:

# 构建1-10的列表
l1 = [x for x in range(1,11)]
# 可以对迭代的元素进行操作
l2= [x*x for x in range(1,11)]
# for循环后跟if语句
l3 = [i for i in range(1,11) if i % 2 == 0]
# 嵌套列表合成单个列表 [[1,2],[3,4]] -> [1,2,3,4]
l = [[1,2],[3,4]]
l4 = [j for i in l for j in i]

字典

字典是是无序的键值对(key:value)集合,等同于c++中的unordered_map哈希表。同一个字典内的键必须是互不相同的。
其形式为 :键:值

# 创建字典
d = {'cat': 'cute', 'dog': 'furry'}  
# 获取key值
print(d['cat'])       # Get an entry from a 
# 查询key是不是在字典中
print('cat' in d)     
# 新增key:value
d['fish'] = 'wet'     # Set an entry in a dictionary
print(d['fish'])      # Prints "wet"
# 如果没有key,则报错,所以一般不直接进行取值操作
# print(d['monkey'])  # KeyError: 'monkey' not a key of d
# 使用get获取key值,如果key不存在,则赋予默认值
print(d.get('monkey', 'N/A')) 
# 删除元素
del d['fish']

迭代
迭代字典很简单,和列表差不多:

d = {'person': 2, 'cat': 4, 'spider': 8}
# 注意这种遍历的是key的值
for animal in d:          #key
    legs = d[animal]      #value
    print 'A %s has %d legs' % (animal, legs)
# Prints "A person has 2 legs", "A spider has 8 legs", "A cat has 4 legs"
# 如果想直接获得键值对, 使用iteritems:
d = {'person': 2, 'cat': 4, 'spider': 8}
for animal, legs in d.iteritems():
    print 'A %s has %d legs' % (animal, legs)
# Prints "A person has 2 legs", "A spider has 8 legs", "A cat has 4 legs"

字典的表达式

nums = [0, 1, 2, 3, 4]
even_num_to_square = {x: x ** 2 for x in nums if x % 2 == 0}
print even_num_to_square  # Prints "{0: 0, 2: 4, 4: 16}"

集合

集合,也就是没有顺序的,同时所有的元素都不相同的集合。A set is an unordered collection of distinct elements,用英文更好的表达其含义。集合同样是用花括号创建:

animals = {'cat', 'dog'}
print('cat' in animals)   # Check if an element is in a set; prints "True"
print('fish' in animals)  # prints "False"
animals.add('fish')       # Add an element to a set
print('fish' in animals)  # Prints "True"
print(len(animals))       # Number of elements in a set; prints "3"
animals.add('cat')        # Adding an element that is already in the set does nothing
print(len(animals))       # Prints "3"
animals.remove('cat')     # Remove an element from a set
print(len(animals))       # Prints "2"

集合的循环很列表一致:

animals = {'cat', 'dog', 'fish'}
for idx, animal in enumerate(animals):
    print '#%d: %s' % (idx + 1, animal)
# Prints "#1: fish", "#2: dog", "#3: cat"

元组

元组是(不可变的)有序值列表。元组在很多方面类似于列表。最重要的区别之一是,元组可以用作字典中的键和集合的元素,而列表则不能。这是一个简单的示例:

# 使用括号
t = (5, 6)        # Create a tuple
print(type(t))    # Prints "<class 'tuple'>"

函数

python函数的定义使用def:

def sign(x):
    if x > 0:
        return 'positive'
    elif x < 0:
        return 'negative'
    else:
        return 'zero'
for x in [-1, 0, 1]:
    print(sign(x))
# Prints "negative", "zero", "positive"

类的定义很简单,如下所示的基本结构:

class Greeter(object):
    # 构造函数
    def __init__(self, name):
        self.name = name  # Create an instance variable
    # 方法
    def greet(self, loud=False):
        if loud:
            print('HELLO, %s!' % self.name.upper())
        else:
            print('Hello, %s' % self.name)
g = Greeter('Fred')  # Construct an instance of the Greeter class
g.greet()            # Call an instance method; prints "Hello, Fred"
g.greet(loud=True)   # Call an instance method; prints "HELLO, FRED!"

?

相关推荐

Python设计模式 第 13 章 中介者模式(Mediator Pattern)

在行为型模式中,中介者模式是解决“多对象间网状耦合”问题的核心模式。它就像“机场调度中心”——多个航班(对象)无需直接沟通起飞、降落时间,只需通过调度中心(中介者)协调,避免航班间的冲突与混乱...

1.3.1 python交互式模式的特点和用法

什么是Python交互模式Python交互模式,也叫Python交互式编程,是一种在Python解释器中运行的模式,它允许用户在解释器窗口中输入单个Python语句,并立即查看结果,而不需要编写整个程...

Python设计模式 第 8 章 装饰器模式(Decorator Pattern)

在结构型模式中,装饰器模式是实现“动态功能扩展”的核心模式。它就像“手机壳与手机的关系”——手机(原始对象)具备通话、上网等基础功能,手机壳(装饰器)可在不改变手机本身的前提下,为其新增保护、...

python设计模式 综合应用与实战指南

经过前面16章的学习,我们已系统掌握创建型模式(单例、工厂、建造者、原型)、结构型模式(适配器、桥接、组合、装饰器、外观、享元、代理)、行为型模式(责任链、命令、迭代器、中介者、观察者、状态、策略...

Python入门学习教程:第 16 章 图形用户界面(GUI)编程

16.1什么是GUI编程?图形用户界面(GraphicalUserInterface,简称GUI)是指通过窗口、按钮、菜单、文本框等可视化元素与用户交互的界面。与命令行界面(CLI)相比,...

Python 中 必须掌握的 20 个核心:str()

str()是Python中用于将对象转换为字符串表示的核心函数,它在字符串处理、输出格式化和对象序列化中扮演着关键角色。本文将全面解析str()函数的用法和特性。1.str()函数的基本用法1.1...

Python偏函数实战:用functools.partial减少50%重复代码的技巧

你是不是经常遇到这样的场景:写代码时同一个函数调用了几十次,每次都要重复传递相同的参数?比如处理文件时总要用encoding='utf-8',调用API时固定传Content-Type...

第2节.变量和数据类型【第29课-输出总结】

同学们,关于输出的知识点讲解完成之后,把重点性的知识点做一个总结回顾。·首先对于输出这一章节讲解的比如有格式化符号,格式化符号这里需要同学们额外去多留意的是不是百分号s格式化输出字符串。当然课上也说百...

AI最火语言python之json操作_python json.loads()

JSON(JavaScriptObjectNotation,JavaScript对象表示法)是一种开放标准的文件格式和数据交换格式,它易于人阅读和编写。JSON是一种常用的数据格式,比如对接各种第...

python中必须掌握的20个核心函数—split()详解

split()是Python字符串对象的方法,用于将字符串按照指定的分隔符拆分成列表。它是文本处理中最常用的函数之一。一、split()的基本用法1.1基本语法str.split(sep=None,...

实用方法分享:pdf文件分割方法 横向A3分割成纵向A4

今天在街上打印店给儿子打印试卷时,我在想:能不能,把它分割成A4在家中打印,这样就不需要跑到街上的打印店打印卷子了。原来,老师发的作业,是电子稿,pdf文件,A3格式的试卷。可是家中的打印机只能打印A...

20道常考Python面试题大总结_20道常考python面试题大总结免费

20道常考Python面试题大总结关于Python的面试经验一般来说,面试官会根据求职者在简历中填写的技术及相关细节来出面试题。一位拿了大厂技术岗SpecialOffer的网友分享了他总结的面试经...

Kotlin Data Classes 快速上手_kotlin快速入门

引言在日常开发中,我们常常需要创建一些只用来保存数据的类。问题是,这样的类往往需要写一堆模板化的方法:equals()、hashCode()、toString()……每次都重复,既枯燥又容易出错。//...

python自动化RobotFramework中Collections字典关键字使用(五)

前言介绍安装好robotframework库后,跟之前文章介绍的BuiltIn库一样BuiltIn库使用介绍,在“python安装目录\Lib\site-packages\robot\librarie...

Python中numpy数据分析库知识点总结

Python中numpy数据分析库知识点总结二、对已读取数据的处理②指定一个值,并对该值双边进行修改③指定两个值,并对第一个值的左侧和第二个值的右侧进行修改2.4数组的拼接和行列交换①竖直拼接(np...

取消回复欢迎 发表评论: