当前位置: 首页 > 工具软件 > Mosh > 使用案例 >

Python Mosh 学习笔记(6小时完全入门)

殷宇
2023-12-01

02:01:45 2D Lists
02:05:11 My Complete Python Course
02:06:00 List Methods
02:13:25 Tuples
02:15:34 Unpacking
02:18:21 Dictionaries
02:26:21 Emoji Converter
02:30:31 Functions
02:35:21 Parameters
02:39:24 Keyword Arguments
02:44:45 Return Statement
02:48:55 Creating a Reusable Function
02:53:42 Exceptions
02:59:14 Comments
03:01:46 Classes
03:07:46 Constructors
03:14:41 Inheritance
03:19:33 Modules
03:30:12 Packages
03:36:22 Generating Random Values
03:44:37 Working with Directories
03:50:47 Pypi and Pip
03:55:34 Project 1: Automation with Python
04:10:22 Project 2: Machine Learning with Python
04:58:37 Project 3: Building a Website with Django

目录
00:00:00 简介
00:01:49 安装Python 3
00:06:10 您的第一个Python程序
00:08:11 如何执行Python代码
00:11:24 学习Python需要多长时间
00:13:03 变量
00:18:21 接收输入
00:22:16 Python备忘单
00:22:46 型号转换
00:29:31 字符串
00:37:36 格式化字符串
00:40:50 字符串方法
00:48:33 算术运算
00:51:33 运算符优先级
00:55:04 数学函数
00:58:17 国际单项体育联合会声明
01:06:32 逻辑运算符
01:11:25 比较运算符
01:16:17 重量转换器程序
01:20:43 While循环
01:24:07 制作猜谜游戏
01:30:51 打造汽车游戏
01:41:48 循环
01:47:46 嵌套循环
01:55:50 名单
02:01:45 二维列表
02:05:11 我的完整蟒蛇课程
02:06:00 列表方法
02:13:25 元组
02:15:34 拆包
02:18:21 字典
02:26:21 表情转换器
02:30:31 功能
02:35:21 参数
02:39:24 关键字参数
02:44:45 返回语句
02:48:55 创建可重用函数
02:53:42 例外
02:59:14 评论
03:01:46 类
03:07:46 施工人员
03:14:41 继承
03:19:33 模块
03:30:12 包裹
03:36:22 生成随机值
03:44:37 使用目录
03:50:47 皮皮和皮皮
03:55:34 项目1:使用Python实现自动化
04:10:22 项目2:使用Python进行机器学习
04:58:37 项目3:与Django建立网站

来自于b站视频 BV14J411U7hj
6小时完全入门的代码/笔记

print("Hello World!")
print('o----')
print(' ||||')
print('*' * 10)
price = 10
price = 20
print(price)
rating = 4.9
name = 'HELLO'
is_published = True
# python对大小写敏感,true这个就是错误的布尔值,必须是True
i_published = False
patient_name = 'John Smith'
patient_age = 20
patient_status = 'New'
patient_status_plus = True
is_new = True
# name = input('What is your name? ')
print('Hi ' + name)
name = input('What is your name? ')
color = input('What is your favorite color? ')
print(name + ' likes ' + color + '.')

截止到0:38:51

birth_year = input('Birth year: ')
# input函数,无论你在终端输入什么,都会被认为是字符串类型的
# 2020 - ‘1999’ python don't know how to do
# int()
# float()
# bool()
# 以上函数是强制转换类型
# 获得变量的类型,并打印类型的函数 type()函数获取括号内变量的数据类型
print(type(birth_year))
age = 2020 - int(birth_year)
print(type(age))
print(age)
# 下面是错误范例 int(weight)
# weight是str类型的
# 通过 int(weight)函数,请问weight变成什么类型了
weight = '70'
int(weight)
print(type(weight))
# 可以看出<class 'str'>,weight依然是str类型的
# weight = input('What your weight in pounds? ')
# int(weight)
# weight_kg = weight * 0.45
# print(weight_kg)
# 所以改为如下
weight = input('What your weight in pounds? ')
weight_kg = int(weight) * 0.45
print(weight_kg)
print(str(weight_kg) + 'kg')
# course = 'Python's Course for Beginners' 这句会报错,因为在''s之前字符串就结束了
# 双引号的作用 这时候就可以运用双引号
course = "Python's Course for Beginners"
print(course)
# 同样单引号也有这种用法
course = 'Python for "Beginners"'
print(course)
course = '''
Hi John

Here is our first email to you.

Thank you,
The support team
'''
print(course)
course = 'Python for Beginners'
print(course[0])  # 这个就是索引,我们在其它编程语言中没有的特性之一 P
print(course[-1])   # s
print(course[-2])   # r
print(course[0:3])  # Pyt
print(course[0:])   # Python for Beginners
print(course[1:])
print(course[:5])
# copy [:]
course = 'Python for Beginners'
another = course[:]
print(another)
name = 'Jennifer'
print(name[1:-1])

截止到0:59:28

import math  # import 要放在最上方
# You can search in Google : Python 3 math model, then you could see the file about it.
print(math.ceil(2.9))  # ceil向上取整
print(math.floor(2.9))  # floor向下取整
first = 'John'
last = 'Smith'
message = first + ' [' + last + '] is a coder'
msg = f'{first} [{last}] is a coder'
print(message)
print(msg)
course = 'Python for Beginners'
print(len(course))
print(course.upper())
print(course.lower())
print(course)
print(course.find('P'))
print(course.find('o'))
print(course.find('O'))
print(course.replace('Beginners', 'Absolute Beginners'))
print(course.replace('P', 'J'))
print('Python' in course)
print('python' in course)
# len()
# course.upper()
# course.lower()
# course.title()
# course.find()
# course.replace()
# '...' in course
print(10 // 3)  # 整除
print(10 / 3)
print(10 % 3)
print(10 ** 3)  # 10^3
x = 10
x = x + 3
x += 3
print(x)
# Operate Precedence
# Math Function
x = 2.9
print(round(x))
print(abs(-2.9))  # 取绝对值 absolute

截止到1:11:31

is_hot = False
is_cold = False
if is_hot:
    print("It's a hot day")
    print("Drink plenty of water")
elif is_cold:
    print("It's a cold day")
    print("Wear warm clothes")
else:
    print("It's a lovely day")
print("Enjoy your day")  # shift and tab, 光标回到这条线的开始处
house_price = 1000000  # 1M = 1000000
good_credit = True
if good_credit:
    put_down = house_price * 0.1
else:
    put_down = house_price * 0.2
print(f'Their down payment is ${put_down}')
# 对于一整段, 可以用ctrl + / 注释
has_high_income = True
has_good_credit = False

if has_good_credit and has_high_income:
    print("Eligible for loan")  # Eligible 有资格的
if has_good_credit or has_high_income:
    print("Eligible for loan")  # Eligible 有资格的

# 对于一段代码,有些有注释,有些没有注释#,也就是说用#注释过的和没注释过的混在一起
# 这时候再ctrl + / ,我们看到,有两个##产生了
has_good_credit = True
has_criminal_record = False

if has_good_credit and not has_criminal_record:
    print("Eligible for loan")

截止到1:30:59

temperature = 35
if temperature >= 30:
    print("It's a hot day")
else:
    print("It's not a hot day")
name = input("Please input your name ")
if len(name) < 3:
    print("name must be at least 3 characters")
elif len(name) > 50:
    print("name can be a maximum of 50 characters")
else:
    print("name looks good!")
# Weight Converter
weight = input('Weight: ')
weight_unit = input('(L)bs or (K)g: ')
# if weight_unit == 'L' or weight_unit == 'l':
if weight_unit.upper() == 'L':  # 如果weight_unit的大写等于'L'
    weight_kilo = int(weight) * 0.45
    print(f'You are {weight_kilo} kilos')
#    print('You are ' + str(weight_kilo) + ' kilos')
else:
    weight_pounds = int(weight) / 0.45
    print(f'You are {weight_pounds} pounds')

# While Loops
i = 1
while i <= 5:
    print('*' * i)
    i = i + 1
print("Done")

# if we give this code to someone else it's unclear
# what does i represent here,it's only in our head that i represents the number of guesses
# the user has made
# so as be a best practice 总是为变量使用有意义和描述性的名称
# 所以这里最好把这个变量命名为 guess_count
# 右键要修改的变量 refactor -> rename
# 或者快捷键 shift + F6
# 再把3改成guess_limit 使得代码的可读性更强
# our code is more readable
secret_number = 9
guess_count = 0
guess_limit = 3
while guess_count < guess_limit:  # while也有else的部分
    guess = int(input("Guess: "))
    guess_count += 1
    if guess == secret_number:
        print("You won!")
        break
else:
    print("Sorry, you failed!")

截止到1:41:59

# Car Game
operate = input('>')
if operate.upper() == 'HELP':
    print('start - to start the car')
    print('stop - to stop the car')
    print('quit - to exit')
operate_car = input('>')
if operate_car.lower() == 'start':
    print("Car started...Ready to go!")
elif operate_car.lower() == 'stop':
    print("Car stopped.")
elif operate_car.lower() == 'quit':
    exit()
else:
    print("I don't understand that...")
operate = input('>')
while operate.lower() != 'quit':
    if operate.lower() == 'help':
        print('start - to start the car')
        print('stop - to stop the car')
        print('quit - to exit')
        operate = input('>')
    elif operate.lower() == 'start':
        print("Car started...Ready to go!")
        operate = input('>')
    elif operate.lower() == 'stop':
        print("Car stopped.")
        operate = input('>')
    else:
        print("I don't understand that...")
        operate = input('>')
# 以上是我自己写的,发现有很严重的问题,在于quit 需要两边才能解决
# 下述是改进的,发现只能 input 一次,原因在于,没有把input 放进循环中
operate = ""
while operate.lower() != 'quit':
    operate = input('>')
    if operate.lower() == 'help':
        print('start - to start the car')
        print('stop - to stop the car')
        print('quit - to exit')

    elif operate.lower() == 'start':
        print("Car started...Ready to go!")

    elif operate.lower() == 'stop':
        print("Car stopped.")
    else:
        print("I don't understand that...")

# 上述这个也有问题,quit一次,start要输入两次,所以既要把字符送入循环中,也得有空字符串
# don't repeat yourself !!!
# 重复地做一件事,得想一下,你做错了什么
# 以下是视频中的范例代码
# 然后我又改了一下 重复stop的
# 还是有点问题,在于stop后又start,状态已经改变了,但是我没有考虑到
count_start = 0
count_stop = 0
command = ""
while True:  # 就是说一直循环,直到等于quit时候结束 还是那句话,如果重复地做一件事,得想,做错了什么(使得重复了),肯定有改进的方法
    command = input("> ").lower()
    if command == "start" and count_start == 0:
        print("Car started...")
        count_start += 1
    elif command == "start" and count_start != 0:
        print("Hi guys you had started it!")
    elif command == "stop" and count_stop == 0:
        print("Car stopped.")
        count_stop += 1
    elif command == "stop" and count_stop != 0:
        print("Hi guys you had stopped it!")
    elif command == "help":  # 三重引号,我们输入什么,它都会原样打印
        print("""
start - to start the car
stop - to stop the car
quit - to exit
        """)
    elif command == "quit":  # 这时候发现又重复了,和条件重复了,所以还是有什么地方可以改进的 于是条件改成 while True
        break
    else:
        print("I don't understand that...")
# 以下是加上started的范例代码,上面属于我自己改的
command = ""
started = False
while True:  # 就是说一直循环,直到等于quit时候结束 还是那句话,如果重复地做一件事,得想,做错了什么(使得重复了),肯定有改进的方法
    command = input("> ").lower()
    if 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 == "stop":
        print("Hi guys you had stopped it!")
    elif command == "help":  # 三重引号,我们输入什么,它都会原样打印
        print("""
start - to start the car
stop - to stop the car
quit - to exit
        """)
    elif command == "quit":  # 这时候发现又重复了,和条件重复了,所以还是有什么地方可以改进的 于是条件改成 while True
        break
    else:
        print("I don't understand that...")

截止到2:13:35

# For loops
for item in 'Python':
    print(item)
for item in ['Mosh', 'John', 'Sarah']:
    print(item)
for item in [1, 2, 3, 4]:
    print(item)
for item in range(10):
    print(item)
for item in range(5, 10):
    print(item)
for item in range(5, 10, 2):  # 最后一个部分是step,range(5, 10)的范围内,以单位2走一步
    print(item)
price = [10, 20, 30]
for item in range(10, 31, 10):
    print(item)
price = [10, 20, 30]
total = 0
for prices in price:
    total = prices + total
print(f'Total: {total}')
# # Nested Loops
for x in range(4):
    print(x)
for x in range(4):
    for y in range(3):
        print(f'({x}, {y})')
numbers = [5, 2, 5, 2, 2]
signal_structure = 'x'
for signal in range(5):
    for signal_count in numbers[:signal]:
        print("x")
# 每一次卡壳,都在这种空字符串上
numbers = [5, 2, 5, 2, 2]
for x_count in numbers:
    output = ""
    for result in range(x_count):
        output = output + 'x'
    print(output)
# 关于空字符串的理解,见下的输出
test = ""
print(test)
test = test + 'x'
print(test)
test = test + 'x' + 'x'
print(test)
# Lists
name = ['John', 'Bob', 'Mosh', 'Sarah', 'Mary']
print(name)
print(name[0])
print(name[2])
print(name[-1])
print(name[-2])
print(name[2:])   # [2:]是Mosh到Mary
print(name[2:4])  # [2:4]是Mosh到Sarah,因为这里结束索引是4,它会返回所有项到这个索引,但是不包括这个索引中的项
print(name[4])  # Mary
print(name)
# 当我们发现John的名字写错了,这时候我们可以
names = ['John', 'Bob', 'Mosh', 'Sarah', 'Mary']
names[0] = 'Jon'
print(names)
# numbers = [3, 6, 2, 8, 4, 10]
# for sort in range(len(numbers)-1):
#     for sort_s in range()
numbers = [3, 6, 2, 8, 4, 10]
# numbers_max = max(numbers)
# print(numbers_max)
numbers = [3, 6, 2, 8, 4, 10]
max_number = numbers[0]
for item in range(0, len(numbers) - 1):
    if numbers[item] < numbers[item + 1]:
        max_number = numbers[item + 1]
print(max_number)
# 视频中的范例如下
max_model = numbers[0]
for number in numbers:
    if number > max_model:
        max_model = number
print(max_model)

# 2D Lists
matrix = [
    [1, 2, 3],
    [4, 5, 6],
    [7, 8, 9]
]
# matrix[0][1] = 20
# print(matrix[0][1])
for row in matrix:
    print(row)
print(row)
for row in matrix:
    for item in row:
        print(item)
# numbers = [5, 2, 1, 7, 4]
# numbers.append(20)
# print(numbers)
numbers = [5, 2, 1, 7, 4]
numbers.insert(0, 10)
print(numbers)
numbers.remove(5)
print(numbers)
numbers.clear()
print(numbers)
numbers = [5, 2, 1, 5, 7, 4]
numbers.pop()  # 把列表的末尾删除 pop也有射击的意思
print(numbers)
print(numbers.index(5))
print(50 in numbers)
print(numbers.count(5))
print(numbers.sort())
numbers.sort()
print(numbers)
numbers.reverse()
print(numbers)

numbers2 = numbers.copy()
numbers.append(10)

print(numbers2)
# for item in numbers2:
numbers = [2, 2, 4, 6, 3, 4, 6, 1]
uniques = []
for number in numbers:
    if number not in uniques:
        uniques.append(number)
print(uniques)

看了一下还剩下三分之二,暂时不打算更新了,因为暑假任务也挺重的,就先靠开头两位的笔记看看了。
以下是后面的一些简略的内容。

# Tuples 元组
# 'tuple' object does not support item assignment
# 元组是不可变的
numbers = (1, 2, 3)
print(numbers[0])
phone = input("Phone: ")
Phone = {
    "1": "One",
    "2": "Two",
    "3": "Three",
    "4": "Four"
}
for phone_print in phone:
    print(Phone.get(phone_print))
# 老问题了,又是字符串的问题,空字符串!!!
# 这里需要定义一个空字符串,再把这个词添加到字符串中,就可以再一行里了
# 就不会像上面我写的那种有换行的错误了
phone = input("Phone: ")
Phone = {
    "1": "One",
    "2": "Two",
    "3": "Three",
    "4": "Four"
}
output = ""
for phone_print in phone:
    output = output + Phone.get(phone_print, '!') + ' '
print(output)
# 以下是范例
phone = input("Phone: ")
digits_mapping = {
    "1": "One",
    "2": "Two",
    "3": "Three",
    "4": "Four"
}
output = ""
for ch in phone:
    output += digits_mapping.get(ch, "!") + " "
print(output)

# message = input(">")
# words = message.split(' ')
# print(words)

# Functions


def expression_function(message_users):
    words = message_users.split(' ')
    expression = {
        ":)": "",
        ":(": ""
    }
    output_in_function = ""
    for word in words:
        output_in_function += expression.get(word, word) + " "
    return output_in_function


message = input(">")
output_expression = expression_function(message)
print(output_expression)

try:
    age = int(input('Age: '))
    income = 2000
    risk = income / age
    print(age)
except ZeroDivisionError:
    print('Age cannot be 0.')
except ValueError:
    print("Invalid value.")

 类似资料: