(一)Python基础语法
文章目录
- 一、变量与数据类型
- 二、列表基础 [ ]
- 三、操作列表 [ ]—遍历
- 四、字典 {键:值,键:值}
- 五、用户输入和while循环
- 六、if语句
- 七、函数def
- 八、类class
- 九、导入类
- 十、文件和异常
一、变量与数据类型
Python数据类型不用声明,编译器自动识别,常见数据类型如下;Python的每一行代码结尾不需要添加分号;Python的代码块内需遵循严格缩进规则;Python3在打印消息时习惯性加上括号,且默认打印结束后换行;python的单行注释采用#, 多行注释采用"""…"""。
- 整型(int)
- 浮点型(float)
- 布尔型(bool)
- 字符串(string): 分 单引号 / 双引号 两类,用法:字符串大小写修改,字符串拼接,str()强制类型转换,删除字符串空白
【注】代码的尝试可通过python交互界面尝试, 命令:python3
#修改字符串大小写——title()/upper()/loweer()
name = "ada lovelace"
print(name.title()) #字符串的 首字母大写 打印结果:Ada Lovelace
print(name.upper()) # 所有字母大写 ADA LOVELACE
print(name.lower()) # 所有字母小写 ada lovelace#拼接字符串—— “ + ”
first_name = "ada"
last_name = "lovelace"
full_name = "ada" + " " + "lovelace"
print(full_name) #拼接字符串 打印结果:ada lovelace #字符串强制类型转换——str()
age = 23
message = "Happy " + str(age) + "rd Birthday!"
print(message) #类型转换 打印结果:Happy 23rd Birthday!#(暂时)删除空白——rstrip()/lstrip()/strip()
favorate_language = ' python '
favorate_language.rstrip() #去除末尾空白
favorate_language.lstrip() #去除开头空白
favorate_language.strip() #去除首位两端空白
二、列表基础 [ ]
列表,类似"数组",由一系列按特定顺序排列的元素组成,**用中括号“[ ]”表示,各元素之间用逗号“,”隔开。在python中习惯性给列表制定一个表示复数的名词(如letters, nums等)。
列表分为字符串列表和数字列表两类,下面以字符串列表进行说明。
- 访问:列表元素的索引从0开始;
- 增加、删除元素:使用内置方法实现,append()/insert() 和 del()/pop()/remove();
- 排序:字母序 / 逆序,sort()/sort(reverse = True),sorted(), len()
#访问列表元素
bicycles = ['trek', 'cannon', 'redline']
print(bicycles[0]) #打印结果:trek#添加元素——apped()/insert()
bicycles.append('honda') #列表尾部添加元素
print(bicycles) #打印结果:['trek', 'cannon', 'redline', 'honda']
bicycles.insert(0, 'ducati') #列表中指定位置插入元素
print(bicycles) #打印结果:['ducati', 'trek', 'cannon', 'redline', 'honda'] #删除元素——del()/pop()/remove()
del bicycles[0] #删除指定位置元素
print(bicycles) #打印结果:['trek', 'cannon', 'redline', 'honda']
poped_bicycles = bicycles.poped() #删除结尾元素
print(poped_bicycles) #打印结果:['trek', 'cannon', 'redline']
bicycles.remove('cannon') #根据值删除元素
print(bicycles) #打印结果:['trek', 'redline', 'honda']#(永久性)列表排序——sort()/sort(reverse=True)
cars = ['bmw', 'audi', 'toyato', 'subaru']
cars.sort()
print(cars) #打印结果:['audi', 'bmw', 'subaru', 'toyato']
cars.sort(reverse=True)
print(cars) #打印结果:['toyato', 'subaru', 'bmw', 'audi']#(临时性)列表排序——sorted
cars = ['bmw', 'audi', 'toyato', 'subaru']
print(sorted(cars) #打印结果:['audi', 'bmw', 'subaru', 'toyato']
print(cars) #打印结果:['bmw', 'audi', 'toyato', 'subaru']#列表反向打印,及长度——reverse()/len()
cars = ['bmw', 'audi', 'toyato', 'subaru']
cars.reverse()
print(cars) #打印结果:['subaru', 'toyato', 'audi', 'bmw']
len(cars) #打印结果:4
三、操作列表 [ ]—遍历
列表遍历,即使用for循环,对列表中的每个元素都执行相同的操作。列表中的元素是可以进行修改的,还有一类特殊的列表,元素不可变化,成为元组(不可变的列表)。
- 遍历:for循环实现;
- 创建数字列表:内置方法实现, range()—生成一系列数字,list()—将range()结果转换成列表;
- 切片:处理列表的部分元素,[x:y], 列表不能直接进行赋值操作。
- 元组:使用圆括号“( )”表示, 其中元素不可修改。
#遍历数组——for循环
magicians = ['alice', 'david', 'bob']
for magicain in magicians: #遍历数组print(magician.title() + ", that was a great trick!")
print("I can't wait to see your next trick, " + magician.title() + ".\n")#打印结果:
Alice, that was a great trick!
David, that was a great trick!
Bob, that was a great trick!
I can't wait to see your next trick, Bob.#创建数字列表——list(range())
nums = list(range(1,6)) #创建数字列表
print(nums) #打印结果:[1, 2, 3, 4, 5]
even_nums = list(range(1,6,2)) #创建数字列表,指定步长
print(even_nums) #打印结果:[1, 3, 5]#列表切片——使用列表的一部分[x:y], [x:], 从头开始[:y], 返回列表最后的x个元素[-x:], 复制列表[:]
players = ['mrac', 'jim', 'tom', 'bob', 'pierr', 'clerry']
print(players[1:4]) #打印结果:['jim', 'tom', 'bob', 'pierr']
print(players[:2]) #打印结果:['marc', 'jim', 'tom']
print(players[4:]) #打印结果:['pierr', 'clerry']
print(players[-3:]) #打印结果:['bob', 'pierr' ,'clerry']my_players = players[:] #复制列表元素
print(my_players) #打印结果:['mrac', 'jim', 'tom', 'bob', 'pierr', 'clerry'] #元组()
dimensions = (200, 50) #定义元组
for dimension in dimensions:print(dimension) #打印结果: 200# 50
四、字典 {键:值,键:值}
在Python中,字典是一系列的键值对,可以通过键来访问与之关联的值。与键相关联的值可以是数字、字符串、列表、字典等。
字典是一种动态结构,可随时在其中添加键-值对。
- 访问字典中的值:通过键实现;
- 添加、删除键-值对:无序添加;
- 修改字典中的值:重新赋值;
- 字典遍历:无序输出,遍历键-值对,遍历所有键,遍历所有值; 方法items() / keys() / values() 。
#访问、(无序)添加、删除键-值对
alien_o = {'color' : 'green', 'points' : 5}
print(alien_o['color']) #打印结果:green
print(alien_o) #打印结果:{'color' : 'green', 'points' : 5}alien_o['x_position'] = 0
alien_o['y_position'] = 25 #添加键-值对
print(alien_o) #打印结果:{'color' : 'green', 'points' : 5, 'y_position' : 25, 'x_position' : 0}#修改字典中的值——重新赋值
alien_o['color'] = 'yellow'
print(alien_o['color']) #打印结果:yellow#(永久性)删除——del
del alien_o['points'] #删除键-值对
print(alien_o) #打印结果:{'color' : 'green', 'y_position' : 25, 'x_position' : 0}#遍历键-值对——for
user_0 = {'username' : 'efermi','first' : 'enrico','last' : 'fermi',
}
for key,value in user_0.items(): #遍历键-值对 #打印结果:无序输出print("\nKey: " + key) #Key: lastprint("Value", + value) #Value: fermi
for key in user_0.keys(): #遍历键 # #打印结果:无序输出print(key.title()) #Key:first #Username
for value in user_0.values(): #遍历值 #Value:enrico #Last #打印结果:无序输出print(value.title()) # #First #Efermi#Key: username #Enrico#Value: efermi #Fermi
五、用户输入和while循环
函数input()会暂停程序运行,给出提示,等待用户输入一些文本(字符串),python会将其存储在一个指定变量中。有时候,提示可能超过一行,则可将提示存储在一个变量中,再将该变量传递给input()。
prompt = "If you tell us who you are, we can personalize the message you see."
prompt += "\nWhat's your first name?"
name = input(prompt)
print("\nHello, " + name + "!")#打印结果:
If you tell us who you are, we can personalize the message you see.
What's your first name? EricHello, Eric!
#while循环——break结束循环,continue结束本次循环,返回循环开头
while True:city = input("\nPlease input the name of a city, enter 'quit' when you are finished: ")if city == 'quit':break #结束循环else:print("I'd like to go to " + city.title() + "!")num = 0
while num < 10:num += 1if num % 2 == 0:continue #结束本次循环,回到循环开头print(num) #打印结果:1 3 5 7 9
六、if语句
if语句的核心都是一个值为True或False的表达式,即条件测试。条件测试中支持多条件的检查,特定值的检查等,结尾处需添加冒号:。
- 多条件检查关键字:and、or、in、not in等;
- 多条件格式:if…elif…else…, else可以省略,elif…else…也可以省略
#if语句格式
age = 23
if age >= 18 and age == 23:print("You are old enough to vote!")#使用if处理列表
requested_toppings = ['mushrooms', 'green peppers', 'extra cheese']
for requested_topping in requested_toppings:if requested_topping == 'green peppers':print("Sorry, we are out of green peppers right now.")else:print("Adding " + requested_topping + ".")
print("\nFinishing making your pizza!")
七、函数def
python中的函数通过关键字def定义,定义以冒号结尾。函数的相关信息:
- 参数传递:实参—>形参(形参可设置默认值,其等号两边不能有空格);
- 返回值:函数需要提供一个变量来存储返回值;
- 函数可以存储在模块中:通过关键字import导入模块,亦可导入模块中的特定函数;
- 函数别名: 通过关键字as给函数/模块指定别名。
#位置实参——一一对应传递, 关键字实参——等号两边不能有空格
def describe_pet(animal_type, pet_name='dog'):"""显示宠物信息"""print("\nI have a " + animal_type + ".")print("My " + animal_type + "'s name is " + pet_name.title() + ".")describe_pet('hamster', 'harry') #调用函数,位置实参
describe_pet(animal_type='hamster', pet_name='harry') #第二次调用函数,关键字实参#返回值——return将值返回到调用函数的代码行
def get_formatted_name(first_name, last_name, middle_name=''): #设置实参可选(通过空末尾字符串实现)"""返回整洁的姓名"""if middle_name:full_name = first_name + ' ' + middle_name + ' ' + last_nameelse:full_name = first_name + ' ' + last_namereturn full_name.title()musician = get_formatted_name('jimi', 'hendrix')
print(musician) #打印结果:Jimi Hendrix
将函数存储在模块中:
#pizza.py
def make_pizza(size, *toppings): #*toppings: 表示创建一个名为toppings的空元祖"""概述要制作的比萨"""print("\nMaking a " + str(size) + "-inch pizza with the following toppings:")for topping in toppings:print("- " + topping)
#making_pizzas.py
import pizza #导入特定函数:from pizza import make_pizza pizza.make_pizza(16, 'pepperoni')
pizza.make_pizza(12, 'mushrooms', 'green peppers', 'extra cheese')#给模块指定别名——as
#import pizza as p
#pizza.make_pizza(16, 'pepperoni')
#pizza.make_pizza(12, 'mushrooms', 'green peppers', 'extra cheese')
八、类class
python中的class名称首字母必须大写,类中包含属性和方法,同其它语言一样。
- 方法__init__(): python的默认方法,其中形参self必不可少,当类class创建新实例时,init()会自动运行,且会自动传入实参self。每个与类相关联的方法调用都自动传入实参self,它是一个指向实例本身的引用,让实例能够访问类中的属性和方法。以self为前缀的变量都可供类中所有的方法使用。
- 类的实例化:class实例化的过程中会传入实参,以便通过例化名调用class中的方法。
- 类的继承:语法 class ElectricCar(Car): 子类时,子类中的方法__init__()需要父类施以援手创建。子类__init__()中通过关键字super调用父类Car中的__init__()方法,关联父类与子类。
- 将类的实例作为属性:相当于对这个属性类进行实例化,并将属性存储在对应的变量中。
#dog.py
class Dog():"""一次模拟小狗的简单尝试"""def __init__(self, name, age):""""初始化name和age"""self.name = name #class中的属性(变量),以self为前缀的变量都可供类中所有的方法使用self.age = agedef sit(self): #class中的方法"""模拟小狗被命令时蹲下"""print(self.name.title() + "is now sitting.")def roll_over(self):"""模拟小狗被命令时打滚"""print(self.name.title() + "rolled over!") my_dog = Dog('willie', 6) #实例化,传参
my_dog.sit() #调用方法
my_dog.roll_over()
类的继承:
#父类
class Car():def __init__(self, make, model, year):self.make = makeself.model = modelself.year = yearself.odometer_reading = 0 #给指定属性添加默认值def get_descriptive_name(self):long_time = str(slef.year) + ' ' + self.name + ' ' + self.modelreturn long_time.title()def read_odometer(self):print("This car has " + str(self.odometer_reading) + " miles on it.")def update_odometer(self, mileage):if mileage >= self.odometer_reading:self.odometer_reading = mileselse:print("You can't roll back an odometer!")class Battery():def __init__(self, battery_size=70):self.battery_size = battery_sizedef describe_battery(self): print("This car has a " + str(self.battery_size) + "-kWh battery.") class ElectricCar(Car): #继承def __init__(self, make, model, year):super.__init__(make, model, year) #通过关键字super调用父类Car中的__init__()方法,关联父类与子类self.battery = Battery() #添加新属性, 将实例作为属性,创建Battery实例my_tesla = ElectricCar('tesla', 'model s', 2016)print(my_tesla.get_descriptive_name())
my_tesla.battery.describe_battery() #调用当前类中的属性类的方法
九、导入类
导入类是一种有效的编程方式,在Python中灵活多用,可以大大节省代码量。
- 在模块中存储多个类:python的标准库中包含了大量已有的模块供用户使用
- 在一个模块中导入多个类:导入方法多样,如下:
- 导入类:相当于将类复制到了当前文件中。
#从模块car中导入类Car, 支持导入多个类
from car import Car
from car import Car, ElectricCar#直接导入模块
import car
十、文件和异常
- 打开文件:函数open(‘file_name’),打开指定文件,Python会在当前文件所在的目录中查找指定的文件。函数open()返回一个表示文件的对象,python将这个对象存储在后面使用的变量中。关键字with会在不需要放文件后将其关闭。
- 读取文件:read()读取整个文件的内容,将其作为一个长长的字符串存储在指定的变量中。redlines()读取文件每一行并将文件各行存储在一个列表中。读取文件时,python会将其中的所有文本都解读为字符串。
#读取整个文件——read()
with open('digital.txt') as file_object:conetents = file_object.read()print(contents)#读取文件行——redlines(),将文件各行存储在一个列表中
with open('digital.txt') as file_object:lines = file_object.readlines()
for line in lines:print(line.rstrip()) #打印列表中的各行内容
- 写入文件:调用write()写入文件内容,同时需指定文件打开模式——写入模式(‘w’)、读取模式(‘r’)、附加模式(‘a’)、读取和写入模式(‘r+’),若省略模式实参,python默认只读模式打开文件。Python只能将字符串写入文本文件,若要将数据写入,必须先使用str()进行转换。
filename = 'programming.txt'with open(filename, 'w') as file_object:file_object.write("I love programming.\n") #write函数不能实现自动换行file_object.write("I love creating new games.\n")
- 异常:python中的异常是使用try-except代码块处理的。try-except代码块让python执行指定的操作,同时告诉python发生异常时怎么办。使用了try-except代码块时,即便出现了异常,程序也将继续运行。
print(5/0)#报错:
Traceback (most recent call last)file "filename.py", line 1, in <module>print(5/0)
ZeroDivisionError:division by zero
为了避免python报上述错误,打断程序,可以通过try-except实现程序的继续运行,避免程序崩溃,如下:
#失败时打印指定提示信息——指定操作
try:print(5/0)
except ZeroDivisionError:print("You can't divide bu zero!")#失败时一声不吭——pass
try:print(5/0)
except ZeroDivisionError:pass
(一)Python基础语法相关推荐
- Python基础语法学习笔记
Python基础语法学习笔记 想淘宝省钱看我简介,博客www.liangxin.name (一) 一.Print()函数 1.数字可以直接输出,无需加引号 只能理解数字,却读不懂文字.因为数字和数学运 ...
- 吾八哥学Python(四):了解Python基础语法(下)
咱们接着上篇的语法学习,继续了解学习Python基础语法. 数据类型 大体上把Python中的数据类型分为如下几类:Number(数字),String(字符串).List(列表).Dictionary ...
- Python 基础语法_Python脚本文件结构
目录 目录 前言 软件环境 Python Script文件结构 导入模块的流程 Python的包package 最后 前言 Python基础语法这一章,主要记录了Python的文件结构.逻辑运算符.算 ...
- python使用缩进作为语法边界-重庆铜梁高校邦数据科学通识课【Python基础语法】答案...
重庆铜梁高校邦数据科学通识课[Python基础语法]答案it8p 重庆铜梁高校邦数据科学通识课[Python基础语法]答案 关注公众号{帅搜}即可查询答案 支持:网课,智慧树,知到,超星,尔雅,学习通 ...
- python基础语法 第0关print-徐州鼓楼高校邦数据科学通识课【Python基础语法】答案...
徐州鼓楼高校邦数据科学通识课[Python基础语法]答案it8p 徐州鼓楼高校邦数据科学通识课[Python基础语法]答案 关注公众号{帅搜}即可查询答案 支持:大学网课,智慧树,知到,超星,尔雅,学 ...
- python基础语法 第0关print-重庆酉阳高校邦数据科学通识课【Python基础语法】答案...
重庆酉阳高校邦数据科学通识课[Python基础语法]答案it8p 重庆酉阳高校邦数据科学通识课[Python基础语法]答案 关注公众号{帅搜}即可查询答案 支持:大学网课,智慧树,知到,超星,尔雅,学 ...
- python基础语法 第0关print-温州文成高校邦数据科学通识课【Python基础语法】答案...
温州文成高校邦数据科学通识课[Python基础语法]答案it8p 温州文成高校邦数据科学通识课[Python基础语法]答案 关注公众号{帅搜}即可查询答案 支持:网课,智慧树,知到,超星,尔雅,学习通 ...
- 基于python物流管理系统毕业设计-长白高校邦数据科学通识课【Python基础语法】答案...
长白高校邦数据科学通识课[Python基础语法]答案it8p 长白高校邦数据科学通识课[Python基础语法]答案 关注公众号{帅搜}即可查询答案 支持:网课,智慧树,知到,超星,尔雅,学习通,选修课 ...
- python代码块所属关系的语法-天元高校邦数据科学通识课【Python基础语法】答案...
天元高校邦数据科学通识课[Python基础语法]答案it8p 天元高校邦数据科学通识课[Python基础语法]答案 关注公众号{帅搜}即可查询答案 支持:大学网课,智慧树,知到,超星,尔雅,学习通,选 ...
- python语法基础学习-Python基础语法精心总结!看完都知道的可以往下继续学习了...
原标题:Python基础语法精心总结!看完都知道的可以往下继续学习了 这应该是最详细的Python入门基础语法总结! 定义变量,使用变量 1. input 用户自己输入值 2. print 打印值 可 ...
最新文章
- ERROR 1366 (HY000): Incorrect string value: '\xD5\xC5\xC8\xFD' for column 'name' at row 1
- 【Paper】2003_Consensus Problems in Networks of Agents with Switching Topology and Time-Delays
- go gin 第二次使用ShouldBindJSON失效的原因及解决办法:使用ShouldBindBodyWith代替
- 如何安装tensorflowGPU环境搭建(不报AVX2的警告)
- python未将对象引用设置到对象的实例_在Python中使用pingarapi。服务器引发Webfault:对象引用未设置为对象的实例...
- 《天天数学》连载00:序言
- Spring Cloud Eureka 高可用注册中心
- C++ Qt 访问权限总结
- mysql 策略_MySQL 密码策略
- Java nginx 双向ssl_nginx配置ssl双向验证 nginx https ssl证书配置
- 群晖NAS教程(十三)、利用Web Station安装wordpress博客
- linux4.12 交叉编译链,交叉编译工具链(很详细)
- 推荐使用金山WPS 2005 !
- win10企业版 微软商店安装
- 如何做一场B格满满的技术大会演讲
- 田忌赛马c语言程序设计,关于c语言的田忌赛马问题。
- Java岗大厂面试百日冲刺 - 日积月累,每日三题【Day23】—— 算法1
- 《大规模元搜索引擎技(1)》一第1章 绪言
- 用手写板向计算机输入汉字是什么技术,使用手写板输入文字的简单介绍
- 计算机大赛剪辑的视频,视频剪辑大赛