IT数码 购物 网址 头条 软件 日历 阅读 图书馆
TxT小说阅读器
↓语音阅读,小说下载,古典文学↓
图片批量下载器
↓批量下载图片,美女图库↓
图片自动播放器
↓图片自动播放器↓
一键清除垃圾
↓轻轻一点,清除系统垃圾↓
开发: C++知识库 Java知识库 JavaScript Python PHP知识库 人工智能 区块链 大数据 移动开发 嵌入式 开发工具 数据结构与算法 开发测试 游戏开发 网络协议 系统运维
教程: HTML教程 CSS教程 JavaScript教程 Go语言教程 JQuery教程 VUE教程 VUE3教程 Bootstrap教程 SQL数据库教程 C语言教程 C++教程 Java教程 Python教程 Python3教程 C#教程
数码: 电脑 笔记本 显卡 显示器 固态硬盘 硬盘 耳机 手机 iphone vivo oppo 小米 华为 单反 装机 图拉丁
 
   -> Python知识库 -> python基础知识 -> 正文阅读

[Python知识库]python基础知识

python基础知识
(来源:学习《pthon从入门到实践》一书所做笔记)

文章目录

1变量和简单数据类型

name="ada lovelace"
print(name.title())
print(name.upper())
print(name.lower())
first_name="ada"
last_name="lovelace"
full_name=first_name+" "+last_name
print(full_name)
#空白泛指任何非打印字符,如空格、制表符、换行符

制表符(前面有空格):\t,换行符\n

print("\tpython")
favorite_language='  python '
favorite_language=favorite_language.strip()
print(favorite_language)
age=23
message="Happy "+str(age)+"rd birthday"
print(message)

2学习列表

2.1列表是什么

bicycles=['trek','cannodake','readline','specialized']
print(bicycles)

2.2访问列表元素

bicycles=['trek','cannodake','readline','specialized']
print(bicycles[0])

2.3访问最后一个元素用-1,倒数第二个用-2…

print(bicycles[-1].title())

2.4使用列表中的各个值

message="My first bicycle was a "+bicycles[0].title()+"."
print(message)

2.5修改列表元素

motorcycles=['honda','yamaha','suzuki']
print(motorcycles)
motorcycles[0]='ducati'
print(motorcycles)

2.5.1在列表末尾添加元素

motorcycles.append('ducati')
print(motorcycles)

2.5.2在列表中插入元素

motorcycles=['honda','yamaha','suzuki']
motorcycles.insert(0,'ducati')#在0号位置前面插入
print(motorcycles)

2.5.3从列表中删除元素,如果知道删除元素的位置使用del语句

del motorcycles[0]
print(motorcycles)
2.5.3.1使用pop删除元素
motorcycles=['honda','yamaha','suzuki']
print(motorcycles)
popped_motorcycle=motorcycles.pop(0)
print(motorcycles)
print(popped_motorcycle)
2.5.3.2根据值删除元素remove()
motorcycles.remove('yamaha')
print(motorcycles)

2.6.1使用sort()对列表进行永久性排序

cars=['bmw','audi','toyota','subaru']
cars.sort()
print(cars)

2.6.1向sort()传递参数reverse=True相反顺序排列元素

cars.sort(reverse=True)
print(cars)

2.6.2使用函数sorted()对列表进行临时排序

cars=['bmw','audi','toyota','subaru']
print("Here is the original list:")
print(cars)
print("\nHere is the sorted list:")
print(sorted(cars))
print("\nHere is the original list again:")
print(cars)

2.7倒着打印列表reverse(),确定列表的长度len()

cars=['bmw','audi','toyota','subaru']
print(cars)

cars.reverse()
print(cars)
print(len(cars))

3 操作列表

3.1遍历整个列表for循环

magicains=['dsdjiw','daeic','carolina']
for magicain in magicains:
    print(magicain.title()+",taht was a great trick!")
    print("I can't wait to see your next trick,"+magicain.title()+".\n")
print("Thank you,everyone.That was a great magic show!")

3.2创建数字列表使用range()函数

for value in range(1,3):
    print(value)

3.2.1使用range()创建数字列表

numbers=list(range(1,6))
print(numbers)

#指定步长,打印1~10内的偶数
even_numbers=list(range(2,11,2))
print(even_numbers)

#创建一个列表,其中包含10个整数1-10的平方

squares=[]
for value in range(1,11):
    square=value**2
    squares.append(square)
    
print(squares)   

#对数字列表进行简单的统计计算

digits=[1,2,3,4,5,6,7,8]
print(max(digits))
print(min(digits))
print(sum(digits))

3.3列表解析

squares=[value**2 for value in range(1,11)]
print(squares)

#切片处理列表的部分元素
players=['charles','martina','michal','wsjwi','dwdd','dddwd2']
print(players[0:3])

#遍历切片
players=['charles','martina','michal','wsjwi','dwdd','dddwd2']
print("Here are the first three players on my team:")
for player in players[:3]:
    print(player.title ())

#复制列表
my_foods=['pizza','falafel','carrot cake']
friend_foods=my_foods[:]

print("my favorite foods are:")
print(my_foods)
friend_foods.append('ice cream')

print("\nmy favorite foods are:")
print(friend_foods)

3.4元组 不可变的列表

demensions=(200,5,6)
print(demensions[0])
print(demensions[1])
print(demensions[2])

#遍历元组中所有值
dimensions=(200,2,2)
for dimension in dimensions:
    print(dimension)

#修改元组变量
dimensions=(200,4)
print("Original dimensions:")
for dimension in dimensions:
    print(dimension)

dimensions=(400,100)
print("\nModified dimensions:")
for dimension in dimensions:
    print(dimension)


4 if语句

4.1基本用法

requested_topping='mushrooms'
if requested_topping!='annjid':
    print("hold the annjid")

#使用and 检查多个条件同c语言中的&&
age_0=22
age_1=89
if age_0>20 and age_1<=19:
    print("haa")
else:
    print("heihei")

#使用or 检查多个条件同c语言中的||
#检查特定的值是否不包含在列表中not in
banned_users=['andrew','carolina','david']
user='marie'
if user not in banned_users:
    print(user.title()+",you can post a respons if you wish")

4.2if-elif-else结构:需要检查超过两个的情形

#4岁以下免费;4~18收费5美元;18岁(含)以上收费10美元
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.")

#同理可使用else-elif-elif_elif-else语句检查多个;()可以省略else
#测试多个条件

requested_toppings=['mushrooms','extra cheese']
if 'mushrooms' in requested_toppings:
    print("Adding mushrooms.")
if 'pepperoni' in requested_toppings:
    print("Adding pepperoni.")
if 'extra cheese' in requested_toppings:
    print("Adding extra cheese.")
print ("\nFinished making your pizza!")

4.3使用if语句处理列表

requested_toppings=[]
if requested_toppings:
    for requested_topping in requested_toppings:
        print("Adding"+requested_topping+".")
    print("\nFinisted making your pizza!")
else:
    print ("are you sure you want a plain pizza?")

5 字典{}

5.1基本用法

alien_0={'color':'green','points':5}
print(alien_0['color'])
alien_0={'x_position':0,'y_posion':25,'speed':'medium'}
print("Original x_position:" + str(alien_0['x_position']))
#向右移动外星人·
#据外星人当前速度决定将其移动多远

if alien_0['speed']=='slow':
    x_increment=1
elif alien_0['speed']=='medium':
    x_increment=2
else:
    #这个外星人的速度一定很快

    x_increment=3

#新位置等于老位置加上增量

alien_0['x_position']=alien_0['x_position']+x_increment
print("New x_position:" + str(alien_0['x_position']))
#由类似对象组成的字典

favorite_languages={
        'jen':'python',
        'sarah':'c',
        'edward':'ruby',
        'phil':'python',
        }
print("Sarah's favorite language is " + 
      favorite_languages['sarah'].title() + 
      ".") 

5.2遍历所有键-值对应

user_0={
       'username':'jhdshi',
       'first':'suhb',
       'last':'fermi',
       }
for key,value in user_0.items():
    print("\nKey:" + key)
    print("\nValue:" + value)

#遍历

favorite_languages={
        'jen':'python',
        'sarah':'c',
        'edward':'ruby',
        'phil':'python',
        }
for name,language in favorite_languages.items():
    print(name.title() + "'s favorite language is " + 
          language.title() + ".")

5.3遍历字典中的所有键 方法keys()

favorite_languages={
        'jen':'python',
        'sarah':'c',
        'edward':'ruby',
        'phil':'python',
        }
for name in favorite_languages.keys():
    print(name.title())

5.3.1按顺序遍历字典中的所有键、函数sorted()

favorite_languages={
        'jen':'python',
        'sarah':'c',
        'edward':'ruby',
        'phil':'python',
        }
for name in sorted(favorite_languages.keys()):
    print(name.title() + ",thank you for taking the poll.")

5.3.2遍历字典中的所有值用value()方法,剔除重复项可使用集合set

favorite_languages={
        'jen':'python',
        'sarah':'c',
        'edward':'ruby',
        'phil':'python',
        }

print("The following languages have been mentioned:")
for language in set(favorite_languages.values()):
    print(language.title())

5.4嵌套,将一系列字典储存在列表中

#例子
alien_0={'color':'green','point':5}
alien_1={'color':'yellow','point':10}
alien_2={'color':'red','point':15}
aliens=[alien_0,alien_1,alien_2]
for alien in aliens:
    print(alien)

#创建一个用于储存外星人的空列表
aliens=[]

#创建30个绿色的外星人使用range()
for alien_number in range(30):
    new_alien={'color':'green','point':5,'speed':'slow'}
    aliens.append(new_alien)

#将前三个外星人颜色修改为黄色
for alien in aliens[:3]:
    if alien['color']=='green':
        alien['color']='yellow'
        alien['speed']='medium'
        alien['point']=10
        
#显示前5个外星人
for alien in aliens[:5]:
    print(alien)
print("...")


#显示创建了多少个外星人
print("Total number of aliens: " + str(len(aliens)))

5.5在字典中储存列表

favorite_languages={
        'jen':['python','ruby'],
        'sarah':['c'],
        'edward':['ruby','go'],
        'phil':['python','haskell'],
        }
for name,languages in favorite_languages.items():
    print("\n" + name.title() + "'s favorite languages are:")
    for language in languages:
        print("\t" + language.title())

5.6在字典中储存字典

users = {
    'ifjri':{
        'first':'fef',
        'last':'fefef',
        'location':'ojd',
        },
    'dedf':{
        'first':'fsqf',
        'last':'fefess',
        'location':'ojsd',
        },
        }
for username,user_info in users.items():
    print("\nUsername: " + username)
    full_name = user_info['first'] + " " + user_info['last']
    location = user_info['location']
    print("\tFull name: " + full_name.title())
    print("\tLocation: " + location.title())

6 用户输入和while循环

6.1函数input的工作原理

#函数input()的工作原理
message=input("Tell me something,and I will repeat it back to you:")
print(message)

#提示超过一行,可以将提示储存到变量中

prompt = "If you tell us who you are,we can personalize the message you see."
prompt +="\nWhat is your fir  st name?"

name=input(prompt)
print("\nHello," + name + "!")

使用int()来获取数值输入

height = input("How tall are you,in inches?")
height = int(height)

if height >= 36:
    print("\nYou are tall enough to ride!")
else:
print("\nYou'll be able to ride when you're a little older.")

#求模运算符%返回余数

6.2while循环

#使用标志
prompt="\nTell me something,and I will repeat it back to you:"
prompt += "\nEnter 'quit' to end the program."

#使用标志
prompt="\nTell me something,and I will repeat it back to you:"
prompt += "\nEnter 'quit' to end the program."

active = True
while active:
    message = input(prompt)
    

if message == 'quit':
    active = False
else:
    print(message)
#在列表之间移动元素
#首先创建一个待验证用户列表
#和一个用于储存已验证用户的空列表
unconfirmed_users = ['alice','brian','candance']
confirmed_users = []

#验证每个用户,直到没有未验证用户为止
#将每个经过验证的列表都移动到已验证的列表中
while unconfirmed_users:
    current_user = unconfirmed_users.pop()
    print("Verifying user:" + current_user.title())
    confirmed_users.append(current_user)
    
#显示所有已验证的用户
print("\nThe following users have been confirmed:")
for confirmed_user in confirmed_users:
    print(confirmed_user.title())

7函数

7.1用关键字def定义函数

def describe_pet(animal_type,pet_name):
    """显示宠物信息"""
    print("\nI have a " + animal_type + ".")
    print("My " + animal_type + "'s name is " + pet_name.title() + ".")
    

describe_pet('hamaster','harry')

7.2使用任意数量的关键字实参

def bulid_profile(first,last,**user_info):
**让python创建一个名为user_info的空字典用于储存用户简介

"""创建一个字典其中包括我们知道的有关用户的一切"""
profile = {}
profile['fist_name'] = first
profile['last_name'] = last
for key,value in user_info.items():
    profile[key] = value
return profile

user_profile = bulid_profile(‘abbert’,‘einstein’,
location =‘princeton’,
field=‘physics’)
print(user_profile)

7.3将函数储存在模块中,导入整个模块

def make_pizza(size,*toppings):
    """概述要制作的披萨"""
    print("\nMaking a " + str(size) + 
          "-inch pizza with the following toppings:")
    for topping in toppings:
        print("- " + topping)

7.4使用as给函数或模块指定别名

from module_name import function_name as fn
import module_name as mn

7.5使用*运算符可以让python导入模块中的所有函数

from pizza import*

make_pizza(16'pepperoni')
make_pizza(12,'mushrooms','green peppers','extra cheese')

8 类

class Dog():
    """"一次模拟小狗的简单尝试"""
def __init__(self, name,age):
    """初始化属性name和age"""
    self.name = name
    self.age = age
    
def sit(self):
    """模拟小狗被命令时蹲下"""
    print(self.name.title() + " is now sitting.")

def roll_over(self):
    """模拟小狗被命令时打滚"""
    print(self.name.title() + " rolled over!")
my_dog =Dog('sasz',6)
print("My ndog's name is " + my_dog.name.title() + ".")
print("My dog is " + str(my_dog.age) + "years old.")

8.1继承将获得另一个类的所有属性和方法

#class Otherdog(Dog)
from hhh import ElectricCar
my_tesla = ElectricCar('tesla','model s',2016)
print(my_tesla.get_descriptive_name())
my_tesla.batery.get_range()

read()读取文件全部内容
#逐行读取采用for 循环
filename = 'pi_digits.txt'
with open(filename) as file_object:
    for line in file_object:
        print(line.rstrip())
#创建一个包含文件各行内容的列表
filename = 'pi_digits.txt'
with open(filename) as file_object:
    lines = file_object.readlines()#从文件中读取每一行   
for line in lines:
    print(line.rstrip())
filename = 'pi_digits.txt'
with open(filename) as file_object:
     lines = file_object.readlines()  
pi_string = ''
for line in lines:
    pi_string +=line.rstrip() 
print(pi_string)
print(len(pi_string))
     
#写入空文件,写入多行·
filename = 'programming.txt'
with open(filename,'w') as file_object:
    file_object.write("I love programming.\n")
    file_object.write("I love creating new games.\n")


#附加到文件
filename = 'programming.txt'
with open(filename,'a') as file_object:
    file_object.write("I also love finding in datasets.\n")
    file_object.write("I love creating apps that can run in a browser.\n")

  




9异常处理

9.1处理ZeroDivisionError异常使用try-exceotion代码块

try:
    print(5/0)
except ZeroDivisionError:
    print("You can't divide by zero!")
    
#使用异常避免崩溃
print("Give me two numbers, and I'l divide them")
print("Enter 'q' to quit.")
while True:
    first_number = input("\nFirst number: ")
    if first_number == 'q':
        break
    second_number = input("second number: ")
    if second_number == 'q':
        break
    answer = int(first_number)/int(second_number)
    print(answer)
    

9.2else代码块try-except代码块

print("Give me two numbers,and I'll divide them.")
print("Enter 'q' to quit")

while True:
    first_number = input("\nFirst number: ")
    if first_number =='q': 
        break
    second_number = input("Second number: ")
    try:
        answer = int(first_number)/(second_number)
    except ZeroDivisionError:
        print("You can't divide by 0!")
    else:
        print(answer)
#处理FileNotFoundError异常
filename = 'alice.txt'
try:
    with open(filename) as f_obj:
        contents = f_obj.read()    
except FileNotFoundError:
    msg = "Sorry ,the file " + filename + " does not exist."
    print(msg)

9.3分析文本

9.3.1储存数据使用json.dump()和json.load()

import json

numbers = [2,3,5,7,11,13]

filename = 'number.json'
with open(filename,'w') as f_obj:
    json.dump(numbers,f_obj)

?

9.3.2使用json.load()将这个列表存储到内存中

import json
filename = 'number.json'
with open(filename) as f_obj:
    numbers = json.load(f_obj)  
print(numbers)
#保存和读取用户生成的数据
import json
username = input("What is your name?")
filename ='username.json'
with open(filename,'w') as f_obj:
    json.dump(username,f_obj)
    print("We'll remenber you when you come back, " + username + "!")    
import json   
filename ='username.json'
with open(filename) as f_obj:
    username = json.load(f_obj)
    print("Welcom back," + username + "!")


10测试代码

def get_formatted_name(first,last,middle=''):
    """生成整洁的名字"""
    if middle:
        full_name = first + ' ' + middle + ' ' + last
    else:
        full_name = first + ' ' + last

return full_name.title()

10.1单元测试和测试用例,可通过的测试

一个要测试的类
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_results(self):
        """显示收集到的所有答卷"""
        print("Survey results:")
        for response in self.responses:
            print('-' + response)

       

11笔记说明

一边看书,一边跟着书上的例子跟着边学边敲,便于以后忘记时翻阅。

?

  Python知识库 最新文章
Python中String模块
【Python】 14-CVS文件操作
python的panda库读写文件
使用Nordic的nrf52840实现蓝牙DFU过程
【Python学习记录】numpy数组用法整理
Python学习笔记
python字符串和列表
python如何从txt文件中解析出有效的数据
Python编程从入门到实践自学/3.1-3.2
python变量
上一篇文章      下一篇文章      查看所有文章
加:2022-01-29 23:02:34  更:2022-01-29 23:03:31 
 
开发: C++知识库 Java知识库 JavaScript Python PHP知识库 人工智能 区块链 大数据 移动开发 嵌入式 开发工具 数据结构与算法 开发测试 游戏开发 网络协议 系统运维
教程: HTML教程 CSS教程 JavaScript教程 Go语言教程 JQuery教程 VUE教程 VUE3教程 Bootstrap教程 SQL数据库教程 C语言教程 C++教程 Java教程 Python教程 Python3教程 C#教程
数码: 电脑 笔记本 显卡 显示器 固态硬盘 硬盘 耳机 手机 iphone vivo oppo 小米 华为 单反 装机 图拉丁

360图书馆 购物 三丰科技 阅读网 日历 万年历 2024年11日历 -2024/11/16 1:45:10-

图片自动播放器
↓图片自动播放器↓
TxT小说阅读器
↓语音阅读,小说下载,古典文学↓
一键清除垃圾
↓轻轻一点,清除系统垃圾↓
图片批量下载器
↓批量下载图片,美女图库↓
  网站联系: qq:121756557 email:121756557@qq.com  IT数码