python入门

一、变量和简单数据类型

1.1运行hello world

print("Hello python world!")

1.2变量

添加一个变量

massage = "Hello python world!"
print(massage)

1.2.1变量的命名和使用
变量名只能包含字母、数字和下划线。

  • 变量可以命名为message_1,但不能是1_message
  • 变量名不能包含空格 greeting_message 可以 greeting message 不行

1.3字符串
可以用单引号也可以用双引号

"This is a string."
'This is also a string.'

1.3.1使用方法修改字符串的大小写

name = "ada lovelace"
print(name.title())
方法功能
title()首字母大写
upper()全部大写
lower()全部小写

1.3.2合并字符串

python用+来合并字符串

first_name ="ada"
last_name="lovelace"
full_name=first name+" "+last name
print(full_name)
print("Hello, "+full_name.title()+"!")

1.3.3使用制表符或换行符来添加空白

print("\tpython")
	python
\n换行

删除空白

方法功能
rstrip()剔除字符串末尾空白
lstrip()剔除字符串开头空白
strip()剔除字符串首尾空白
favorite_language=' python '
favorite_language.rstrip()
' python'

1.4数字
1.4.1整数

2+3=5
2*3=6
2**3=8 //**表示乘方运算

1.4.2浮点数

0.1+0.2=0.3

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

age = 23
message = "Happy "+str(age)+"rd Birthday!"
print(message)

如果不用str的话,那么输出就会报错,因为python不清楚到底是23还是2和3

1.4.4 python之禅
在Python终端执行import this
在这里插入图片描述
python代码的指导原则

二、列表简介
2.1列表
列表由一系列按特定顺序排列的元素组成。用[]表示列表,用逗号分隔其中的元素。

bicycles=['trek','cannondale','redline']
print(bicycles)

结果为

['trek','cannodale','redline']

2.1.1访问列表元素

bicycles=['trek','cannondale','redline']
print(bicycles[0])

结果为

trek

记住:索引是从0而不是从1开始的

三、操作列表
3.1遍历整个列表

magicians = ['alice','david','carolina']
for magician in magicians:
print(magician)

结果为

alice
david
carolina

3.1.1深入研究循环

for cat in cats:
for dog in dogs:

3.1.2在for循环中执行更多的操作

magicians = ['alice','david','carolina']
for magician in magicians:      //这里的冒号一定不要遗忘哦
    print(magician.title()+",that was a great trick!")

只要print缩进了,因此它们都将针对列表的每位魔术师执行一次,
第一二三次迭代的抬头分别为 Alice David Carolina

3.1.3在for循环结束后执行一些操作

magicians = ['alice','david','carolina']
for magician in magicians:
    print(magician.title()+",that was a great trick!")
print("Thank you.")

那么Thank you只会在最后出现一次

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

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

结果为:

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

结果为

[1,4,9,16,25,36,49,64,81,100]

3.5元组
不可变的列表称为元组

第四章 if语句
4.1 if语句

if conditional_test:
	do something
age = 19
if age>=18:
	print("You are old enough to vote!")

4.2if else 语句

age = 17
if age>=18:
	print("you are old enough to vote.")
else:
	print("sorry.")

4.3 if-elif-else结构

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.")

4.4 省略else代码块

age =12
if age<4:
	price = 0
elif age<18:
	price = 5
elif age<65:
	price=10
elif age >=65:
	price=5
print(Your admission cost is $"+str(price)+".”)

4.5测试多个条件
if-elif-else结构功能强大,但仅适合用于只有一个条件满足的情况,遇到通过了的测试后,Python就会跳过余下的测试。当必须检查所有条件时,应用一系列不包含elif和else代码块的简单if语句。

requested_toopings=['mushrooms','extra cheese']
if'mushirooms' in requested_toppings:
	print("adding mushrooms.")
if"pepperoni' in requested_toppings:
	print("adding pepperoni.")
if'cheese' in requested_toppings:
	print("adding cheese.)
adding mushrooms.
adding pepperoni.
addomg cheese.

4.6检查特殊元素

requested_toppings=['mushrooms','green peppers','cheese']
for requested_topping in requested_toppings:
	print("adding "+requested_topping+".")

结果为:

adding mushrooms.
adding green peppers.
adding cheese

第五章 字典
5.1一个简单的字典

aline_0 = {'color':'green','points':5}
print(alien_0['color'])
print(alien_0['points'])

结果为

green
5

第六章 用户输入和while循环
6.1函数Input()的工作原理
函数input()让程序暂停运行,等待用户输入一些文本。获取用户输入后,python将其存储在一个变量中,以方便使用。

name = input("please enter your name: ")
print("hello, "+name+"!")

运行区:
在这里插入图片描述
6.1.1使用int()来获取数值输入
在Python解释器里
在这里插入图片描述
如果不加

age = int(age)这一行 就会报错 因为系统不知道20是一个数字还是2和0

6.2while循环简介

6.2.1使用while循环
current_number = 1
while current_number <= 5:
	print(current_number)
	current_number += 1

6.2.1让用户选择何时退出

prompt = "n\Tell me something ,and i will repeat it back to you:"
prompt+= "n\Enter 'quit' to end the program."
message = ""                                         
while message != 'quit':
    message = input(prompt)
    print(message)

当输入quit时,循环才结束

6.2.2使用标志
在前一个示例中,我们让程序在满足指定条件时就执行特定任务。但在更复杂的程序中,很多不同的事件都会导致程序停止运行。
在要求很多条件都满足才继续运行的程序中,可定义一个变量,用于判断整个程序是否处于活动状态,这个变量被称为标志。

prompt = "n\Tell me something ,and i will repeat it back to you:"
prompt+= "n\Enter 'quit' to end the program."
active = True
while active:
    message = input(prompt)
    if message == 'quit':
        active = False
    else:
        print(message)

第七章 函数
7.1定义函数

def greet_user():
   print("Hello!")
greet_user()              //调用函数

7.1.1向函数传递信息

def greet_user(username):
	print("Hello, "+username.title()+"!")
greet_user('萌哒哒的CXY')

结果:

Hello, 萌哒哒的Cxy!

7.1.2实参和形参
前面定义函数greet_user时,要求给变量username指定一个值,调用这个函数并提供这种信息(人名)
username 是一个形参
萌哒哒的CXY是实参

7.2传递实参
向函数传递实参的方式很多,可使用位置实参,这要求实参的顺序与形参的顺序相同,也可使用关键字实参。
7.2.1位置实参

def describe_pet(animal_type,pet_name):
    print("\nI hava a "+animal_type+".")
    print("Its name is "+pet_name+".")
describe_pet('cat','coco')

结果为
在这里插入图片描述

7.2.2关键字实参
关键字实参是传递给函数的名称——值对。你直接在实参中将名字和值关联起来了,因此向函数传递实参不会混淆。关键字实参让你无须考虑函数中实参的顺序,还清楚地指出了函数调用中各个值的用途。

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(animal_type='cat',pet_name='coco')

7.2.3默认值
编写函数时,可以给每个形参指定默认值。在调用函数中给形参提供了实参时,python将使用指定的实参值,否则,将使用形参的默认值。因此,给形参指定默认值值后,可在函数调用中省略相应的实参。

def describe_pet(pet_name,animal_type='cat'):
	print("\nI have a"+animal_type+".")
	print("My "animal_type+"'s name is"+pet_name.title()+".")
describe_pet(pet_name='coco')

调用这个函数时,如果没有给animal_type指定值,Python将把这个形参值设为cat

但是如果给animal_type提供了实参,那么python将会忽略这个形参的默认值。

7.3返回值
函数并非总是直接显示输出,相反,它可以处理一些数据,并返回一个或一组值。函数返回的值被称为返回值。在函数中,可使用return 语句将值返回到调用函数的代码行,返回值将程序大部分工作移动到函数中完成,从而简化程序。
7.3.1返回简单值

def get_formatted_name(first_name,last_name):
    full_name = first_name+' '+last_name
    return full_name.title()
musician = get_formatted_name('jimi','hendrix')
print(musician)

调用返回值时,需要提供一个变量用于存储返回的值。在这里,将返回值存储在了变量musician中,输出完整的姓名 Jimi Hendrix

7.3.2让实参变为可选的
并非所有人都有中间名,如何让中间名变为可选的

def get_formatted_name(first_name,last_name,middle_name=''):
    if middle_name:
        full_name=first_name+' '+middle_name+' '+last_name
    else:
        full_name=first_name+' '+last_name
    return full_name.title()
musician = get_formatted_name('jimi','hendrix')
print(musician)
musician = get_formatted_name('john','hooker','lee')
print(musician)

7.3.3结合使用函数和while
下面结合函数和while循环

def get_formatted_name(first_name,last_name):
    full_name = first_name+' '+last_name
    return full_name.title()
while True:
    print("\nPlease tell me your name:")
    f_name = input("First name: ")
    l_name = input("Last name: ")
    formatted_name = get_formatted_name(f_name,l_name)
    print("\nHello, "+formatted_name+"!")

其中while循环让用户输入姓名:依次提示用户输入名和姓
但是这个while循环存在一个问题,没有定义退出条件,因此每次提示用户输入时,都应该提供退出途径,每次提示用户输入时,都使用break语句提供了退出循环的简单途径:

def get_formatted_name(first_name,last_name):
    full_name = first_name+' '+last_name
    return  full_name.title()
while True:
    print("\nPlease tell me your name:")
    print("(enter 'q' at any time to quit)")
    f_name = input("First name: ")
    if f_name == 'q':
        break
    l_name = input("Last name: ")
    if l_name == 'q':
        break
    formatted_name = get_formatted_name(f_name,l_name)
    print("\nHello, "+formatted_name+"!")

7.4传递列表
假设有一个用户列表,我们要问候其中的每位用户,下面的示例将一个名字列表传递给一个名为greet_users()的函数,这个函数问候列表中的每个人:

def greet_users(names):
    for name in names:
        msg = "Hello, "+name.title()+"!"
        print(msg)
usernames = ['hannah','ty','margot']
greet_users(usernames)

我们将greet_users()定义成接受一个名字列表,并将其存储在形参names中,这个函数遍历收到的列表usernames,然后用greet_users()调用它,就可以实现对其中的每位用户都打印一条问候语。

7.5传递任意数量的实参
有时候,预先不知道函数需要接受多少个实参,好在Python允许函数从调用语句中收集任意数量的实参。
例如,制作披萨的函数,它需要接受很多种配料,但是你无法预先确定顾客要多少中配料,下面的函数只有一个形参*toppings,但是不管提供多少种实参,这个形参都可以将它们收入囊中。

def make_pizza(*toppings):
    print(toppings)
make_pizza('pepperoni')
make_pizza('mushrooms','green peppers','cheese')

形参名为*toppings中的星号让Python创建一个名为toppings的空元组,并将收到的所有值都封装到这个元组中,函数体内的print语句通过生成输出来证明Python能够处理使用一个值调用函数的情形,也能处理使用三个值来调用函数的情形。

def make_pizza(*toppings):
    print("\nMaking a pizza with the following toppings:")
    for topping in toppings:
        print("- "+topping)
make_pizza('peperoni')
make_pizza('mashrooms','green pappers','cheese')

不管函数收到的实参是多少个,这个函数都能妥善的处理
结果为:

Making a pizza with the following toppings:
- peperoni

Making a pizza with the following toppings:
- mashrooms
- green pappers
- cheese

7.6 将函数存储在模块中
函数的优点之一是,使用它们可以将代码块与主程序分离。还可以更进一步,将函数存储在被称为模块的独立文件中,再将模块导入到主程序中。import语句允许在当前运行的程序文件中使用模块中的代码。

7.6.1导入整个模块
首先要创建一个模块,下面来创建一个包含函数make_pizza()的模块。
新建一个py文件

def make_pizza(*toppings):
    print("\nMaking a pizza with the following toppings:")
    for topping in toppings:
        print("- "+topping)

python读取这个文件时,代码行import pizza让Python打开文件pizza.py,并将其中的所有函数都复制粘贴到这个程序中。要调用被导入的模块中的函数,可指定导入的模块名词pizza和函数名make_pizza(),并用句点分隔它们。

import pizza
pizza.make_pizza('pepperoni')
pizza.make_pizza('mushrooms','green peppers','cheese')

这些代码的输出与没有导入模块的原始程序相同:

Making a pizza with the following toppings:
- pepperoni

Making a pizza with the following toppings:
- mushrooms
- green peppers
- cheese

7.6.2使用as给函数指定别名
如果要导入的函数的名称可能与程序中现有的名称冲突,可指定简短的别名,类似于外号。用…as…语句来实现。

from pizza import  make_pizza as p
p('pepperoni')
p('mushrooms','green peppers','cheese')

7.6.3用as给模块指定别名
用import…as…语句

import pizza as p
p.make_pizza('pepperoni')
p.make_pizza('mushrooms','green peppers','cheese')

7.6.4导入模块中的所有函数
用from…import * 语句

from pizza import  *
make_pizza('pepperoni')
make_pizza('mushrooms','green peppers','cheese')

通过名称来调用每个函数,如果模块中有函数重名的情况,python会覆盖函数而不是分别导入所有函数,所以要避免重名。

第八章 类

python是面向对象编程,在面向对象编程中,编写的表示现实世界中的实物和情景的类,并基于这些类创建对象。编写类时,定义一大类对象都有的通用行为。基于类创建对象时,每个对象都自动具备这种通用行为,然后根据需要赋予每个对象独特的个性。

根据类来创建对象被称为实例化。

8.1创建和使用类
使用类几乎可以模拟任何东西,下面来编写一个表示小狗的简单类Dog——它表示的不是特定小狗,而是任何小狗。对于大多数宠物狗,都有名字和年龄,还能蹲下和打滚。由于大多数小狗都具备上述两项信息(名字和年龄)和两种行为(蹲下和打滚),我们的Dog类将包含它们,这个类让python知道如何创建表示小狗的对象,编写这个类后,我们将使用它来创建表示特定小狗的实例。

8.1.1创建Dog类
根据Dog类创建的每个实例都将存储名字和年龄。我们赋予了每条小狗蹲下(sit())和打滚(roll_over)的能力:

class Dog():
    def __init__(self,name,age):
        """初始化属性name和age"""
        self.name = name
        self.age = age
    def sit(self):
        """模拟小狗被命令时蹲下"""
        print(self.name.title()+" is now sittting.")
    def roll_over(self):
        print(self.name.title()+" rolled over!")

解释一下上面的代码:

(1)先定义一个名为Dog的类:

class Dog():

在python中,首字母大写的名称指的是类。这个类定义的括号是空的,因为我们要从空白创建这个类。然后编写了一个文档字符串,对这个类的功能作了描述。

(2)方法__init__

 def __init__(self,name,age):

类中的函数称为方法。开头和末尾各有两个下划线,这是一种约定,避免Python默认方法与普通方法发生名称冲突。
将方法__init__()定义了包含三个形参:self、name和age。在这个方法的定义中,形参self必不可少,还必须位于其他形参的前面。

为什么要包含形参self?
因为python调用这个__init__()方法来创建Dog实例时,将自动传入实参self。每个与类相关联的方法调用都自动传递实参self,它是一个指向实例本身的引用,让实例能够访问类中的属性和方法。我们创建Dog实例时,python调用这个__init__()方法来创建实例时,将自动传入实参self。每个与类相关联的方法调用都自动传递实参self,它是一个指向实例本身的引用,让实例能够访问类中的属性和方法。

(3)属性

 self.name = name
 self.age = age

name和age这两个变量都有前缀self,以self为前缀的变量都可供类中的所有方法使用,我们还可以通过类中的任何实例来访问这些变量。
self.name = name获取存储在形参name中的值,并将其存储到变量name中。这样可通过实例访问的变量称为属性。
也就是说,在方法中要访问变量,就要在变量前面加self

(4)sit()和roll_over()
Dog类还定义了另外两个方法:sit()和roll_over()。由于这些方法不需要额外的信息,如名字或年龄,因此它们只有一个形参self。
sit()和roll_over()所做的有限,它们只是打印一条消息,指出小狗正蹲下或打滚。

8.1.2 根据类创建实例

下面来创建一个表示特定小狗的实例:

class Dog():
    def __init__(self,name,age):
        self.name = name
        self.age = age
my_dog = Dog('coco','6')
print("My dog's name is "+my_dog.name+".")
print("My dog is "+my_dog.age+" years old.")

运行结果:
在这里插入图片描述

在这个实例中,首先定义名为Dog的类:

class Dog():

然后使用Dog类中的方法,创建一个表示特定小狗的示例:

def __init__(self,name,age):

接着设置属性name和age:

       self.name = name
        self.age = age

然后,我们让python创建一条名为coco的狗,并使用提供的值来设置属性name和age。我们将这个实例变量存储在变量my_dog中,即:

my_dog = Dog('coco')

之后就可以打印了:

print("My dog's name is "+my_dog.name+".")
print("My dog is "+my_dog.age+" years old.")

这里面 my_dog.name和my_dog.age是访问属性。
访问属性就是用的句点法,即:

my_dog.name
my_dog.age

python先找到实例my_dog,再查找与这个实例相关联的属性name。

  • 66
    点赞
  • 206
    收藏
    觉得还不错? 一键收藏
  • 34
    评论
评论 34
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值