Python入门

Python入门

退将复修吾初服。

变量与数据类型

变量

Python中没有声明变量的命令,变量都是赋值时创建的,甚至可以在设置后更改其类型,可在一行中为多个变量赋值。

示例

x = 5 # x is of type int
x = "Steve" # x is now of type str
print(x)
x, y, z = "Orange", "Banana", "Cherry"
print(x)
print(y)
print(z)

字符串变量可以使用单双引号进行声明。

示例

x = "Bill"
# is the same as
x = 'Bill'
输出变量

Python中的print语句用来输出变量,如果需要结合文本和变量,Python中使用+字符。

示例

x = "awesome"
print("Python is " + x)
x = "Python is "
y = "awesome"
z =  x + y
print(z)

对于数字,+用于数学运算。

示例

x = 5
y = 10
print(x + y)

当组合字符串和数字时,Python会给出错误。1

全局变量

在函数外部创建的变量(如上述所有示例所示)称为全局变量。

全局变量可以被函数内部和外部的每个人使用。(示例1)

如果在函数内部创建具有相同名称的变量,则该变量将是局部变量,并且只能在函数内部使用。具有相同名称的全局变量将保留原样,并拥有原始值。(示例2)

要在函数内部创建全局变量,可以使用 global 关键字。如果要在函数内部更改全局变量的值,请使用global关键字引用该变量。(示例3)

示例1

x = "awesome"

def myfunc():
  print("Python is " + x)

myfunc()
# Python is awesome

示例2

x = "awesome"

def myfunc():
  x = "fantastic"
  print("Python is " + x)
# Python is fantastic
myfunc()

print("Python is " + x)
# Python is awesome

示例3

x = "awesome"
def myfunc():
  global x
  x = "fantastic"

myfunc()

print("Python is " + x)
# Python is fantastic

数据类型

Python常见文本类型如下:2

文本类型:str
数值类型:int, float, complex
序列类型:list, tuple, range
映射类型:dict
集合类型:set, frozenset
布尔类型:bool
二进制类型:bytes, bytearray, memoryview

可以用type()函数获取对象的数据类型。

可以用下面的方法为变量指定类型。

x = str(“Hello World”)str
x = int(29)int
x = float(29.5)float
x = complex(1j)complex
x = list((“apple”, “banana”, “cherry”))list
x = tuple((“apple”, “banana”, “cherry”))tuple
x = range(6)range
x = dict(name=“Bill”, age=36)dict
x = set((“apple”, “banana”, “cherry”))set
x = frozenset((“apple”, “banana”, “cherry”))frozenset
x = bool(5)bool
x = bytes(5)bytes
x = bytearray(5)bytearray
x = memoryview(bytes(5))memoryview

缩进与注释

缩进

示例

if 5 > 2:
	print("Five!")

缩进指的是代码行开头的空格,Python中缩进不能省略,空格数取决于程序员,但至少需要一个。

必须在同一代码块中使用同样数量的空格,否则Python会出错。

错误示例

if 5 > 2:
 print("Five is greater than two!") 
        print("Five is greater than two!")

注释

实际上,Python没有多行注释的语法。

由于 Python 将忽略未分配给变量的字符串文字,因此您可以在代码中添加多行字符串(三引号),并在其中添加注释。

只要字符串没有分配给变量,Python就会忽略它们,这样就完成了注释。

# 进行单行注释
"""
多
行
注
释
"""

数字

Python数字类型

Python中有三种数字类型:

  • int

  • float

  • complex

int

Python中的int长度不限。

float

e表示10 的幂,不区分大小写。

complex

复数用"j"作为虚部编写。

示例

x = 2+3j
y = 7j
z = -7j

类型转换

示例

x = 10 # int
y = 6.3 # float
z = 1j # complex

# 把整数转换为浮点数

a = float(x)

# 把浮点数转换为整数

b = int(y)

# 把整数转换为复数

c = complex(x)

print(a)
print(b)
print(c)

print(type(a))
print(type(b))
print(type(c))

随机数

Python没有random()函数,但有一个一个名为 random 的内置模块,可用于生成随机数:

示例

import random

print(random.randrange(1,10))

Casting

Python 是一门面向对象的语言,因此它使用类来定义数据类型,包括其原始类型。

使用构造函数完成在 Python 中的转换:

  • int() - 用整数字面量或浮点字面量构造整数(通过对数进行下舍入),或者用表示完整数字的字符串字面量
  • float() - 用整数字面量、浮点字面量,或字符串字面量构造浮点数(提供表示浮点数或整数的字符串)
  • str() - 用各种数据类型构造字符串,包括字符串,整数字面量和浮点字面量

示例

# 整数
x = int(1)   # x 将是 1
y = int(2.5) # y 将是 2
z = int("3") # z 将是 3
#浮点数
x = float(1)     # x 将是 1.0
y = float(2.5)   # y 将是 2.5
z = float("3")   # z 将是 3.0
w = float("4.6") # w 将是 4.6
#字符串
x = str("S2") # x 将是 'S2'
y = str(3)    # y 将是 '3'
z = str(4.0)  # z 将是 '4.0'

布尔

布尔表示True或False两值之一。

bool()函数可以评估任何值:

除空字符串外,任何字符串均为 True。

除 0 外,任何数字均为 True。

除空列表外,任何列表、元组、集合和字典均为 True。

示例

下列布尔函数会返回False。

bool(False)
bool(None)
bool(0)
bool("")
bool(())
bool([])
bool({})

运算符

Python中通过**实现幂运算,通过//实现地板除。

其余内容与C几乎相同。

字符串

在Python中 'hello'等同于 "hello"

多行字符串

可以用三个引号将多行字符串赋值给变量。

a = """The Zen of Python, by Tim Peters   
Beautiful is better than ugly.     
Explicit is better than implicit.  
Simple is better than complex.     
Complex is better than complicated.
Flat is better than nested.        
Sparse is better than dense.
Readability counts.
Special cases aren't special enough to break the rules.
Although practicality beats purity.
Errors should never pass silently.
Unless explicitly silenced.
In the face of ambiguity, refuse the temptation to guess.
There should be one-- and preferably only one --obvious way to do it.
Although that way may not be obvious at first unless you're Dutch.
Now is better than never.
Although never is often better than *right* now.
If the implementation is hard to explain, it's a bad idea.
If the implementation is easy to explain, it may be a good idea.
Namespaces are one honking great idea -- let's do more of those!"""
print(a)

字符串数组

Python 中的字符串是表示 Unicode 字符的字节数组(从0开始)。Python 没有字符数据类型,单个字符就是长度为 1 的字符串。

Python中用方括号访问字符串的元素。

示例

a = "Hello, World!"
print(a[1])
b = "Hello, World!"
print(b[2:5])
负索引

从字符串末尾开始计数进行切片。

示例

b = "Hello, World!"
print(b[-5:-2])
# orl
字符串长度

len()函数获取字符串的长度

示例

a = "Hello, World!"
print(len(a))

字符串方法

所有的字符串方法都返回新值而不更改原字符串。

以下是几个常用的字符串方法。

strip( )

删除开头和结尾的空白字符

示例

a = " Hello, World! "
print(a.strip()) 
# 返回"Hello, World!"
lower( )

返回小写的字符串。

示例

a = "Hello, World!"
print(a.lower())
upper( )

返回大写的字符串。

示例

a = "Hello, World!"
print(a.upper())
replace( )

用另一段字符串来替换字符串。

示例

a = "Hello, World!"
print(a.replace("World", "Kitty"))
split( )

在找到分隔符的实例时将字符串拆分为子字符串。

类似C中的strtok()函数。

示例

a = "Hello, World!"
print(a.split(",")) 
# 返回['Hello', ' World!']

字符串检查

可以使用in或者not in关键字进行字符串检查,返回值为布尔类型。

示例

# 检查以下文本中是否存在短语 "ina"
txt = "China is a great country"
x = "ina" in txt
print(x)

# 检查以下文本中是否没有短语 "ina"
txt = "China is a great country"
x = "ain" not in txt
print(x) 

字符串串联

可以使用+运算符将两个字符串串联

示例

a = "Hello"
b = "World"
c = a + " " + b
print(c)
# Hello World

字符串格式

可以使用format()方法组合字符串和数字。

这个方法接受传递参数后将其进行格式化,并将它们放在占位符 {} 所在的字符串中。

{}类似C中的%d、%f、%c、%s

示例

age = 63
txt = "My name is Bill, and I am {}"
print(txt.format(age))
# My name is Bill, and I am 63

quantity = 3
itemno = 567
price = 49.95
myorder = "I want {} pieces of item {} for {} dollars."
print(myorder.format(quantity, itemno, price))
# I want 5 pieces of item 789 for 24.36 dollars.

可以通过索引号来确保参数放入正确占位符中。

示例

quantity = 3
itemno = 567
price = 49.95
myorder = "I want to pay {2} dollars for {0} pieces of item {1}."
print(myorder.format(quantity, itemno, price))
# I want to pay 24.36 dollars for 5 pieces of item 789.

集合

集合数据类型

Python中有四种集合数据类型:

  • **列表(List)**是一种有序和可更改的集合。允许重复的成员。
  • **元组(Tuple)**是一种有序且不可更改的集合。允许重复的成员。
  • **集合(Set)**是一个无序和无索引的集合。没有重复的成员。
  • **词典(Dictionary)**是一个无序,可变和有索引的集合。没有重复的成员。

列表List

列表是一个有序且可更改的集合。在 Python 中,列表用方括号编写。

类似STL中的vector。

示例

thislist = ["apple", "banana", "cherry"]
print(thislist)
# ['apple', 'banana', 'cherry']
访问项目

可以通过索引号来访问列表项。

示例

thislist = ["apple", "banana", "cherry"]
print(thislist[1])
# banana

thislist = ["apple", "banana", "cherry"]
print(thislist[-1])
# cherry

可以通过指定范围的起点和终点来指定索引范围。

将包括开始索引,但不包括结束索引。

示例

thislist = ["apple", "banana", "cherry", "orange", "kiwi", "melon", "mango"]
print(thislist[2:5])
# ['cherry', 'orange', 'kiwi']

thislist = ["apple", "banana", "cherry", "orange", "kiwi", "melon", "mango"]
print(thislist[-4:-1])
# ['orange', 'kiwi', 'melon']
更改项目值

可以引用索引号来更改项目值。

示例

thislist = ["apple", "banana", "cherry"]
thislist[1] = "mango"
print(thislist)
# ['apple', 'mango', 'cherry']
遍历列表

可以使用for循环来遍历列表项。

示例

thislist = ["apple", "banana", "cherry"]
for x in thislist:
  print(x)
# apple
# banana
# cherry
检查项目是否存在

可以使用in关键字确定项目是否存在

示例

thislist = ["apple", "banana", "cherry"]
if "apple" in thislist:
  print("Yes, 'apple' is in the fruits list")
# Yes, 'apple' is in the fruits list
列表长度

可以使用len()方法确定列表中有多少项。

示例

thislist = ["apple", "banana", "cherry"]
print(len(thislist))
# 3
添加项目

可以使用append()方法将项目添加到列表末尾。

示例

thislist = ["apple", "banana", "cherry"]
thislist.append("orange")
print(thislist)
# ['apple', 'banana', 'cherry', 'orange']
删除项目

remove()方法删除指定的项目

pop()方法删除指定的索引(如果未指定索引,则删除最后一项)

del关键字删除指定的索引

del关键字也能完整地删除列表

clear()方法清空列表

thislist = ["apple", "banana", "cherry"]
thislist.remove("banana")
thislist.pop()
del thislist[0]
del thislist
thislist.clear()# []
复制列表

通过list2 = list1来复制列表时,前者将只是对后者的引用,更改将同步进行。

copy()list()方法复制列表

thislist = ["apple", "banana", "cherry"]
mylist = thislist.copy()
mylist = list(thislist)
合并列表

最简单的方法是使用 + 运算符。

示例

list1 = ["a", "b" , "c"]
list2 = [1, 2, 3]

list3 = list1 + list2
print(list3)
# ['a', 'b', 'c', 1, 2, 3]

使用extend()方法将list2添加到list1的末尾。

示例

list1 = ["a", "b" , "c"]
list2 = [1, 2, 3]

list1.extend(list2)
print(list1)
# ['a', 'b', 'c', 1, 2, 3]

元组Tuple

元组是有序且不可更改的集合。在Python中,元组用圆括号编写。

元组的创建、访问、遍历、检查项目是否存在、长度、合并与列表相似。

更改元组值

通过元组->列表->元组的转换实现。

示例

x = ("apple", "banana", "cherry")
y = list(x)
y[1] = "kiwi"
x = tuple(y)
创建一个项目的元组

必须在项目后添加逗号,否则Python无法识别。

示例

thistuple = ("apple",)
print(type(thistuple))
# <class 'tuple'>

thistuple = ("apple")
print(type(thistuple))
# <class 'str'>

集合Set

集合指无序和无索引的集合。在Python中,集合用花括号编写。

集合的长度与列表相同。

访问项目

由于set无序,故不能引用索引来访问set中的项目。

示例

thisset = {"apple", "banana", "cherry"}

for x in thisset:
  print(x)

print("banana" in thisset)
# True
添加项目

集合一旦创建就无法更改项目。

add()方法添加一个项目。

update()方法添加多个项目。

示例

thisset = {"apple", "banana", "cherry"}

thisset.add("orange")
thisset.update(["orange", "mango", "grapes"])
删除项目

remove()方法在删除项目不存在时将引发错误。

discard()方法在项目不存在时不会引发错误。

pop()方法删除最后一项(不知道具体哪项),方法返回值为被删除的项目。

clear()方法清空集合

del关键字删除集合

合并集合

union()方法返回一个新集合。

update()方法将set2中项目插入set1中。

示例

set1 = {"a", "b" , "c"}
set2 = {1, 2, 3}

set3 = set1.union(set2)
set1.update(set2)

字典dictionary

字典是一个无序、可变和有索引的集合。在 Python 中,字典用花括号编写,拥有键和值。

检查键是否存在、字典长度、复制字典与列表相同。

示例

thisdict =	{
  "brand": "Porsche",
  "model": "911",
  "year": 1963
}
print(thisdict)
# {'brand': 'Porsche', 'model': '911', 'year': 1963}
访问项目

可以通过方括号内引用键名来访问字典中的项目。

get()方法可以得到相同结果。

示例

x = thisdict["model"]
x = thisdict.get("model")
更改项目值

可以通过引用键名更改特定项目值

示例

thisdict =	{
  "brand": "Porsche",
  "model": "911",
  "year": 1963
}
thisdict["year"] = 2022
遍历字典

循环遍历字典时,返回值是字典的键。

values()函数返回字典的值。

items()函数遍历键和值。

示例

for x in thisdict:
  print(x)# 键

for x in thisdict:
  print(thisdict[x])# 值
  
for x in thisdict.values():
  print(x)# 值  

for x, y in thisdict.items():
  print(x, y)# 键和值
添加项目

示例

thisdict =	{
  "brand": "Porsche",
  "model": "911",
  "year": 1963
}
thisdict["color"] = "red"
print(thisdict)
删除项目

pop()方法删除指定键名的项目。

popitem()方法删除最后插入的项目。

del关键字删除指定键名项目或整个字典。

clear()关键字清空字典。

嵌套字典

示例

child1 = {
  "name" : "Phoebe Adele",
  "year" : 2002
}
child2 = {
  "name" : "Jennifer Katharine",
  "year" : 1996
}
child3 = {
  "name" : "Rory John",
  "year" : 1999
}

myfamily = {
  "child1" : child1,
  "child2" : child2,
  "child3" : child3
}

分支语句

Python支持来自数学的常用逻辑条件。

Python依赖缩进,同一代码块(C中一个{}中的内容)缩进必须一致。

Python中and or 等逻辑运算符等价于&|

if语句

示例

a = 66
b = 200
if b > a:
  print("b is greater than a")
# b is greater than a

如果只有一条语句要执行,可以将其与if放在同一行。

示例

if a > b: print("a is greater than b")

elif语句

示例

a = 66
b = 66
if b > a:
  print("b is greater than a")
elif a == b:
  print("a and b are equal")

else语句

示例

a = 200
b = 66
if b > a:
  print("b is greater than a")
elif a == b:
  print("a and b are equal")
else:
  print("a is greater than b")

如果有两条语句要执行,一条用于 if,另一条用于 else,则可以将它们全部放在同一行。

示例

print("A") if a > b else print("B")

print("A") if a > b else print("=") if a == b else print("B")

pass语句

可以使用pass语句来避免Python中if语句不能为空的错误。

示例

a = 66
b = 200

if b > a:
  pass

循环语句

while循环

while循环的break、continue语句与C基本相同。

else语句

通过使用 else 语句,当条件不再成立时,我们可以运行一次代码块。注意缩进。

示例

i = 1
while i < 6:
  print(i)
  i += 1
else:
  print("i is no longer less than 6")
# 1
# 2
# 3
# 4
# 5
# i is no longer less than 6

for循环

for循环用于列表、元组、字典、集合或字符串。

Python中的for循环不需要预先设置索隐变量。

for循环的break、continue语句与C基本相同。

循环遍历字符串

示例

for x in "banana":
  print(x)
# b
# a
# n
# a
# n
# a
range()函数

range()函数返回一个数字序列,默认从0开始,每次递增1,以指定数字结束。

range(10)->for(int i = 0;i<10;i++)

range(a,b,c)中a为起始值,b为结束值,c为增量值。

示例

for x in range(3, 50, 6):
  print(x)
# 3
# 9
# 15
# 21
# 27
# 33
# 39
# 45
else语句

示例

for x in range(3):
  print(x)
else:
  print("Finally finished!")
# 0
# 1
# 2
# Finally finished!
pass语句

示例

for x in [0, 1, 2]:
  pass

函数

创建函数

def关键字用于定义函数。

pass语句用于跳过无内容函数。

示例

def my_function():
  print("Hello from a function")
my_function()

参数

默认参数值

对于没有调用参数的函数,使用默认值。

示例

def my_function(country = "China"):
  print("I am from " + country)

my_function("Sweden")
my_function("India")
my_function()
my_function("Brazil")
传参的数据类型

发送的参数可以是任何数据类型,并且在函数内被视为相同数据类型。

将list作为参数发送,则它在函数中仍是list。

示例

def my_function(food):
  for x in food:
    print(x)

fruits = ["apple", "banana", "cherry"]

my_function(fruits)
关键字参数

示例

def my_function(child3, child2, child1):
  print("The youngest child is " + child3)

my_function(child1 = "Phoebe", child2 = "Jennifer", child3 = "Rory")
任意参数

示例

def my_function(*kids):
  print("The youngest child is " + kids[2])

my_function("Phoebe", "Jennifer", "Rory")

返回值

return语句使函数返回值。

递归

示例

def tri_recursion(k):
  if(k>0):
    result = k+tri_recursion(k-1)
    print(result)
  else:
    result = 0
  return result

print("\n\nRecursion Example Results")
tri_recursion(6)

文件IO3

打印到屏幕

print语句将传递的表达式传换成字符串,并将结果写到标准输出。

读取键盘输入

input语句从标准输入读取一行(去掉结尾换行符),并返回一个字符串。

input语句也可以接收一个Python表达式作为输入,并返回运算结果。

示例

str = input("请输入:")
print "你输入的内容是: ", str

# 请输入:[x*5 for x in range(2,10,2)]
# 你输入的内容是:  [10, 20, 30, 40]

打开和关闭文件

open()函数打开一个文件,创建file对象,之后用相关方法调用进行读写。

"r"只读、"w"写入,缓冲区buffering默认为0。

file对象的属性见下表。

属性描述
file.closed返回true如果文件已被关闭,否则返回false。
file.mode返回被打开文件的访问模式。
file.name返回文件的名称。
file.softspace如果用print输出后,必须跟一个空格符,则返回false。否则返回true。

示例

fo = open("foo.txt", "w")
print "文件名: ", fo.name
print "是否已关闭 : ", fo.closed
print "访问模式 : ", fo.mode
print "末尾是否强制加空格 : ", fo.softspace

# 文件名:  foo.txt
# 是否已关闭 :  False
# 访问模式 :  w
# 末尾是否强制加空格 :  0

close()方法用于关闭文件。

文件读写

read()方法从一个打开的文件中读取一个字符串。

count从已打开文件中读取的字节计数。该方法从文件的开头开始读入,如果没有传入count,它会尝试尽可能多地读取内容,很可能是直到文件的末尾。

write()方法可以将字符串写入打开的文件。

示例

fileObject.read([count])

fileObject.write(string)



  1. 可以用format()方法实现字符串和数字的组合。 ↩︎

  2. 以下列表均来源于W3school ↩︎

  3. 主要参考 ↩︎

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值