Python教程笔记----6小时完全入门

学习所看的视频来源于B站,授课老师:Mosh Hamedani老师

视频网址:python教程2019版 6小时完全入门 并且达到能开发网站的能力 目前最好的python教程 (含中文翻译)_哔哩哔哩_bilibili

目录

一、执行Python代码

第一个程序

 第二个程序

二、知识点

(一)转换变量类型

(二)引号

1、单引号、双引号

2、三引号

(三)取值

(四)定义参数

(五)大小写

         (六)find()、replace()

(七)字符串中是否包含‘Python’?

         (八)基础运算

(九)数学函数

(十)语句

(十一)逻辑运算符  (and  or  not)

              比较运算符(>  <  >=  <=  ==  !=)

实践一  体重单位 磅 和 千克 的转化器

 (十二)while 循环

实践二 猜谜游戏

实践三 汽车开车

(十三)for 循环

练习  (计算购物车中所有商品的总成本)

(十四)嵌套循环

练习1 打印出多维数组

练习2(编写程序打印出下列图像)

(十五)列表

练习(编写程序找出列表中最大的数)

(十六)插入  .append()     .insert() 

(十七)删除  del    .remove()   .clear()    .pop()

(十八)排序  .sort()    .reverse()

(十九)查询索引index()   列表中某元素的个数count()

(二十)浅拷贝.copy()

练习(写一个程序,删除我们列表上的副本(重复项))

(二十一)矩阵

(二十二)元组

(二十三) 字典

练习1(将输入的号码(数字)翻译成英文打印出来)

练习2(表情包转换器1)

(二十四)函数function

函数中定义参数 

返回函数 return()

练习(表情转换器(2))

(二十五)怎么处理错误?

​ 进行错误处理后 (try expect)

 0在除法中的错误(zero division error)

(二十六) 类

构造函数 

练习(定义一个名为person的新类型,这些person对象应该有一个name属性和一个对话方法)

(二十七)Python的继承

(二十八)Python的模块

 练习(创建一个find_max函数:获取一个列表,并返回最大值max放在模块utils中,并调用使用)

(二十九) Python 的包

 导入包中模块

(三十) python里的标准库

random.py 生成随机值

练习(得到两个随机值的元组) (类:dice    函数:roll)

(三十一)使用目录

三、实践

(一)如何安装来自pypi.org的软件包:

 (二)如何使用Excel文件


一、执行Python代码

  1. 打开pycharm编辑器
  2. 新建一个Python file
  3. 命名文件
  4. 编程
  5. 运行:编辑完后Ctrl+'s'保存,然后右击鼠标run这个文件

变量:整数、浮点、字符串、布尔值

第一个程序

name=input('what is your name? ')
print('Hi '+name)

 第二个程序

字符串不能和整数、浮点数直接运算

birth_year=input('birth year: ')
age = 2019 - birth_year
print(age)

Python教程笔记----6小时完全入门_第1张图片

二、知识点

(一)转换变量类型

整数      int()

浮点型  float()

布尔值  bool()

1.

birth_year=input('birth year: ')
age = 2019 - int(birth_year)
print(age)
birth year: 2001
18

2.

weight_kg=input('weight(kg): ')
weight_lbs=int(weight_kg)/0.45
print(weight_lbs)
weight(kg): 46
102.22222222222221

(二)引号

1、单引号、双引号

course1="python's course for beginners"
course2='python for "beginners"'
print(course1)
print(course2)
python's course for beginners
python for "beginners"

2、三引号

打印多行

course='''
Hi John,

here is our first email to you.

thank you,
the support team
'''
print(course)
Hi John,

here is our first email to you.

thank you,
the support team

(三)取值

course='python for beginners'
print(course[0])#正取值
print(course[-1])#逆取值
print(course[0:3])
print(course[0:8:2])#隔空取值
print(course[8:0:-1])#逆向隔空取值
print(course[:])#拷贝
print(course[0:])
print(course[0:len(course)])
p
s
pyt
pto 
of nohty
python for beginners
python for beginners
python for beginners

(四)定义参数

first="john"
last="smith"
massage=first+' ['+last+'] is a corder'
msg=f'{first} [{last}] is a corder'
print(massage)
print(msg)
john [smith] is a corder
john [smith] is a corder

(五)大小写

course="Python for Beginners"
print(course.upper())
print(course.lower())
print(course.title())
PYTHON FOR BEGINNERS
python for beginners
Python For Beginners

(六)find()、replace()

course="Python for Beginners"
print(course.find('P'))  #0
print(course.find('o'))  #4
print(course.find('0'))  #-1
print(course.find('Beginners'))  #11
print(course.replace('Beginners','Absolute Beginners'))  #Python for Absolute Beginners

(七)字符串中是否包含‘Python’?

print('Python'in course)  #True

(八)基础运算

print(10+3)  #13
print(10-3)  #7
print(10*3)  #30
print(10**3)  #1000
print(10/3)  #3.3333333333333335
print(10//3)  #3
print(10%3)  #1

(九)数学函数

四舍五入 round()              绝对值abs()                   .ceil()                    .floor()

print(round(2.9))  #3
print(round(2.4))  #2
print(abs(-2.9))  #2.9
import math              #导入数字模块
print(math.ceil(2.9))  #3
print(math.floor(2.9))  #2

(十)语句

练习1:实现下面文本要求

Python教程笔记----6小时完全入门_第2张图片

代码:

is_hot=False
is_cold=False
if is_hot:
    print('today is hot day')
    print('drink plenty of water')
elif is_cold:
    print('today is cold day')
    print('wear warm clothes')
else:
    print('today is lovely day')
print('Enjoy your day')

 练习2:实现下面文本要求

Python教程笔记----6小时完全入门_第3张图片

solution

price=1000000
has_good_credit = True
if has_good_credit:
    down_payment=price*0.1
else :
    down_payment=price*0.2
print(f"down payment is:{down_payment}")
down payment is:100000.0

(十一)逻辑运算符  (and  or  not)

练习

solution

has_high_income=True
has_good_credit=True
if has_high_income and has_good_credit:
    print("Eligible for loan")

 比较运算符(>  <  >=  <=  ==  !=)

练习1

Python教程笔记----6小时完全入门_第4张图片

 solution

temperature = int(input("temperature is : "))
if temperature > 30:
    print("it's a hot day")
elif temperature < 10:
    print("it's a cold day")
else:
    print("it's a neither hot or cold day")
temperature is :25
it's a neither hot or cold day

练习2

Python教程笔记----6小时完全入门_第5张图片

 solution

name=input('name: ')
i=len(name)
if i<3:
    print('name must be at least 3 characters')
elif i>50:
    print('name can be a maximum of 50 characters')
else:
    print('name looks good!')

 

实践一  体重单位 磅 和 千克 的转化器

solution

weight=int(input("weight: "))
unit=input("(L)bs or (K)g: ")
if unit.upper()=="L":
    i=weight*0.45
    print(f"You are {i} kilos")
elif unit.upper()=="K":
    i=weight/0.45
    print(f"You are {i} pounds")
else :
    print('please input l or k')

效果

 (十二)while 循环

简单的例子

i=1
while i<=5:
    print('*'*i)
    i+=1
print('Done')
*
**
***
****
*****
Done

实践二 猜谜游戏

secret_number=9
guess_count=0
guess_limit=3
while guess_count

结果 

Python教程笔记----6小时完全入门_第6张图片Python教程笔记----6小时完全入门_第7张图片

实践三 汽车开车

command= ""
started=False
while True:
    command=input("> ").lower()
    if command == "help":
        print('''
start - to start the car
stop - to stop the car
quit - to exit
        ''')
    elif command== 'start':
        if started:
            print('car is already started!')
        else:
            started=True
            print('Car started...')
    elif command == 'stop':
        if not started:
            print('car is already stopped')
        else:
            started=False
            print('Car stopped...')
    elif command == 'quit':
        break
    else:
        print("I don't understand that ...")
> HELP

start - to start the car
stop - to stop the car
quit - to exit
        
> start
Car started...
> start
car is already started!
> stop
Car stopped...
> stop
car is already stopped
> mac
I don't understand that ...
> quit

Process finished with exit code 0

(十三)for 循环

for item in 'Python':
    print(item)
for item in [1,2,3]:
    print(item)
for item in ['john','mosh','smith']:
    print(item)
for item in range(10):
    print(item)
for item in range(1,10,2):
    print(item)
P
y
t
h
o
n
1
2
3
john
mosh
smith
0
1
2
3
4
5
6
7
8
9
1
3
5
7
9

Process finished with exit code 0

练习  (计算购物车中所有商品的总成本)

prices=[10,20,30]
total=0
for price in prices:
    total+=price
print(f'total: {total}')#total: 60

(十四)嵌套循环

练习1 打印出多维数组

for x in range(4):
    for y in range(3):
        print(f'({x},{y})')
(0,0)
(0,1)
(0,2)
(1,0)
(1,1)
(1,2)
(2,0)
(2,1)
(2,2)
(3,0)
(3,1)
(3,2)

练习2(编写程序打印出下列图像)

Python教程笔记----6小时完全入门_第8张图片

solution 

for x in [5,2,5,2,2]:
    print(x*'x')
for x_count in [5,2,5,2,2]:
    output=""
    for count in range(x_count):
        output+='x'
    print(output)

(十五)列表

names=['john','mosh','shara','mary','lily']
print(names)
print(names[0])
print(names[2:4])
print(names[:])
names[0]='joh'
print(names)
['john', 'mosh', 'shara', 'mary', 'lily']
john
['shara', 'mary']
['john', 'mosh', 'shara', 'mary', 'lily']
['joh', 'mosh', 'shara', 'mary', 'lily']

练习(编写程序找出列表中最大的数)

list=[4,3,5,6,12,1]
max=0
for i in list:
    if i>=max:
        max=i
print(max)

(十六)插入  .append()     .insert() 

numbers=[5,2,1,5,7,4]
numbers.append(12)
print(numbers)
numbers.insert(0,7)
print(numbers)
[5, 2, 1, 5, 7, 4, 12]
[7, 5, 2, 1, 5, 7, 4, 12]

(十七)删除  del    .remove()   .clear()    .pop()

numbers=[5,2,1,5,7,4]
del numbers[0]#del ,放置索引直接删,不支持赋值语句
print(numbers)
numbers=[5,2,1,5,7,4]
numbers.remove(5)
print(numbers)#remove:直接删成员
numbers.clear()
print(numbers)#clear 全删
numbers=[5,2,1,5,7,4]
numbers.pop()
print(numbers)#不放置索引默认删除末尾值
print(numbers.pop())#pop 可以返回删除值
[2, 1, 5, 7, 4]
[2, 1, 5, 7, 4]
[]
[5, 2, 1, 5, 7]
7

(十八)排序  .sort()    .reverse()

numbers=[5,2,1,5,7,4]
numbers.sort()#升序排序
print(numbers)
numbers.reverse()#降序排序
print(numbers)
[1, 2, 4, 5, 5, 7]
[7, 5, 5, 4, 2, 1]

(十九)查询索引index()   列表中某元素的个数count()

numbers=[5,2,1,5,7,4]
print(numbers.index(1))#查询索引
print(50 in numbers)#判断列表中是否有该元素
print(numbers.count(5))#列表中元素5的个数
2
False
2

(二十)浅拷贝.copy()

numbers=[5,2,1,5,7,4]
num2=numbers.copy()
numbers.append(12)
print(numbers)
print(num2)
[5, 2, 1, 5, 7, 4, 12]
[5, 2, 1, 5, 7, 4]

练习(写一个程序,删除我们列表上的副本(重复项))

numbers=[2,2,5,6,6,5,12,7]
uniques=[]
for number in numbers:
    if number not in uniques:
        uniques.append(number)
print(uniques)
[2, 5, 6, 12, 7]

(二十一)矩阵

matrix=[
    [1,2,3],
    [4,5,6],
    [7,8,9]
]
print(matrix)
print(matrix[0][0])
matrix[0][0]=12
print(matrix[0][0])
for row in matrix:
    for item in row:
        print(item)
[[1, 2, 3], [4, 5, 6], [7, 8, 9]]
1
12
12
2
3
4
5
6
7
8
9

(二十二)元组

元组只读不改,列表可读可改;元组用括号定义

解压缩

numbers=(5,12,7)
x,y,z=numbers
print(x)
print(y)
print(z)
#解压缩同样适用于列表
numbers=[5,12,7]
x,y,z=numbers
print(x)
print(y)
print(z)
5
12
7
5
12
7

(二十三) 字典

customer={
    "name":"john smith",
    "age":"20",
    "phone":"123456"
}
print(customer)
print(customer['name'])
customer['name']='jock'
print(customer['name'])
customer['email']='[email protected]'
print(customer['email'])
{'name': 'john smith', 'age': '20', 'phone': '123456'}
john smith
jock
[email protected]

练习1(将输入的号码(数字)翻译成英文打印出来)

 solution

numbers={
    '0':'zero',
    '1':'one',
    '2':'two',
    '3':'three',
    '4':'four',
    '5':'five',
    '6':'six',
    '7':'seven',
    '8':'eight',
    '9':'nine'
}
phone=input('phone: ')
output=""
for i in phone:
    output+=numbers[i]+" "
print(output)

练习2(表情包转换器1)

message=input('> ')
msg=message.split()
emojis={
    ':)':'',
    ':(':''
}
output=""
for i in msg:
    output+=emojis.get(i,i)+" "
print(output)
> good morning :)
good morning  

(二十四)函数function

函数:用于执行特定代码的几行代码的容器,可重用的代码块(先定义后调用

def greet_user():#定义函数
    print('花看半开,酒饮微醺。')
    print('————洪应明《菜根谭》')

print("start")
greet_user()#调用函数
print("finish")
start
花看半开,酒饮微醺。
————洪应明《菜根谭》
finish

函数中定义参数 

def greet_user(name):
    print(f'Hi {name} !')
    print('welcome aboard.')


def greet_user2(first_name,last_name):
    print(f'Hi {first_name} {last_name} !')
    print('welcome aboard.')

print('start')
greet_user('john')
greet_user2('john','smith')
print('finish')
start
Hi john !
welcome aboard.
Hi john smith !
welcome aboard.
finish

  返回函数 return()

def square(number):
    result=number*number
    return(result)


print(square(3))#9
def square(number):
    print(number*number)


square(3)#9

练习(表情转换器(2))

def emoji_converter(message):
    words=message.split()
    emojis={
        ':)':"",
        ':(':"☹"
    }
    output=''
    for word in words:
        output+=emojis.get(word,word)+" "
    print(output)

emoji_converter(input('> '))

 

(二十五)怎么处理错误?

(作为一个程序员,想要当程序发生错误时程序不奔溃,而是打印出错误提示)

示值错误(value error)

age=int(input("age: "))
print(age)

Python教程笔记----6小时完全入门_第9张图片 进行错误处理后 (try expect)

try:
    age=int(input("age: "))
    print(age)
except ValueError:
    print('Invalid value')

 0在除法中的错误(zero division error)

try:
    age=int(input("age: "))
    income=10000
    risk=income/age
    print(age)
except ZeroDivisionError:
    print('age can not be 0.')
except ValueError:
    print('Invalid value')

(二十六) 类

  • 类的命名方式和往常的不同,不用单词间下划线,通过大写每个单词的第一个字母来分离多个单词(用class定义一个类)
  • 一个类下有多个函数

用类来定义一个新类型 

class EmailClient:
    def draw(self):
        print("draw")

    def move(self):
        print("move")


EmailClient1=EmailClient()
EmailClient1.draw()
EmailClient1.x=20
print(EmailClient1.x)
draw
20

构造函数 

class EmailClient:
    def __init__(self,x,y):#用构造函数来定义x,y
        self.x=x
        self.y=y

    def draw(self):
        print("draw")

    def move(self):
        print("move")

point1=EmailClient(10,20)
print(point1.x)#10
point1.x=11
print(point1.x)#11

练习(定义一个名为person的新类型,这些person对象应该有一个name属性和一个对话方法)

class Person:
    def __init__(self,name):
        self.name=name

    def talk(self):
        print(f'Hi, I am {self.name}.')

i=Person("john")
print(i.name)
i.talk()
john
Hi, I am john.

(二十七)Python的继承

class common:
    def walk(self):
        print("walk")

class dog(common):
    pass

class cat(common):
    def annoying(self):
        print("annoying")


dog1=dog()
dog1.walk()
cat1=cat()
cat1.walk()
cat1.annoying()
walk
walk
annoying

(二十八)Python的模块

模块:新建一个Python file储存函数、类;编程时可重复调用模块

调用模块:调用整个模块&调用模块中的特定函数

import converters#调用整个函数
print(converters.kg_to_lbs(45))
from converters import kg_to_lbs#调用模块的特定函数
print(kg_to_lbs(46))
100.0
102.22222222222221

 练习(创建一个find_max函数:获取一个列表,并返回最大值max放在模块utils中,并调用使用)

模块utils代码:

def find_max(list):
    max=list[0]
    for i in list:
        if max<=i:
            max=i
    return max

调用函数:

import utils#调用整个模块
list=[4,5,6,2,3,10]
max=utils.find_max(list)
print(max)#10
#或者
import utils#调用整个模块
list=[4,5,6,2,3,10]
print(list)#10

from utils import find_max#调用模块中的特定函数
list=[2,5,6,5,7,10]
max=find_max(list)
print(max)#10

(二十九) Python 的包

放置多个模块的目录或文件夹

建立包:new—directory或者new package ;在包内创建相应模块

(包:ecommerce  模块shipping)

def calc_shipping():
    print('shipping!')

 导入包中模块

import ecommerce.shipping#调用包中的整个模块
ecommerce.shipping.calc_shipping()

from ecommerce.shipping import calc_shipping,calc_tax#调用包中模块的一个或多个函数
calc_shipping()
calc_tax()

Python教程笔记----6小时完全入门_第10张图片

(三十) python里的标准库

库里有很多内置模快 ,eg. random.py

random.py 生成随机值

import random
for i in range(3):
    print(random.random())#输出3个0-1的随机值

import random
for i in range(3):
    print(random.randint(10,20))#输出3个10-20的整数

import random
members=['john','mary','mosh','mark']
leader=random.choice(members)#随机挑选领导者
print(leader)

0.18776716633953994
0.5121911896606305
0.9015254212043647
16
20
15
mosh

练习(得到两个随机值的元组) (类:dice    函数:roll)

import random
class dice:
    def roll(self):
        first=random.randint(1,6)
        second=random.randint(1,6)
        return first,second

dice=dice()
print(dice.roll())#随机数eg.(1,4)

(三十一)使用目录

from pathlib import Path
path=Path("ecommerce")
print(path.exists())
print('*******************************')
from pathlib import Path
path=Path()
for file in path.glob("*.py"):#搜索文件
    print(file)
print('*******************************')
from pathlib import Path
path=Path()
for file in path.glob("*"):#搜索目录
    print(file)
False
*******************************
app.py
demo2.py
main.py
*******************************
.idea
app.py
demo2.py
main.py
venv

 pypi  and pip

http:// pypi.org  搜 sms.aas   (搜项目)

http://yelp.com

三、实践

(一)如何安装来自pypi.org的软件包:

1.登录http://pypi.org网站

Python教程笔记----6小时完全入门_第11张图片

 2.搜索软件包

 Python教程笔记----6小时完全入门_第12张图片

 复制指令:pip install openpyxl

Python教程笔记----6小时完全入门_第13张图片

回到pycharm ,---Terminal 

 Python教程笔记----6小时完全入门_第14张图片

Python教程笔记----6小时完全入门_第15张图片

 粘贴指令  +enterPython教程笔记----6小时完全入门_第16张图片

 (二)如何使用Excel文件

 (视频还没看完,明天接着看。o  0)

你可能感兴趣的:(python入门,python,开发语言,后端)