python学习

变量

message = “Hello Python world!”

print(message)

message = “Hello Python Crash Course world!”

print(message)

这样得到的输出是两行不同的输出,每个print都是一个独立的输出。

变量在命名的时候不能将数字作为开头,需要使用下划线(_)来将单词隔开。

字符串

name = “ada lovalace”

print(name)

print(name.title())

#将每个单词的首字母大写Ada Lovalace

print(name.upper())

#将所有的字母都大写

print(name.lower())

#将所有的字母都小写

在合并字符串的时候只要使用“+”就行

first_name = “wang”

last_name = “mengchen”

full_name = =first_name + " " + last_name

#这里在两个加号之间添加了一个空格

print(full_name)

wang mengchen

print("Hello, " + full_name.title() + “!”)

Hello, Wang Mengchen!

#如果加个变量作为中转的话

message = "Hello, " + full_name.title() + “!”

print(message)

#会得到一样的结果

\t#制表符会在输出的前面添加一段空白

print("\thandsome")

print(“handsome”)

            handsome

handsome

\n#换行符会让输出换行

print(“Language:\nPython\nC\nJava”)

Language:

Python

C

Java

#在同一个字符串中可以同时使用制表符和换行符

.rstrip()和.lstrip()

#分别删除字符结尾的空白和字符前面的空白

浮点数:带小数点的数都是浮点数

使用str()函数避免类型错误

age = 23

message = "Happy " + age + “rd Birthday!”

#不能这样输出,因为happy和rd birthday是字符串,但是age不是字符串,所以我们需要将age转换为字符串。

message = "Happy " + str(age) + “rd Birthday!”

#这样就行了

列表

#列表是由一系列按特定顺序排列的元素组成。用方括号([ ])来表示列表,用逗号来分隔其中的元素。

bicycles = [‘trek’ , ‘cannondale’ , ‘redline’ , ‘specialized’]

print(bicycles)

[‘trek’, ‘cannondale’, ‘redline’, ‘specialized’]

#如果想要得到列表中的第一个自行车的话

print(bicycles[0])

trek

#索引是从0开始计数的 在列表中我们也同样可以使用title和upper等操作控制大小写。

#在我们想使用列表中的值得时候可以直接使用

bicycles = [‘trek’ , ‘cannondale’ , ‘redline’ , ‘specialized’]

print("My first bicycle is " + bicycles[0] + “!”)

My first bicycle is trek!

#想要修改列表元素时,直接命名就行

bicycles = [‘trek’ , ‘cannondale’ , ‘redline’ , ‘specialized’]

print(bicycles)

bicycles[0] = ‘giant’

print(bicycles)

[‘trek’, ‘cannondale’, ‘redline’, ‘specialized’]

[‘giant’, ‘cannondale’, ‘redline’, ‘specialized’]

#这个时候列表中的第一个元素已经被修改了

#在列表末尾添加元素使用bicycles.append(giant)

#想要插入元素的话使用insert

bicycles = [‘trek’ , ‘cannondale’ , ‘redline’ , ‘specialized’]

print(bicycles)

bicycles.insert(1, ‘giant’)

print(bicycles)

[‘trek’, ‘cannondale’, ‘redline’, ‘specialized’]

[‘trek’, ‘giant’, ‘cannondale’, ‘redline’, ‘specialized’]

#这样giant就被插入到了列表中的“1”的位置

#从列表中删除元素的话需要使用del语句

bicycles = [‘trek’ , ‘cannondale’]

print(bicycles)

del bicycles[1]

print(bicycles)

[‘trek’, ‘cannondale’]

[‘trek’]

#列表中“1”位置的元素就被删除了

#pop指令可以删除末尾的元素,删除的时候可以通过变量赋值使被移除的元素被储存起来。

bicycles = [‘trek’ , ‘cannondale’]

print(bicycles)

pop_bicycles = bicycles.pop()

print(bicycles)

print(pop_bicycles)

[‘trek’, ‘cannondale’]

[‘trek’]

cannondale

#可以看到cannondale随便被移除了,但是通过中间赋值指令pop_bicycles = bicycles.pop(),被移除的时候得以保存。

#如果在pop()的括号中输入数字,就可以弹出列表中任意位置的元素了。

#根据特定的值删除元素使用.remove()指令。

bicycles = [‘trek’ , ‘cannondale’ , ‘giant’]

print(bicycles)

bicycles.remove(‘giant’)

print(bicycles)

[‘trek’, ‘cannondale’, ‘giant’]

[‘trek’, ‘cannondale’]

组织列表

#方法.sort()对列表会根据首字母进行永久排序,并且没有办法恢复到原来的顺序。

#方法.sort(reverse=True)会根据首字母的相反顺序进行排序。

bicycles = [‘trek’ , ‘cannondale’ , ‘giant’]

print(bicycles)

bicycles.sort()

print(bicycles)

bicycles.sort(reverse=True)

print(bicycles)

[‘trek’, ‘cannondale’, ‘giant’]

[‘cannondale’, ‘giant’, ‘trek’]

[‘trek’, ‘giant’, ‘cannondale’]

#.sorted()可以进行临时排序。在输出print的时候进行print(sorted(bicycles))会临时根据首字母进行排序,但是过后就会恢复。

#bicycles.reverse()会对原有顺序进行倒序。

#len(bicycles)可以获得列表长度。

操作列表

#想要对列表中所有的元素都进行同一个操作的时候,可以用for循环。print前面的缩进表示循环后进行的。 千万不能忘记了缩进。

actors = [‘wang’, ‘zhang’, ‘li’]

for actor in actors:

print(actor.title() + "is a famous actor")

Wangis a famous actor

Zhangis a famous actor

Liis a famous actor

#可以在for循环中加入一些title或其他的指令。

创建数值列表

for value in range(1,4):

print(value)

1

2

3

#range函数中是左闭右开的,直到右边的数就停止。

#使用range创建数字列表的话用list。

numbers = list(range(1,4))

print(numbers)

[1, 2, 3]

#可以通过设置第三个数来设置公差

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

print(numbers)

[1, 3, 5]

#这样就是输出1到5,公差为2.

squares = []

for value in range(1,6):

square = value**2

squares.append(square)

print(squares)

[1, 4, 9, 16, 25]

#min()列表可以找到最小值。max可以找到最大值。sum可以找到列表的总和。

#切片:只打印列表中的某几个元素。

players = [‘kobe’, ‘james’, ‘davis’, ‘paul’]

print(players[1:3])

[‘james’, ‘davis’]

#如果没有开头的话,默认从开头开始。如果没有结尾,默认直到结束。

#在复制列表的时候,需要使用

my_foods = [‘noodles’, ‘ice cream’, ‘humbeger’]

friend_foods = my_foods[:]

#这样得到的my_foods和friend_foods是两个不同的列表,可以分别使用。

#Python将不能修改的值称为不可变的,不可变的列表被称为元组。

#列表使用中括号[],元组使用小括号()。

#虽然不能修改元组中的值,但是我们可以给元组的变量赋值,也就是重新定义元组。

players = (‘kobe’, ‘james’, ‘davis’, ‘paul’)

print("my favorite player is ")

for player in players:

print(player)

players = (‘durant’,‘jordan’)

print("my favorite player is ")

for player in players:

print(player)

kobe

james

davis

paul

my favorite player is

durant

jordan

#这样重新赋值就相当于重新定义了该元组。

IF语句

players = [‘kobe’, ‘james’, ‘davis’, ‘paul’]

for player in players:

if player == 'james':

    print(player.upper())

else:

    print(player.title())

Kobe

JAMES

Davis

Paul

#在判断的时候==表示等于,编程中的!表示不,也就是说!=表示不等于。

#检查条件时,注意区分大小写。

#检查条件时,and相当于“与”门,必须所有条件都是ture才输出ture,否则为false。

#or相当于“或”门,只要有一个条件的结果是ture,那么输出的结果就是ture。

#if-elif-else结构

#根据年龄段收费的游乐场

#四岁以下免费

#4~18岁收费¥20

#18岁(含)以上收费¥40

age = 14

if age < 4:

print('Your admission cost is 0')

elif age < 18:

print('Your admission cost is ¥20')

else:

print('Your admission cost is ¥40')

Your admission cost is ¥20

#如果没有通过if中的条件,就会执行elif中的条件,如果还是没有通过,就会执行else中的语句。

#可以同时使用多个elif代码块。

nanrenmen = [‘wangmengchen’, ‘wangjiayi’, ‘wangzhicheng’ ,‘zhaozikang’]

for nanren in nanrenmen:

if nanren == 'wangjiayi':

    print(nanren + " is a bad person

    !")

else:

    print(nanren + " is a handsome man!")

wangmengchen is a handsome man!

wangjiayi is a bad person!

wangzhicheng is a handsome man!

zhaozikang is a handsome man!

#在if语句中插入for循环。

#字典是一系列键-值对。每个键都与一个值相关联。字典可以包含任意个键-值对,也可以随时在其中添加键-值对。

aline_0 = {‘x_position’:0,‘y_position’:25,‘speed’:‘medium’}

print('Original position is ’ + str(aline_0[‘x_position’]) + ‘.’)

if aline_0[‘speed’] == ‘low’:

x_add = 1

elif aline_0[‘speed’] == ‘medium’:

x_add = 2

else:

x_add = 3

aline_0[‘x_position’] = aline_0[‘x_position’] + x_add

print("Now,the position is " + str(aline_0[‘x_position’]) + ‘.’)

Original position is 0.

Now,the position is 2.

#由类似对象组成的字典,可以事先设定好了再进行使用。

women = {‘jiayi’:‘chaiyutong’,‘chengzi’:‘gougou’,‘qiaoqiao’:‘zhuzhu’,‘nanshen’:‘zhangtianai’}

print("wangjiayi’s lover is " + women[‘jiayi’] + ‘!’)

print("chengzi’s lover is " + women[‘chengzi’] + “!”)

print("qiaoqiao’s lover is " + women[‘qiaoqiao’] + “!”)

print("nanshen’s lover is " + women[‘nanshen’] + “!”)

wangjiayi’s lover is chaiyutong!

chengzi’s lover is gougou!

qiaoqiao’s lover is zhuzhu!

nanshen’s lover is zhangtianai!

#在for循环中使用字典的时候应该做到对应,使用A,B的方法,对应“字典.items()”,进行循环。

men = {

'zhaozikang' : 'zhanan',

'wangzhicheng': 'yibannanren',

'wangjiayi' : 'haonanren',

'wangmengchen' : 'nanshen'

}

for name,adj in men.items():

print("I'm " + name + ',' "I'm a " + adj + "!")

I’m zhaozikang,I’m a zhanan!

I’m wangzhicheng,I’m a yibannanren!

I’m wangjiayi,I’m a haonanren!

I’m wangmengchen,I’m a nanshen!

#遍历字典中的所有键,“字典.keys()”

#遍历字典中的所有值,“字典.value()”

#set(字典)是可以提取字典中所有不重复的元素。

嵌套

#可以做个嵌套,将三个字典嵌套进一个列表中,这个列表里的三个值分别是三个字典。

#也可以在字典中使用列表

players = {

'men':['kobe','james'],

'woman':'dengyaping',

}

print('my favorite ping-pong player is ’ + players[‘woman’])

print('i like two basketball players, the list is ')

for man in players[‘men’]:

print('\t' + man)

my favorite ping-pong player is dengyaping

i like two basketball players, the list is

    kobe

    james

#用户输入,input()将用户输入解读为字符串,int()将用户输入解读为数值。

age = input(‘How old are you?’)

age = int(age)

if age <18:

print('Sorry, you are not allowed to enter the room!')

else:

print('Okay,you can go!')

How old are you?25

Okay,you can go!

#在while循环中加入输入指令

message = “Please tell me a number and I will repeate it back to you.”

message += ‘If you want to quit,please tell me quit.’

number = ‘’

while number != ‘quit’:

number = input(message)

if number != 'quit':

    print(number)

Please tell me a number and I will repeate it back to you.If you want to quit,please tell me quit.22

22

Please tell me a number and I will repeate it back to you.If you want to quit,please tell me quit.quit

#因为加了if语句,这样在输入“quit”的时候就不会打印“quit”了。

#在要求很多条件都满足才能继续运行的程序中,可定义一个变量,用于判断整个程序是否处于活动状态。这个变量被称为标志,充当了程序的交通信号灯。例如active = True 这样while会一直循环直到一个条件使active = False。

#使用break语句会立刻退出while循环。

#continue语句会忽略剩下的代码,直接回到while的开头。

number = 0

while number <=10:

number += 1

if number % 2 == 1:

    continue

print(number)

2

4

6

8

10

#在while循环中结合字典使用。

response = {}

active = True

while active:

name = input("\nWhat's your name?")

mountain = input("Which mountain would you want to climb?")

response[name] = mountain

person = input("Is here somebody else want to answer the question?")

if person == 'no':

    break

print("----------")

for name,mountain in response.items():

print(name + 'wants to climb ' + mountain + '.')

What’s your name?wangmengchen

Which mountain would you want to climb?xishan

Is here somebody else want to answer the question?yes

What’s your name?wanglihong

Which mountain would you want to climb?zhumulangmafeng

Is here somebody else want to answer the question?no


wangmengchenwants to climb xishan.

wanglihongwants to climb zhumulangmafeng.

#函数:带名字的代码块,用于完成具体的工作。

#函数定义,位置实参(顺序很重要)

def greet_user(username , the_talk):

"""给用户一个简单的问好"""

print('\n' + the_talk + '.')

print(username.title() + '!')

greet_user(‘wangmengchen’ , ‘Hello’)

greet_user(‘wanglihong’ , ‘You are handsome’)

Hello.

Wangmengchen!

You are handsome.

Wanglihong!

#在这段代码中,nusername是一个形参,wangmengchen是一个实参,实参是屌用函数时传递给函数的信息。

#向函数传递实参的方式有很多种,可以使用位置参数,但这要求实参的顺序与形参的顺序相同;也可以使用关键字实参,其中每个实参都由变量名和值组成;还可以使用列表和字典。

#关键字实参

def greet_user(username , the_talk):

"""给用户一个简单的问好"""

print('\n' + the_talk + '.')

print(username.title() + '!')

greet_user(username=‘wangmengchen’ , the_talk=‘Hello’)

Hello.

Wangmengchen!

#函数并非总是直接显示输出,相反,它可以处理一些数据,并返回一个火一组值。函数返回的值被称为返回值。

def full_name(first_name,last_name,middle_name=’’):

"""打印人的全名"""

if middle_name:

    name = first_name + ' ' + middle_name + ' ' +last_name

else:

    name = first_name + ' ' + last_name

return name #这里return的作用是什么

musician = full_name(‘LeBron’,‘James’)

print(musician)

musician = full_name(‘1’,‘2’,‘3’)

print(musician)

LeBron James

1 3 2

#将字典与函数想结合

def full_message(first_name,last_name,age=’’):

""""显示一个人的资料"""

person={'first':first_name,'last':last_name}

if age:

    person['age'] = age

return person

one = full_message(“lihong”, ‘wang’, age=27)

print(one)

{‘first’: ‘lihong’, ‘last’: ‘wang’, ‘age’: 27}

#将while循环和函数结合起来

def full_message(first_name,last_name,age=’’):

""""显示一个人的资料"""

full_name = first_name + ' ' + last_name

return full_name

while True:

print('\nPlease tell me your name:')

print('(You can enter "q" to quit anytime.)')

f_name = input("First name:")

if f_name == 'q':

    break

l_name = input("Last name:")

if l_name == 'q':

    break

name = full_message(f_name,l_name)

print("\nHello, " + name.title() + '!')

print('You are handsome!')

Please tell me your name:

(You can enter “q” to quit anytime.)

First name:mengchen

Last name:wang

Hello, Mengchen Wang!

You are handsome!

Please tell me your name:

(You can enter “q” to quit anytime.)

First name:

#传递任意数量的实参,如果事先不知道有多少个实参,那就使用“*toppings”星号来解决

#星号让python创建了一个名为toppings的空元组,并将收到的所有值都封装到这个元组里

#结合使用位置实参和任意数量实参

def make_pizza(size,*toppings):

"""概述要制作的披萨"""

print("\nMaking a " + str(size) + "-inch pizza with the following toppings:")

for topping in toppings:

    print("- " + topping)

make_pizza(7,‘pork’,‘apple’)

make_pizza(9,“beef”,“orange”)

Making a 7-inch pizza with the following toppings:

  • pork

  • apple

Making a 9-inch pizza with the following toppings:

  • beef

  • orange

#根据类来创建对象被称为实例化,这让那个我们能够使用类的实力。

#下面将编写一个表示小狗的简单类Dog——它表示的不是特定的小狗,而是任何小狗。

#类中的函数被称为方法。在python中,首字母大写的就是类。

class Dog():

"""一次模拟小狗的简单尝试"""

def __init__(self,name,age):

    """初始化属性name和age"""

    self.name = name

    self.age = age

def sit(self):

    """模拟小狗被命令时蹲下"""

    print(self.name.title() + " now is sitting.")

def roll_over(self):

    """模拟小狗被命令时打滚"""

    print(self.name.title() + ' rolled over!')

my_dog = Dog(‘willian’,5)

print("My dog’s name is " + my_dog.name.title() + ‘.’)

print('My dog is ’ + str(my_dog.age) + " years old.")

my_dog.sit()

#在创建Dog.()实例的时候,通过实参向Dog传递姓名和年龄,self会自动传递。在这个方法定义汇总,self必不可少。以self为前缀的变量都可供类中的所有方法使用。

class Dog():

"""一次模拟小狗的简单尝试"""

def __init__(self,name,age):

    """初始化属性name和age"""

    self.name = name

    self.age = age

def sit(self):

    """模拟小狗被命令时蹲下"""

    print(self.name.title() + " now is sitting.")

def roll_over(self):

    """模拟小狗被命令时打滚"""

    print(self.name.title() + ' rolled over!')

#想要修改属性的值:直接通过实例进行修改;通过方法进行设置;通过方法进行递增(增加特定的值)。

#如果将要编写的类是另一个现成类的特殊版本,可使用继承。一个类继承另一个类时,它将自动获得另一个类的所有属性和方法;原有的类称为父类,而新类称为子类。

#创建子类的时候父类必须在当前文件中,且位于子类前面。定义子类时,必须在括号内指定父类的名称,使用方法__init__()接受创建Car实例所需的信息。super()是一个特殊函数,帮助python将父类和子类连接起来,这行代码让python屌用ElectricCar的父类的方法__init__(),让ElectricCar实例包含父类的所有属性。 注:父类也称为超类。

#从一个模块中导入多个类

from car import Car, ElectricCar

#用逗号将多个类隔开

#如果想要导入整个模块的话就直接用import

import car

#引入文件,使用方法read()读取这个文件的全部内容,并将其作为一个长长的字符串存储在contents中。

with open(‘123.txt’) as file_object:

contents = file_object.read()

print(contents)

#在打开一个文件的时候,必须要保证这个人间和程序的目录是同一级目录。

#但是这样输出的时候末尾会有一个空白,是因为read()到达文件末尾时返回一个空字符串,而将这个空字符串显示出来时就是一个空行。要删除末尾的空行,需要在print语句中使用rstrip()

#如果目标文件和程序不在同一级目录中,我们需要使用绝对路径。

with open(‘E:\QQMusic\resae\soundbox3_match’)

#创建一个包含文件各行内容的列表

#readlines()方法从文件中读取每一行

#在文件中写入内容:写入模式’w’、读取模式‘r’、附加模式‘a’、能够读取和写入文件的模式‘r+’。如果忽略模式实参,python默认为只读模式打开文件

#其中写入模式会覆盖,如果想要添加内容,需要使用附加模式。

#如果程序运行的时候可能面临错误的风险,就使用try、except和else进行处理。

#.split()可以将以空格为分隔符的字符串分拆成多个部分,并将这些部分存储到一个列表中。

#进行存储数据的时候需要使用模块json来存储数据。

#首先导入模块json,然后创建一个列表,将该文件以写入模式打开,然后存储一组数字的简短程序用的是json.dump()。而将这些数字读取到内存中的程序就用json.loud()。

# python三目运算符
b= 0
a= b if b==0 else -1
print(a)
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值