初学Python之基础知识笔记

由于学业要求,进行了Python的学习,慕课上的视频看得不是很理解,所以向B站大佬进行了学习。六小时极速入门!

——接下来就是紧张刺激的贴代码环节,记录自己的学习
  • 001 简单的打印
print("Hello world")
print('*' * 10)
price = 10
print(price)
  • 002 不同类型的打印
name = 'Make'
age = 18
isHave = False
print(age,name,isHave)
  • 003 输入和输出
full_name = input('What is your name? \n')
print('Hi ' + full_name)
  • 004 输入和输出类型
birth = int(input('Birth year: '))
age = 2020- birth
print(type(age))
print(age)
  • 005 单引号双引号三引号的用法 字符串 多种下标取法
coures = "Python's for Beginners"
print(coures)
coures = 'Python for "Beginners"'
print(coures)
coures = '''
Hi oldbai
see you
'''
print(coures)
coures = 'Python for Beginners'
print(coures[0])
print(coures[-1])
print(coures[0:3])
print(coures[0:])
print(coures[:6])
print(coures[:])
coures = 'Jennifer'
print(coures[1:-1])
  • 006 一种简便的打印
first = 'John'
last = 'Smith'
msg = f'{first} [{last}] is a coder'
print(msg)
  • 007 字符串的多种方法
course = 'Python for Beginners'
print(len(course))
print(course.upper())
print(course.lower())
print(course.title())
print(course.find('O'))
print(course.find('o'))
print(course.find('Beginners'))
print(course.replace('Beginners','OldBai'))
print('Python' in course)
print(course)
  • 008 除法 整除 次方
print(10/3)
print(10//3)
print(10**3)
x = 10
x = x + 3
print(x)
x += 3
print(x)
  • 009 运算优先级
x = 10 + 3 * 2
y = 10 + 3 * 2 **2
print(x,y)
  • 010 引入数学方法
import math
print(math.ceil(2.9))
print(math.floor(2.9))
x = 2.9
print(round(x))
x = -2.9
print(abs(x))
  • 011 if的使用
is_hot = True
is_hot = False
# is_cold = True
is_cold = False
if is_hot:
    print("It's a hot day")
    print("Drink plentf of  water")
elif is_cold:
    print("You are so cold")
    print("Wear warm clothes")
else:
    print("It's a good day")
    print("Have a good time")
print("From oldBai")
  • 012 if的使用
price = 10000
has_good_credit = True

if has_good_credit:
    down_payment = 0.1 * price
else:
    down_paymen = 0.2 * price
print(f"Down payment: {down_payment}")
  • 013 if的使用 强制转换类型
weight = int(input('Weight: '))
unit = input('(L)bs or (K)g: ')
if unit.upper() == "L" :
    converted = weight * 0.45
    print(f"You are {converted} kilos")
else:
    converted = weight / 0.45
    print(f"You are {converted} pounds")
  • 014 while循环
i = 1
while i<=5:
    print('*'*i)
    i=i+1
print("Done")

secret_num = 9
guess_count = 0
guess_limit = 3
while guess_count<guess_limit:
    guess = int(input('Guess: '))
    guess_count += 1
    if guess == secret_num:
        print('You Win')
        break
    else:
        print('You should again!')
else:
    print('Sorry you failed')
print("End")
  • 015 while循环
command = ""
started = False
while True :
    command = input("> ").lower()
    if command == "start" :
        if started:
            print("Car is already started!")
        else:
            print("Car started...")
            started = True
    elif command == "stop" :
        if not started:
            print("Car is already stopped!")
        else:
            print("Car stopped...")
    elif command == "help" :
        print("""
------->start - to start the Car
------->stop - to stop the Car
------->quit - to quit
        """)
    elif command == "quit" :
        print("You quit the Car")
        break
    else:
        print("Sorry , I don't understand that!")
  • 016 for循环的多种遍历
for item in 'Python':
    print(item)
for item in ['Mosh','John','Sarah']:
    print(item)
for item in [1,2,3,4,5]:
    print(item)
for item in range(10):
    print(item)
for item in range(11,15):
    print(item)
for item in range(5,10,2):
    print(item)
prices = [10,20,30]
total = 0
for price in prices:
    total += price
print(f"Total:{total}")
  • 017 嵌套循环
for x in range(4):
    for y in range(4):
        print(f'({x},{y})')
num = [5,2,5,2,2]
for item in num:
    output = ''
    for count in range(item):
        output += 'x'
    print(output)
  • 018 使用数组的方法
names = ['John','Bob','Mosh','Sarah','Mary']
print(names)
number = [3,6,9,12,15,1,11]
max = number[0]
for iten in number:
    if iten > max :
        max = iten
print(max)
print(max(number))
  • 019 二维数组
matrix  = [
    [1,2,3],
    [4,5,6],
    [7,8,9]
]
print(matrix)
print(matrix[0][0])
for row in matrix:
    for item in row:
        print(item)
  • 020 列表方法
numbers = [5,2,1,1,7,4]
numbers.append(20)
print(numbers)
numbers.insert(0,10)
print(numbers)
numbers.remove(5)
print(numbers)
numbers.pop()
print(numbers)
print(numbers.index(2))
print(50 in numbers)
print(numbers.count(1))
numbers.sort()
print(numbers)
numbers.reverse()
print(numbers)
numbers_2 = numbers.copy()
print(numbers_2)
numbers.clear()
print(numbers)
  • 021 列表的添加
numbers = [2,2,4,6,3,4,6,1]
uniques = []
for  number in numbers:
    if number not in uniques:
        uniques.append(number)
print(uniques)
  • 022 元组
numbers = (1,2,3)
print(numbers[1])
  • 023 解压缩
coordinates = (1,2,3)
x,y,z = coordinates
print(x,y,z)
coordinates = [1,2,3]
x,y,z = coordinates
print(x,y,z)
  • 024 字典 也就是结构体
customer = {
    "name" : "John Smith",
    "age" : 30,
    "is_verified" : True
}
print(customer.get("name"))
print(customer.get("birthdate"))
customer["birthdate"] = "Jan 1 1980"
print(customer.get("birthdate"))
print(customer.get("birthdate","Jan 1 1980"))
  • 一个练习
phone = input("Phone: ")
digits_mapping = {
    "1" : "One",
    "2" : "Two",
    "3" : "Three",
    "4" : "Four"
}
output = ""
for item in phone:
    output += digits_mapping.get(item,"!") + " "
print(output)
  • 025 “win”+"."引用表情 一个小练习
message = input(">")
words = message.split(' ')
print(words)
emojis = {
    ":)" : "😊",
    ":(" : "😒"
}
output = ""
for word in words :
    output += emojis.get(word, word) + " "
print(output)
  • 026 定义方法函数 结尾要空两行
def greet_user():
    print('Hi there!')
    print('Welcome aboard')


print("Start")
greet_user()
print("Finish")
  • 027 带参数的函数
def greet_user(fist_name, last_name):
    print(f'Hi {fist_name} {last_name}!')
    print('Welcome aboard')


print("Start")
greet_user("John", "Smith")
greet_user("Mary", "Smith")
print("Finish")
  • 028 参数位置不对应的解决办法 关键字传参 位置参数关键字参数两个概念
def greet_user(fist_name, last_name):
    print(f'Hi {fist_name} {last_name}!')
    print('Welcome aboard')


print("Start")
greet_user("John", "Smith")
greet_user("Smith","John")
greet_user(last_name="Smith",fist_name="John")
print("Finish")

  • 029 函数的小练习
def square(number):
    return number * number


result = square(3)
print(result)
  • 030 用函数完成表情引用
def emoji_converter(message):
    words  = message.split(" ")
    emjis = {
        ":)":"😊",
        ":(":"😒"
    }
    output = ""
    for word in words :
        output += emjis.get(word,word) + " "
    return output


message  = input(">")
print(emoji_converter(message))
  • 031 处理错误
try:
    age = int(input('Age: '))
    income = 20000
    risk = income / age
    print(age)
except ZeroDivisionError:
    print('Age cannot be 0')
except ValueError:
    print('Invalid value')
  • 032 python 的 类
class Point:
    def move(self):
        print("move")

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


point = Point()
point.x = 10
point.y = 20
print(point.x)
print(point.y)
point.draw()
point.move()
  • 033 构造函数
class Point:
    def __init__(self,x,y):
        self.x = x
        self.y = y

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


point = Point(10,20)
point.x = 11
print(point.x)
  • 034 类的练习
class Person:
    def __init__(self,name):
        self.name = name
    def talk(self):
        print(f"Hi I'm {self.name}")


john = Person("John Smith")
print(john.name)
john.talk()
  • 035 继承
class Mammal:
    def walk(self):
        print("walk")


class Dog(Mammal):
    pass #路径语句


class Cat(Mammal):
    def bark(self):
        print("bark")


dog = Dog()
dog.walk()
cat = Cat()
cat.walk()
cat.bark()
  • 036 模块 两种引入方法:
    —1.目录图片目录图片
    —2.代码
def lbs_to_kg(weight):
    return weight * 0.45


def kg_to_lbs(weight):
    return weight / 0.45
import converter
from converter import kg_to_lbs

print(kg_to_lbs(100))
print(converter.kg_to_lbs(70))
  • 037 函数的练习
    —1.目录结构:在这里插入图片描述
    —2.代码:
def find_max(numbers):
    findMax = numbers[0]
    for number in numbers:
        if findMax < number :
            findMax = number
    return findMax
import FindMax
numbers = [10,6,3,2]
max = FindMax.find_max(numbers)
print(max)
  • 038 包
    —1.目录结构:在这里插入图片描述
    —2.代码:
def calc_shipping():
    print("calc_shipping")
import ecommerce.shipping
ecommerce.shipping.calc_shipping()
from ecommerce.shipping import calc_shipping
calc_shipping()
from ecommerce import shipping
shipping.calc_shipping()
  • 039 随机函数
import random

memebers = ['John','Mary','Bob','Mosh']
for i in range(3):
    print(random.random())
    print(random.randint(10,20))
    print(random.choice(memebers))
  • 040 骰子练习
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())
  • 041 引用文件
from pathlib import Path
path = Path("emails")
# 判断是否存在
print(path.exists())
# 创建
print(path.mkdir())
print(path.exists())
# 删除
print(path.rmdir())
print(path.exists())
# 遍历文件
path_1 = Path()
print(path_1.glob('*.py'))
for flie in path_1.glob('*.py'):
    print(flie)

代码贴完了,基本入门了。接着就是学习第三方库还有一些高级基础,希望这些基础代码对初学者有帮助,跟着敲一遍有助于理解~

  • 6
    点赞
  • 17
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值