【合集】Python基础知识【第一版】

本文介绍了Python编程的基础知识,包括变量、字符串操作、列表、字典、条件语句、循环结构、函数以及类的使用。通过示例展示了如何定义和调用函数,创建和操作列表、字典,以及如何使用条件语句进行逻辑判断。此外,还涉及到了用户输入、字符串格式化和文件操作等概念。

变量

print("-------------输出语句-------------");message="Hello Python world";print(message);print("-------------首字母大写-------------");name="ada lovelace";print(name.title());print("-------------大小写-------------");print(name.upper());print(name.lower());print("-------------拼接字符串-------------");first_name = "ada"last_name = "lovelace"full_name = first_name + " " + last_nameprint(full_name);print("-------------添加空白------ 山东党性培训 www.shganxun.cn -------");print("	Python");print("Languages:
Python
C
JavaScript");print("-------------删除空白-------------");print("Hello ".rstrip());print("-------------运算-------------");print(2+3);print(3-2);print(2*3);print(3/2);print(3**2);print(3**3);print(10**6);print(0.1+0.1);print(0.2+0.2);print("------------注释-------------");# 测试注释
-------------输出语句-------------Hello Python world-------------首字母大写-------------Ada Lovelace-------------大小写-------------ADA LOVELACEada lovelace-------------拼接字符串-------------ada lovelace-------------添加空白-------------PythonLanguages:PythonCJavaScript-------------删除空白-------------Hello-------------运算-------------5161.592710000000.20.4------------注释-------------Process finished with exit code 0
  1. 运行文件hello_world.py时,末尾的.py指出这是一个Python程序,因此编辑器将使用Python解释器来运行它
  2. 变量名只能包含字母、数字和下划线。变量名可以字母或下划线打头,但不能以数字打头,例如,可将变量命名为message_1,但不能将其命名为1_message。
  3. 变量名不能包含空格,但可使用下划线来分隔其中的单词。例如,变量名greeting_message可行,但变量名greeting message会引发错误。
  4. 不要将Python关键字和函数名用作变量名,即不要使用Python保留用于特殊用途的单词,
  5. 变量名应既简短又具有描述性。
  6. 慎用小写字母l和大写字母O,因为它们可能被人错看成数字1和0
  7. 在Python中,注释用井号( # )标识。井号后面的内容都会被Python解释器忽略

列表

print("-------------列表-------------");bicycles = ['trek', 'cannondale', 'redline', 'specialized'];print(bicycles);print("-------------访问列表元素-------------");print(bicycles[0]);print("-------------修改列表元素-------------");bicycles[0]='ducati';print(bicycles);print("-------------添加列表元素-------------");bicycles.append('test');print(bicycles);print("-------------插入列表元素-------------");bicycles.insert(0,'test2');print(bicycles);print("-------------删除列表元素-------------");del bicycles[0];print(bicycles);print(bicycles.pop());print(bicycles);print("-------------排序列表元素-------------");bicycles.sort();print(bicycles);print("-------------倒叙打印列表元素-------------");print(bicycles.reverse());print("-------------列表长度-------------");print(len(bicycles));print("-------------数值列表------------");numbers=list(range(1,6));print(numbers);
-------------列表-------------['trek', 'cannondale', 'redline', 'specialized']-------------访问列表元素-------------trek-------------修改列表元素-------------['ducati', 'cannondale', 'redline', 'specialized']-------------添加列表元素-------------['ducati', 'cannondale', 'redline', 'specialized', 'test']-------------插入列表元素-------------['test2', 'ducati', 'cannondale', 'redline', 'specialized', 'test']-------------删除列表元素-------------['ducati', 'cannondale', 'redline', 'specialized', 'test']test['ducati', 'cannondale', 'redline', 'specialized']Process finished with exit code 0
  1. 列表由一系列按特定顺序排列的元素组成
  2. 列表是有序集合,因此要访问列表的任何元素,只需将该元素的位置或索引告诉Python即可
  3. Python方法 sort() 让你能够较为轻松地对列表进行排序。
  4. 要保留列表元素原来的排列顺序,同时以特定的顺序呈现它们,可使用函数 sorted() 。函数sorted() 让你能够按特定顺序显示列表元素,同时不影响它们在列表中的原始排列顺序。
  5. 要反转列表元素的排列顺序,可使用方法 reverse()
  6. 使用函数 len() 可快速获悉列表的长度
  7. Python根据缩进来判断代码行与前一个代码行的关系。

选择结构

print("-------------检查是否相等-------------");car='bmw';print(car=='bmw');print(car=='audi');print(car=='BMW');print(car.upper()=='BMW');age=18;print(age==18);print(age>=18);print(age<=18);print(age>18);print(age<18);age_0 = 22;age_1 = 18;print(age_0 >= 21 and age_1 >= 21);print(age_0 >= 21 or age_1 >= 21);print("-------------if语句-------------");age = 19if age >= 18:    print("You are old enough to vote!");        age=17    if age>=18:        print("You are old enough to vote!");    else:        print("Sorry you are too young");                age = 12        if age < 4:            print("Your admission cost is $0.")        elif age < 18:            print("Your admission cost is $5.")        else:            print("Your admission cost is $10.")                        age = 12            if age < 4:                price = 0            elif age < 18:                price = 5            elif age < 65:                price = 10            elif age >= 65:                price = 5print("Your admission cost is $" + str(price) + ".")
-------------检查是否相等-------------TrueFalseFalseTrueTrueTrueTrueFalseFalseFalseTrue-------------if语句-------------You are old enough to vote!Sorry you are too youngYour admission cost is $5.Your admission cost is $5.Process finished with exit code 0
  1. 在Python中检查是否相等时区分大小写
  2. 要判断两个值是否不等,可结合使用惊叹号和等号( != )
  3. 要检查是否两个条件都为 True ,可使用关键字 and 将两个条件测试合而为一
  4. 关键字 or 也能够让你检查多个条件,但只要至少有一个条件满足,就能通过整个测试。
  5. 在 if 语句中,缩进的作用与 for 循环中相同。如果测试通过了,将执行 if 语句后面所有缩进的代码行,否则将忽略它们。
  6. 经常需要检查超过两个的情形,为此可使用Python提供的 if-elif-else 结构

字典

print("-------------一个简单的字典-------------");alien_0 = {'color': 'green', 'points': 5}print(alien_0['color'])print(alien_0['points'])print("-------------访问字典中的值------------");alien_0={'color':'green'};print(alien_0['color']);print("-------------先创建一个空字典------------");alien_0 = {}alien_0['color'] = 'green'alien_0['points'] = 5print(alien_0)print("-------------修改字典中的值------------");alien_0={'color':'green'}print("The alien is " + alien_0['color'] + ".")alien_0['color'] = 'yellow'print("The alien is now " + alien_0['color'] + ".")print("-------------删除键值对------------");alien_0 = {'color': 'green', 'points': 5}print(alien_0);del alien_0['points']print(alien_0);print("-------------遍历字典------------");user_0 = {    'username': 'efermi',    'first': 'enrico',    'last': 'fermi',}for key,value in user_0.items():    print("
Key:"+key)    print("Value:"+value)
-------------一个简单的字典-------------green5-------------访问字典中的值------------green-------------先创建一个空字典------------{'color': 'green', 'points': 5}-------------修改字典中的值------------The alien is green.The alien is now yellow.-------------删除键值对------------{'color': 'green', 'points': 5}{'color': 'green'}-------------遍历字典------------Key:usernameValue:efermiKey:firstValue:enricoKey:lastValue:fermiProcess finished with exit code 0
  1. 字典是一系列键 — 值对。每个键都与一个值相关联,你可以使用键来访问与之相关联的值。与键相关联的值可以是数字、字符串、列表乃至字典。事实上,可将任何Python对象用作字典中的值。
  2. 要获取与键相关联的值,可依次指定字典名和放在方括号内的键
  3. 字典是一种动态结构,可随时在其中添加键 — 值对。要添加键 — 值对,可依次指定字典名、用方括号括起的键和相关联的值。
  4. 对于字典中不再需要的信息,可使用 del 语句将相应的键 — 值对彻底删除。
  5. 字典存储的是一个对象(游戏中的一个外星人)的多种信息,但你也可以使用字典来存储众多对象的同一种信息。

循环结构

print("-------------函数input()的工作原理-------------");message = input("Tell me something, and I will repeat it back to you: ")print(message)print("-------------编写清晰的程序-------------");name=input("Please enter your name:");print("Hello,"+name+"!");print("-------------求模运算符-------------");print(4%3);print("-------------while循环-------------");current_number = 1while current_number <= 5:    print(current_number)    current_number += 1print("-------------让用户选择何时退出-------------");prompt = "
Tell me something, and I will repeat it back to you:"prompt += "
Enter 'quit' to end the program. "message = ""while message != 'quit':    message = input(prompt)    print(message)print("-------------break语句-------------");prompt = "
Please enter the name of a city you have visited:"prompt += "
(Enter 'quit' when you are finished.) "while True:    city = input(prompt)    if city == 'quit':        break    else:        print("I'd love to go to " + city.title() + "!")
-------------函数input()的工作原理-------------Tell me something, and I will repeat it back to you: Hello WorldHello World-------------编写清晰的程序-------------Please enter your name:AliceHello,Alice!-------------求模运算符-------------1-------------while循环-------------12345-------------让用户选择何时退出-------------Tell me something, and I will repeat it back to you:Enter 'quit' to end the program. Hello WorldHello WorldTell me something, and I will repeat it back to you:Enter 'quit' to end the program. quitquit-------------break语句-------------Please enter the name of a city you have visited:(Enter 'quit' when you are finished.) ShangHaiI'd love to go to Shanghai!Please enter the name of a city you have visited:(Enter 'quit' when you are finished.) quitProcess finished with exit code 0
  1. 函数 input() 让程序暂停运行,等待用户输入一些文本。获取用户输入后,Python将其存储在一个变量中,以方便你使用。
  2. 函数 input() 接受一个参数:即要向用户显示的提示或说明,让用户知道该如何做。
  3. 每当你使用函数 input() 时,都应指定清晰而易于明白的提示,准确地指出你希望用户提供什么样的信息——指出用户该输入任何信息的提示都行
  4. 使用函数 input() 时,Python将用户输入解读为字符串

函数

print("-------------函数-------------");def greet_user():    print("Hello World")print("-------------区分线-------------");greet_user();print("-------------调用函数-------------");def tpl_sum( T ):          #定义函数tpl_sum()    result = 0           #定义result的初始值为0    for i in T:          #遍历T中的每一个元素i        result += i     #计算各个元素i的和    return result  #函数tpl_sum()最终返回计算的和print("(1,2,3,4)元组中元素的和为:",tpl_sum((1,2, 3,4))) #使用函数tpl_sum()计算元组内元素的和print("[3,4,5,6]列表中元素的和为:",tpl_sum([3,4, 5,6])) #使用函数tpl_sum()计算列表内元素的和print("[2.7,2,5.8]列表中元素的和为:",tpl_sum([2.7, 2,5.8])) #使用函数tpl_sum()计算列表内元素的和print("[1,2,2.4]列表中元素的和为:",tpl_sum([1,2,2.4]))#使用函数tpl_sum()计算列表内元素的和
-------------函数--------------------------区分线-------------Hello World-------------调用函数-------------(1,2,3,4)元组中元素的和为: 10[3,4,5,6]列表中元素的和为: 18[2.7,2,5.8]列表中元素的和为: 10.5[1,2,2.4]列表中元素的和为: 5.4Process finished with exit code 0
  1. 这个示例演示了最简单的函数结构
  2. 调用函数就是使用函数,在 Python 程序中,当定义一个函数后,就相当于给了函数一个名称,指定了函数里包含的参数和代码块结构。完成这个函数的基本结构定义工作后,就可以通过调用的方式来执行这个函数,也就是使用这个函数。
  3. 在 Python 程序中,使用关键字 def 可以定义一个函数,定义函数的语法格式如下所示。
def<函数名>(参数列表):    <函数语句>    return<返回值>

在上述格式中,参数列表和返回值不是必需的,return 后也可以不跟返回值,甚至连 return 也没有。如果 return 后没有返回值,并且没有 return 语句,这样的函数都会返回 None 值。有些函数可能既不需要传递参数,也没有返回值。

注意:当函数没有参数时,包含参数的圆括号也必须写上,圆括号后也必须有“:”。

在 Python 程序中,完整的函数是由函数名、参数以及函数实现语句(函数体)组成的。在函数声明中,也要使用缩进以表示语句属于函数体。如果函数有返回值,那么需要在函数中使用 return 语句返回计算结果。

根据前面的学习,可以总结出定义 Python 函数的语法规则,具体说明如下所示。

  • 函数代码块以 def 关键字开头,后接函数标识符名称和圆括号()。
  • 任何传入参数和自变量必须放在圆括号中间,圆括号之间可以用于定义参数。
  • 函数的第一行语句可以选择性地使用文档字符串——用于存放函数说明。
  • 函数内容以冒号起始,并且缩进。
  • return [表达式] 结束函数,选择性地返回一个值给调用方。不带表达式的 return 相当于返回 None。

print("-------------类-------------");class MyClass:         #定义类MyClass    "这是一个类."myclass = MyClass()    #实例化类MyClassprint('输出类的说明:')  #显示文本信息print(myclass.__doc__)  #显示属性值print('显示类帮助信息:')help(myclass)print("-------------类对象-------------");class MyClass:                 #定义类MyClass    """一个简单的类实例"""    i = 12345                  #设置变量i的初始值    def f(self):               #定义类方法f()        return 'hello world'  #显示文本x = MyClass()                  #实例化类#下面两行代码分别访问类的属性和方法print("类MyClass中的属性i为:", x.i)print("类MyClass中的方法f输出为:", x.f())print("-------------构造方法-------------");class Dog():    """小狗狗"""    def __init__(self, name, age):        """初始化属性name和age."""        self.name = name        self.age = age    def wang(self):        """模拟狗狗汪汪叫."""        print(self.name.title() + " 汪汪")    def shen(self):        """模拟狗狗伸舌头."""        print(self.name.title() + " 伸舌头")print("-------------调用方法-------------");def diao(x,y):    return (abs(x),abs(y))class Ant:    def __init__(self,x=0,y=0):        self.x = x        self.y = y        self.d_point()    def yi(self,x,y):        x,y = diao(x,y)        self.e_point(x,y)        self.d_point()    def e_point(self,x,y):        self.x += x        self.y += y    def d_point(self):        print("亲,当前的位置是:(%d,%d)" % (self.x,self.y))ant_a = Ant()ant_a.yi(2,7)ant_a.yi(-5,6)
-------------类-------------输出类的说明:这是一个类.显示类帮助信息:Help on MyClass in module __main__ object:class MyClass(builtins.object)|  这是一个类.|  |  Data descriptors defined here:|  |  __dict__|      dictionary for instance variables (if defined)|  |  __weakref__|      list of weak references to the object (if defined)-------------类对象-------------类MyClass中的属性i为: 12345类MyClass中的方法f输出为: hello world-------------构造方法--------------------------调用方法-------------亲,当前的位置是:(0,0)亲,当前的位置是:(2,7)亲,当前的位置是:(7,13)Process finished with exit code 0
  1. 把具有相同属性和方法的对象归为一个类
  2. 在 Python 程序中,类只有实例化后才能够使用。类的实例化与函数调用类似,只要使用类名加小括号的形式就可以实例化一个类。
  3. 方法调用就是调用创建的方法,在 Python 程序中,类中的方法既可以调用本类中的方法,也可以调用全局函数来实现相关功能。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值