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

python快速入门(Python快速入门第二版黑马程序员电子书)

cac55 2024-10-11 10:52 15 浏览 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!"

?

相关推荐

苹果新macOS、新Mac还没出,但已经有新版虚拟机软件Parallels Desktop 19

自从苹果电脑全面转向ARM架构芯片之后,想在新款Mac电脑上安装Windows或Linux系统,就只能依靠虚拟机软件了,其中ParallelsDesktop应该是比较多Mac用户选择使用的一款,现在...

这个开源神器可快速帮你安装 MacOS 虚拟机

大家好,我是JackTian。安装Windows和Linux操作系统是最熟悉不过的必备技能了。那么,给大家推荐一个非常实用的开源脚本:macos-guest-virtualbox.sh,帮你...

如何在VMware虚拟机上安装运行Mac OS系统??

想在自己的Windows电脑上安装一个MacOS体验一下苹果系统的小伙伴,教程来了!!!一、安装前准备虚拟机运行软件:VMwareWorkstationPro,版本:16.0.0。(可以注册)VM...

效率!MacOS下超级好用的Linux虚拟工具:Lima

对于MacOS用户来说,搭建Linux虚拟环境一直是件让人头疼的事。无论是VirtualBox还是商业的VMware,都显得过于笨重且配置复杂。今天,我们要介绍一个轻巧方便的纯命令行Linux虚拟工具...

普通电脑安装苹果MacOS+Windows10双系统,这次可不是虚拟机

上篇文章中说到,有一朋友因为工作需要,得临时使用苹果系统,笔者给他用VmwareWorkStation安装了一个苹果系统的虚拟机,结果装是装上了,但是发现调整分辨率有点小问题,文件传输也不方便。虽说...

官方证实苹果M1芯片不支持Windows 11

中关村在线消息:近日根据微软官方透露,目前已经确定Windows11不支持运行在苹果M1芯片上,这意味着过往在Mac电脑上安装Windows系统的做法在M1芯片的Mac电脑上并不适用。不过此前有网友...

这可能是 Mac 共享文件最详细的教程了

如果希望让一台Mac访问另一台Mac上的文件,就可以使用Mac的文件共享功能。而且不仅是Mac之间,甚至用iPhone、iPad、WindowsPC都可以访问Mac的共享文件...

在 M1/M2 Mac 上,让 Windows 11 免费“跑”起来

自从苹果在产品中逐步使用自研的M系列芯片淘汰掉英特尔芯片之后,很多事情都发生了改变。作者|KirkMcElhearn和JoshuaLong译者|弯月出品|CSDN(ID:CS...

VMware Workstation克隆虚拟机后修改ip地址和mac地址

VMwareWorkstation克隆虚拟机,登录之后发现,克隆虚拟机不仅用户名相同,连ip地址、mac地址也是相同的,很显然访问相同ip地址的虚拟机是会出现ip地址冲突的。一、修改IP地址这就需要...

VirtualBox7中安装macOS big sur,在windows10&amp;11上「保姆级教程」

macOSBigSur是苹果公司研发的桌面端操作系统,于北京时间2020年6月23日在2020苹果全球开发者大会上发布。BigSur采用全新的精美设计,为主要app如Safari浏览器...

最强mac虚拟机Parallels Desktop 16 有哪些重要的新增功能?

ParallelsDesktop16正式发布,软件带来了一些显着的新功能和性能增强,包括对macOSBigSur的全面支持。当苹果推出macOSBigSur时,它终止了对Par...

关于在MacOS安装虚拟机的全过程(macos 安装虚拟机)

哈喽大家好,我是咕噜美乐蒂,很高兴又见面啦!下面美乐蒂将详细地给大家介绍一下在macOS上使用VMwareFusion创建虚拟机并安装操作系统的步骤:一、确认虚拟化支持:首先,确认你的Ma...

macOS上也能轻松运行Win系统的虚拟机,你还不知道吗?

在macOS系统上运行Win系统的方式,虚拟机篇吉安光头强原创你是否曾经为了在Mac上运行Windows系统而烦恼不用着急,下面我将分享一种简单易行的方法,让你轻松在Mac上运行Windows系统准备...

Mac M芯片上安装统信UOS 1070arm64虚拟机

原文链接:MacM芯片上安装统信UOS1070arm64虚拟机Hello,大家好啊!今天给大家带来一篇关于如何在苹果M系列芯片的Mac电脑上,通过VMware安装ARM64版统信UOS1070...

虚拟机不好用?Mac mini 多配一台Windows电脑,用远程桌面更好!

最近新入手了MacminiM4款,这里来更新一下相关问题,对于还没有购买Macmini,但是又想要用苹果电脑的朋友,一些参考,我觉得还是挺有用的!Macmini选择哪个渠道购买好?现在比较划算...

取消回复欢迎 发表评论: