详解python基本语法


Python 是一种广泛使用的高级编程语言,以其清晰的语法和代码可读性而闻名。它由 Guido van Rossum 于 1991 年首次发布,并支持多种编程范式,包括面向对象、命令式、功能性和过程式编程。这里介绍一下python的基本语法。

数据

变量

在定义变量的时候Python和C++不同不需要指定变量的类型,是一种弱类型的语言。不过在定义变量名称时仍有一些限制,变量名只能由字母数字和下划线组成,变量名可以由字母或者下划线开头但是不能以数字开头。

Python中用引号括起来的都是字符串,其中的引号既可以是单引号也可以是双引号,引号都成对存在。为了方便操作字符串,python为字符串变量提供了很多方法供大家使用。

title():将字符串的首字母进行大写
upper():将字符串的所有字母转成大写
lower():将字符串的所有字母转成小写
rstrip():暂时剔除字符串末尾的空白
lstrip():暂时剔除字符串头部的空白
strip():剔除字符串两端的空白
str():将数字转成字符串

若想永远移除字符串变量两端的空白,需要在修改后再次赋值调用放法如下:

string1 = string1.rstrip()

数据结构

在python中通过括号类型来区分不同的数据类型,[]对应列表,()对应元组,{}对应字典。下面我们分别对这三种数据类型进行简要介绍。

列表
列表使用[]表示类似于C++中的动态数组vector,下面我们以一个例子对字符串列表进行说明,定义列表bicycles来表示自行车品牌列表:

bicycles = ['feige' , 'giant', 'ongjiu', 'trek']

# 元素之间用逗号来进行分割,元素序号从0开始而不是从1开始,打印第0个元素 
# 列表中最后一个元素的编号为-1倒数第二个编号为-2,剩下的依次类推
print(bicycles[0])

# 修改第0个元素
bicycles[0] = "ofo"

# 追加元素  
 bicycles.append("newBike")

# 特定位插入元素
 bicycles.insert(0,'ducadi')

# 定义空列表
motorcycles = []

# 末尾弹出元素  
bicycles.pop()

# 根据列表索引删除元素
bicycles.pop(index)

# 根据值删除列表中的元素  
bicycles.remove('ducadi')

# 删除第0个元素
# 方法remove只能删除第一个遇到的元素,若是遇到多个则需要循环遍历进行删除
 del bicycles[0]

# 对列表进行永久排序
bicycles.sort()

# 按照字符表的反方向进行排序
bicycles.sort(reverse = True)

# 对列表进行临时排序 
sorted(cars)

# 获取列表长度  
lens(bicycles)

# 永久翻转列表的顺序
bicycles.reverse()  

# 遍历列表
for bicycle in bicycles:
	print(bicycle)

# 列表的一部分称为列表的切片
# 打印列表的前三个 不包含右边界
print(bicycles[0,3]) 
# 打印前四个
bicycles[:4] 
# 从第三个到最后
bicycles[2:] 
# 最后三个元素
bicycles[-3:]

# 遍历切片
for bicycle in bicycles[:3]:
	print(bicycle.title())

# 复制列表
newBicycles = bicycles[:]

# 生成1到4的数字列表
# range函数生成的列表包含左边界不包含右边界
range(1,5)

# 创建1到5的名为numbers的字符列表
numbers = list(range(1,6))

# 创建2到11间隔为2的列表
range(2,11,2)
# 求列表中最大值,最小值,列表的和
max() min() sum()
# 求取1到10数值平方的列表
squares = []
for value in range(1,11)
	squares = value ** 2
	squares.append(square)

元组

元组用()表示,和列表相比元组的特性很明显,列表可以修改而元组不可以修改,虽然不能修改元组的元素,但可以给存储元组的变量从新赋值。相比于列表,元组是更简单的数据结构,如果需要存储一组值在程序的整个生命周期内不变,可以使用元组。其它方法元组的使用方法和列表相同。

字典
python中的字典类似于C++中map存储的是键值对数据。在python中字典数据结构用{}来进行表示。字典是一系列的键值对,每个键都与一个值相关联,可以通过键来访问相对应的值,与键相对应的值可以是数字、字符串、列表乃至字典,事实上可将任何python对象用作字典中的值。

# 用一个字典来表示球员的姓名和得分
player_1 = {'name' : 'xiaoming', 'point' : 23}

# 打印球员姓名和得分
print(player_1['name'])
print(player_1['point'])

# 向字典中添加键值对
player_1["age"] = 33


# 修改键值对
player_1["age"] = 30

# 删除键值对
del player_1["age"]

# 创建一个空字典
player_2 = {}

# 遍历字典
for key, value in player_1.items():
	do something

# 遍历字典中的所有键
for key in player_1.keys():
	do something

# 判断键是否在对应的字典中
if 'name' in player_1.keys() 
if 'name' not in player_1.keys()

# 可以通过sorted()函数来获得特定顺序排列的键列表的副本
favorite_languages = {
	'jen' : 'python',
	'salar' : 'C++',
	'edward' : 'jave',
	'phil' : 'ruby'
}
for name in sorted(favorite_languages.keys()):
	print(name.title() + "thanks you")

# 遍历字典中值
for language in favorite_languages.values():
	print(language.title())

# 通过集合set剔除字典值中的重复项目
for language in set(favorite_languages.values()):
	print(language.title())

# 字典嵌套
alien_0 = {'color' : 'green', 'point':45}
alien_1 = {'color' : 'blue', 'point':40}
alien_2 = {'color' : 'yello', 'point':42}
aliens = [alien_0, alien_1, alien_2]
for alien in aliens:
	print(alien)

# 在字典中存储列表  
favorite_languages = {
	'Jenny' : ['ruby', 'java'],
	'Lily': ['c++', 'python'],
	'phil': ['perl', 'C']
}
for name, languages in favorite_languages.items():
	print(name.title() + "favorite languages are:")
	for language in languages:
		print(language)

# 在字典中存储字典 
users = {
	'Lily' : {
		'first' : 'albert',
		'last' : 'einstein',
		'location' : 'princeton'
		},
	'mcurie' : {
		'first' : 'marie',
		'last' : 'curie',
		'location' : 'paris'
		}
}
for username, uer_info in user.items():
	print("uername" + uername)
	fullname = user_info["first"] + user_info["last"]
	location = user_info["location"]

循环-判断-用户输入

判断

python中进行判断的关键字同样是if,判断条件和C++相同包括: ==、!=、<、<=、>、>=,多个条件同时成立用关键字 and 类似于C++中的 &&

if (age >= 21) and (age <= 35):
	do something

# 多个条件只要一个为真即为真用关键字or类似于C++中的 ||
# 检查特定值是否在列表中用in,判断特定值是否不在列表中用not in
request_toppings = ['mushroom', 'onions', 'pipeline']
if 'mushroom' in reque_t-toppings:
	do something
if 'mushroom' not in request_toppings:
	do something

# if-else语句
if condition1:
	do something
else:
	do something

# 使用多个elif代码块
if condition1:
	do something
elif condition2:
	do something
elif condition3:
	do something
else:
	do something

用户输入

# 1.获取字符串输入
name = input("Please Enter your name")
print("hello" + name + "!")

# 2.获取数值输入
age = input("How old are you")
age = int(age)

# 3.运算符
# + 加法运算 – 减法运算 *乘法运算 /除法运算 ** 乘方运算 %求模运算(余数)

循环

# 用户选择何时退出  
message = ''
while message != 'quit':
	message = input("input string")
	print(message)

# 使用标志
active = True
while active:
	message = input("请输入字符串:")
	if message == "quit":
		active = False
	else:
		print(message)

# 使用break退出
while True:
	city = input("enter the name of your city")
	if city == "quit":
		break;
	else:
		print("my city is" + city.title())

# 使用continue继续循环
current_number = 0
while current_number < 10:
	current_number += 1
	if current_number % 2 == 0:
		continue
	print(current_number)

# while循环处理列表和字典
# for循环中不应该修改列表否则将导致python难以追踪其元素,要在遍历列表同时对其进行修改,可使用while循环

# 列表之间移动元素
unconfirmed_users = ['Alice', 'Jack', 'John']
confirmed_users = []
while unconfirmed_users:
	current_user = unconfirmed_users.pop()
	confirmed_users.append(current_user)

# 删除包含特定值的所有列表元素
pets = ['cat', 'dog', 'dog', 'goldfish','cat']
while 'cat' in pets:
	pets.remove('cat')

# 使用用户输入来填充字典
responses = {}
polling_active = True
while polling_active:
	name = input("what is your name")
	response = input("what is your favorite subject?")
	responses[name] = response
	repeat = input("would you like to let another person to response?(yes or no)")
	if(repeat == 'no'):
		polling_active = False
print("polling ended")

函数

参数

def greet_user(username):
	print("hello" + username.title() + "!")

# 传递实参  
def describe_bet(animal_type, pet_name):
	print("I have a" + animal_type + "named" + pet_name)
dscribe_bet('hamster', 'harry')

# 键值对参数  
describe_bet(animal_type="hamster", pet_name="harry")  

# 指定函数默认值  
def describe_bet(pet_name, animal_type="dog"):
	do something

# 传递列表  
def greet_users(names):
	for name in names:
		msg = "hello" + name.title()
		print(msg)
usernames = ['Brice', 'Danny', "Lily"]
greet_users(usernames)

function_name(listname[:])  

# 如果需要禁止函数修改列表,向函数中传递列表的副本而不是原件,这样函数所有的操作修改的都是副本而丝毫不影响原件
# 传递任意数量的实参
# 形参名*toppings中的星号让Python创建一个名为toppings的空元组,并将所有的值都封到了这个元组中
def make_pizza(*toppings):
	print(toppings)
make_pizza('mushroom', 'greenpeppers', 'cheese')

# 结合使用位置实参和任意数量实参
def make_pizza(size, *toppings):
	print("make a" + str(size) + "inch pizza")
	for topping in toppings:
		print("-" + topping)

# 使用任意数量的关键字实参
def build_profile(first, last, **user_info):
	profile = {}
	profile['first_name'] = first
	profile['last_name'] = last
	for key, value in user_info.items():
		profile[key] = value
	return profile
user_profile = build_profile('abert', 'einstein', location="priceton",field="physcis")
print(user_profile)		

返回值

# 返回简单值
def get_formatted_name(first_name, last_name):
	full_name=first_name + '' + last_name
	return full_name.title()

# 返回字典
def build_person(first_name, last_name, age=''):
	person={'first':first_name, 'last':last_name}
	if(age):
		person['age'] = age
	return person
musician = build_person("jimi", 'hendrix', age=27)

将函数存储在模块中

# 导入整个模块
imprt module_name
# 调用方法 
module_name.function_name()
# 导入特定的函数
from module_name import function_0, function_1, function_2…
# 使用as给函数指定别名
from module_name import function_name as fn
# 使用as给模块指定别名
import module_name as mn
# 导入模块所有的函数
from module_name import *

函数编写规范:
1.给形参指定默认值或调用关键字实参,等号两边不要有空格
2.代码行的长度不要超过79个字符
3.模块包含多个函数,可使用两个空行将相邻函数分开
4.文件头没有注释时,所有的import语句都应放在文件开头

文件和异常

为了提高程序的运行效率,在程序运行的时候,需要从文件中读取数据,在运行结束之后需要将结果输出到文件中,这个过程中程序需要进行文件操作。在程序运行的过程中可能由于某些原因导致崩溃,当程序面临这些崩溃时如何操作,就是程序的异常处理。通过异常处理可以降低突发状况的危害,提高程序的可用性和稳定性。

读取文件

# 读取整个文件
# 1.open传递文件的名称,程序会在程序源文件所在的目录去查找test.txt文件
# 2.关键字with在不需要访问文件后将其关闭, 你只管打开文件,并在需要时访问它,Python会在合适的时候自动将其关闭  
# 3.read() 到达文件末尾时返回一个空字符串,而将这个空字符串显示出来就是一个空行。要删除末尾的空行,可在打印时使用rstrip()路径  
with open("test.txt") as file_object:
	contents = file_object.read()
	print(contents)

在open()中即可传递文件的相对路径也可以传递文件的绝对路径,Linux和OS X路径中使用斜杠( / ), Window系统中路径使用反斜杠( \ )
另外由于反斜杠在Python中被视为转义标记,为在Windows中万无一失,应以原始字符串的方式指定路径,即在开头的单引号前加上r逐行读取,每一行的结尾都有一个看不见的换行符,打印出来会出现空开,通过rstrip()消除空白。

filename = "test.txt"
with open(filename) as file_object:
	for line in file_object:
		print(line.rstrip())

# 创建一个包含文件各行内容的列表
filename = "test.txt"
with open(filename) as file_object:
	lines = file_object.readlines()
for line in lines:
	print(line.rstrip())

# 写入文件
# open中传递两个参数第一个为文件名称,第二个为文件的打开模式:
# w:写入模式 r:读取模式 a:附加模式 r+:读写模式
# 写入模式w模式打开文件时要格外小心,因为如果指定的文件已经存在,python会在返回文件对象前清空该文件  
filename = "test.txt"
with open(filename, 'w') as file_object:
	file_object.write("I Love Python")

# 写入多行
filename = "test.txt"
with open(filename) as file_object:
	file_object.write("I love python")
	file_object.write("I love create new things")

异常

# 使用try-except-else代码块处理异常
while True:
	first_number = input("\nFirst number:")
	if first_number == 'q':
		break
	second_number = input("\n Second number:")
try:
	answer = int(first_number) / int(second_number)
except ZeroDivisionError:
	print("You can't divide by zero")
else:
	print(answer)

# 处理FileNotFoundError异常
filename = "alice.txt"
try:
	with open(filename) as f_obj:
		contents = f_obj.read()
except FileNotFoundError:
	#异常可使用pass语句表示异常时不做任何处理
	msg = "Sorry the File" + filename + "does not exist"
	print(msg)
else:
	#计算文件中包含多少个单词
	words = contents.split()
	num_words = len(words)
	print("The file has" + str(num_words) + "words")

操作Json文件

# 写列表
import json
numbers = [2, 3, 5, 7, 9]
filename = "number.json"
with open(filename, 'w') as f_obj:
	json.dump(numbers, f_obj)

# 读列表
import json
filename = "number.json"
with open(filename) as f_obj:
	numbers = json.load(f_obj)
print(numbers)

类对象

面向对象编程是大型软件开发的基础,能极大的提高代码的复用率,提高软件的开发效率。在面向对象编程中最基础的就是类的编写和使用,本文将对Python中类的创建和使用方法进行简要介绍。

创建类

下面我们以一个dog类为例进行说明,dog的属性包括姓名和年龄,行为包括坐下和站起。

class Dog():
	def __init__(self,name,age):
		self.name = name
		self.age = age
		self.color = "red"
	def sit(self):
		print(self.name.title() + "is now sitting")
	def stand_up(self):
		print(self.name.title() + "stands up")
	def set_dog_color(self,dogcolor):
		self.color = dogcolor

通过上面的例子可知:
1.类的成员函数的第一个参数都是self类似于C++中的this指针,函数通过self和类关联起来。
2.方法__init__()[注:开头和末尾两个下划线],是一个特殊的函数,和C++类中的构造函数类似,负责对类的成员变量进行初始化,创建类时Python会自动调用它。
3.在调用函数的成员变量时都是通过self.paramer的方式进行访问,类似于C++中通过this指针调用成员变量。
4.成员变量的属性值可以通过__init__()传入、可以在__init__()中指定默认值、可以通过对象名直接修改,还可以通过成员函数对成员变量进行修改。
5.类名称的首字母一般都大写

使用类

下面同样以Dog类为例说明,类的使用方法:

class Dog():
	---snip—
my_dog = Dog("Billy",6)
my_dog.sit()
my_dog.stand_up()
print("My dog's name is " + my_dog.name.title() + ".")
print("My dog's age is " + str(my_dog.age))

通过上面的例子可知
1.Python中不像C++中可以给每个变量设置访问权限,所有变量均可以通过对象名来进行访问。
2.所有的成员函数(init()除外)都可以通过对象名直接进行访问。

类的继承

一个类继承另一个类时,它将自动获得另一个类的所有属性和方法:原有的类称为父类,而新类称为子类,子类继承了其父类所有的属性和方法,同时还可以定义自己的属性和方法。
下面我们以汽车和电动汽车为例进行说明其中汽车为父类,电动汽车为子类

class Car():
	def __init__(self,make,model,year):
		self.make = make
		self.model = model
		self.year = year
		self.odometer_reading = 0
	def get_describe_name(self):
		long_name = str(self.yaer) + ' ' + self.make + ' ' + self.model
		return long_name.title()
	def update_odometer(self, miles):
		self.odometer_reading += miles

class ElectricCar(Car):
	def __init__(self, make, model, year):
		super().__init(make, model, year)
		self.battery_size = 70
	def describe_battery(self):
		print("battery size is " + str(self.battery_size))
	def get_describe_name(self):
		print("This is a electric Car")

# 调用  
my_tesla = ElectricCar('tesla', 'models', 2016)  
print(my_tesla.get_describe_name())

通过上面的例子可以知道:
1.创建子类时,父类必须包含在当前文件中,且位于子类的前面
2.定义子类时必须在括号内指定父类的名称
3.在方法__init__()内传递父类所需要的信息
4.通过super()调用父类的__init__()方法
5.子类可以重写父类的成员函数
6.类可以通过继承或者组合的方式进行使用

导入外部类

随着不断添加新功能,文件可能变的很长,为了遵循python的总体理念,我们应尽可能让文件整洁,为此我们可以将类存储在不同的模块中,然后在主程序中导入所需的模块。
假如我们将Car和ElectricCar都定义在了car.py文件中。

# 导入Car类
from car import Car
# 同时导入Car类和ElectricCar类
from car import Car, ElectricCar
# 导入整个模块
import car
# 导入整个模块之后,通过模块名来定义相关的类
import car
my_beetle = car.Car('volkswagen', 'beetle',2017)
# 导入模块中的所有的类
from module_name import *
# 需要从一个模块中导入很多类时,最好导入整个模块
module_name.class_name()

类编码风格
1.类名应该采用驼峰命名法,即将类名中的每个单词的首字母进行大写,而不使用下划线,实例名称和模块名都采用小写格式,单词之间加上下划线。
2.对于每个类,都应紧跟在类定义后面包含一个文档字符串,这样的字符串要简要的描述类的功能,并遵循编写函数的文档字符串时采用的格式约定。每个模块也都应包含一个文档字符串对其中的类功能进行描述。
3.可以使用空行来进行代码组织,但不要滥用。在类中,可以使用一个空行来分割方法;而在模块中可以使用两个空行来分隔类。
4.需要同时导入标准库中的模块和自己编写的模块时,先导入标准库模块再添加一个空行,然后再导入自己编写的模块。

测试

Python标准库中模块unitest提供了代码测试工具。单元测试用于核实函数的某个方面没有问题;测试用例是一组单元测试,这些单元测试一起核实函数在各种情形下的行为都复合要求。良好的测试用例考虑了函数可能收到的各种输入,包含针对所有这些情形的测试。全覆盖测试用例包含一整套单元测试,涵盖了各种可能的函数使用方法。

测试函数

以下面函数作为被测试的函数

def get_formatted_name(first, last):
	full_name = first + " " + last
	return full_name.title()

创建测试

import unittest
from name_function import get_formatted_name
class NamesTestCase(unittest.TestCase):
	def test_first_last_name(self):
		formatted_name = get_formatted_name('Janis', 'Jplin')
		self.assertEqual(formatted_name, 'Janis Jplin')
unittest.main()

方法必须以test_开头,这样它才会在运行测试脚本时自动运行;

测试中的各种断言

assertEqual(a,b)
assertNotEqual(a,b)
assertTrue(x)
assertFalse(x)
assertIn(item, list)
assertNotIn(item, list)

创建要测试的类,帮助管理匿名调查

class AnonymousSurvey():
	def __init__(self, question):
		self.question = question
		self.responses = []
	def show_question(self):
		print(self.question)
	def store_response(self, new_response):
		self.responses.append(new_response)
	def show_result(self):
		print("survey results:")
		for response in self.responses:
			print("." + response)

测试AnonymousSurvey()类:

import unittest
from survey import AnonymousSurvey
class TestAnonymousSurvey(unittest.TestCase):
	def test_store_three_responses(self):
		question = "what's language did you first learn to speak?"
		my_survey = AnonymousSurvey(question)
		responses = ['English', 'Spanish', 'Chinese']
		for response in responses:
			my_survey.store_response(response)
		for response in responses:
			self.assertIn(response, my_survey.responses)

setup方法
setup()方法类似于测试类的构造函数,Python先运行它,再运行各个以test_开头的方法,setup方法创建了测试需要的对象和数据。

import unittest
from survey import AnonymousSurvey
class TestAnonymousSurvey(unittest.TestCase):
	def __init__(self):
		question = "what's your mother tongue?"
		self.my_survey = AnonymousSurvey(question)
		self.responses = ["English", "Spanish", "Chinese"]
	def test_store_three_responses(self):
		--snip—
  • 17
    点赞
  • 35
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

码农飞飞

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值