我的Python学习基础笔记

1.起步
2.变量和简单数据类型
3.列表
4.操作列表
5.if语句
6.字典
7.while循环
8.函数
9.类
10.文件和异常
11.测试

# 使用方法修改字符串的大小写
name = "ada lovelace"
print(name.title())
print(name.upper())
print(name.lower())
# 合并字符串
first_name = "ada"
last_name = "lovelace"
full_name = first_name + " " + last_name
print(full_name)
print("Hello, " + full_name.title() + "!")
message = "Hello, " + full_name.title() + "!"
print(message)
# 使用制表符或换行来添加空白
print("\tpython")
print("Languages:\nPython\nC\nJavaScript")
# 删除空白
favorite_language = ' python '
# 删除右端的空格
favorite_language = favorite_language.rstrip()
# 删除左端的空格
favorite_language = favorite_language.lstrip()
# 删除左右端的空格
favorite_language = favorite_language.strip()
print(favorite_language)
# 使用函数str()避免类型错误
age = 23
message = "happy " + str(age) + "rd birthday!"
print(message)
print("------------------")
import this
print("------------------")
# 列表
bicycles = ['trek', 'cannondale', 'redline', 'specialized']
print(bicycles)
# 访问列表元素
print(bicycles[0])
print(bicycles[0].title())
print(bicycles[3])
print(bicycles[-1])
print(bicycles[-2])
message = "My first bicycle was a " + bicycles[0].title() + "."
print(message)
# 修改列表元素
motorcycles = ['honda', 'yamaha', 'suzuki']
print(motorcycles)
motorcycles[0] = 'ducati'
print(motorcycles)
# 在列表中添加元素
motorcycles.append('ducati')
print(motorcycles)
motorcycles = []
motorcycles.append('1')
motorcycles.append('2')
motorcycles.append('3')
print(motorcycles)
# 在列表中插入元素
motorcycles.insert(2, '20')
print(motorcycles)
# 在列表中删除元素
del motorcycles[2]
print(motorcycles)
# 使用方法pop()删除元素:列表就像一个栈,而删除列表末尾的元素相当于弹出栈顶元素,虽然不在列表里,但是还能继续使用
motorcycles = ['honda', 'yamaha', 'suzuki']
popped_motorcycles = motorcycles.pop()
print(motorcycles)
print(popped_motorcycles)
# 弹出列表中任何位置处的元素
motorcycles = ['honda', 'yamaha', 'suzuki', 'wea', 'wodeya']
first_owned = motorcycles.pop(0)
print('The first motocycle I owned was a ' + first_owned.title() + '.')
# 根据值删除元素
motorcycles.remove('wodeya')
print(motorcycles)
# 使用方法sort()对列表进行永久性排序
# 按字母顺序
cars = ['bmw', 'audi', 'toyota', 'subaru']
cars.sort()
print(cars)
# 按字母逆序
cars = ['bmw', 'audi', 'toyota', 'subaru']
cars.sort(reverse=True)
print(cars)
# 使用函数sorted()对列表进行临时排序:会保留原始顺序序列
cars = ['bmw', 'audi', 'toyota', 'subaru']
print(sorted(cars))
print(cars)
# 倒着打印列表:反转列表
print(cars)
cars.reverse()
print(cars)
# 确定列表的长度
print(len(cars))
# 遍历整个列表:for循环
magicians = ['alice', 'david', 'carolina']
for magician in magicians:
    print(magician)
# 使用函数range()
for value in range(1, 5):
    print(value)
# 使用range()创建数字列表
numbers = list(range(1, 6))
print(numbers)
# 打印1-10内的偶数
even_numbers = list(range(2, 11, 2))
print(even_numbers)
# 数的平方加入到一个列表
squares = []
for value in range(1, 11):
    square = value**2
    squares.append(square)
print(squares)
# 对数字列表执行简单的统计计算
digits = [1, 2, 3, 4, 5, 6, 7, 8, 9, 0]
print(str(min(digits)) + '_' + str(max(digits)) + '_' + str(sum(digits)))
# 列表解析
squares = [value**2 for value in range(1, 11)]
print(squares)
# 切片
players = ['charles', 'martina', 'michael', 'florence', 'eli']
print(players[0:3])
print(players[1:4])
print(players[:4])
print(players[2:])
print(players[-3:])
# 遍历切片
for player in players[:3]:
    print(player.title())
# 复制列表
my_foods = ['pizza', 'falafel', 'carrot']
friends_foods = my_foods[:]
print(friends_foods)
my_foods.append('cannoli')
friends_foods.append('ice cream')
print(my_foods)
print(friends_foods)
# 元组
dimensions = (200, 50)
print(dimensions[0])
print(dimensions[1])
# 遍历元组
for dimension in dimensions:
    print(dimension)
# if语句
cars = ['audi', 'bmw', 'subaru', 'toyota']
for car in cars:
    if car == 'bmw':
        print(car.upper())
    else:
        print(car.title())
# 使用and、or检查多个条件
# 检查特定值是否包含在列表中
requested_toppings = ['mushrooms', 'onions', 'pineapple']
if 'mushrooms' in requested_toppings:
        print('you are true')
# 检查特定值是否不包含在列表中
banned_users = ['andrew', 'carolina', 'david']
user = 'marie'
if user not in banned_users:
    print("error")
# 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.")
# if语句处理列表
available_toppings = ['mushrooms', 'olives', 'green peppers', 'pepperoni', 'pineapple', 'extra cheese']
requested_toppings = ['mushrooms', 'french fries', 'extra cheese']
for requested_topping in requested_toppings:
    if requested_topping in available_toppings:
        print('yes')
    else:
        print('no')
# 字典
alien_0 = {'color': 'green', 'points': 5}
print(alien_0['color'])
print(alien_0['points'])
# 添加键-值对
alien_0['x_position'] = 0
alien_0['y_position'] = 25
print(alien_0)
# 创建空字典
alien_0 = {}
alien_0['color'] = 'green'
alien_0['points'] = 5
print(alien_0)
alien_0['color'] = 'red'
print(alien_0)
# 删除键-值对
del alien_0['points']
print(alien_0)
# 由类似对象组成的字典
favorite_languages = {
    'jen' : 'python',
    'sarah' : 'c',
    'edward' : 'ruby',
    'phil' : 'python',
    }
print(favorite_languages['sarah'])
# 遍历所有的键-值对
user_0 = {
    'username' : 'efermi',
    'first' : 'enrico',
    'last' : 'fermi',
    }
for key, value in user_0.items():
    print("\nKey: " + key)
    print("Value: " + value)
# 遍历字典中的所有键
print("\n")
for name in favorite_languages.keys():
    print(name.title())
# 按顺序遍历字典中的所有键
for name in sorted(favorite_languages.keys()):
    print(name.title() + ", thank you for taking the poll")
# 遍历字典中的所有值
for language in favorite_languages.values():
    print(language.title())
# 嵌套 字典列表
alien_0 = {'color' : 'green', 'points' : 5}
alien_1 = {'color' : 'yellow', 'points' : 10}
alien_2 = {'color' : 'red', 'points' : 15}
aliens = [alien_0, alien_1, alien_2]
for alien in aliens :
    print(alien)
# 30人外星人
# 创建一个用于存储外星人的空列表
aliens = []
#创建30个绿色外星人
for alien_number in range(0, 30):
    new_alien = {'color' : 'green', 'points' : 5, 'speed' : 'slow'}
    aliens.append(new_alien)
# 显示前5个外星人
for alien in aliens[:5]:
    print(alien)
print('---')
print("Total number of aliens: " + str(len(aliens)))
# 在字典中存储列表
pizza = {
    'crust': 'thick',
    'toppings': ['mushrooms', 'extra cheese'],
    }
print(pizza['toppings'])
# 在字典中存储字典
users = {
    'aeinstein' : {
        'first' : 'albert'
        },
    'mcurie' : {
        'first' : 'curie'
        },
    }
for username, user_info in users.items():
    print("\nUsername: " + username)
    full_name = user_info['first']
    print("\t" + full_name)
# 函数input()
# message = input("Tell me soething, and I will repeat it back to you: ")
print(message)
# while循环
current_number = 1
while current_number <= 5:
    print(current_number)
    current_number += 1
# 让用户选择何时退出
message = "quit"
while message != 'quit':
    print(message)
# 在列表之间移动元素
# 首先,创建一个待验证用户列表和一个存储已验证用户的空列表
unconfirmed_users = ['alice', 'brain', 'candace']
confirmed_users = []
# 验证每个用户,直到没有验证用户为止
# 将每个经过验证的列表都移到已验证用户列表中
while unconfirmed_users:
    current_user = unconfirmed_users.pop()
    print("Verifying user: " + current_user.title())
    confirmed_users.append(current_user)
# 显示所有已验证的用户
print("\nThe following users have been confiremd:")
for confirmed_user in confirmed_users:
    print(confirmed_user.title())
# 删除包含特定值的所有列表元素
pets = ['dog', 'cat', 'dog', 'goldfish', 'cat', 'rabbit', 'cat']
print(pets)
while 'cat' in pets:
    pets.remove('cat')
print(pets)
# 函数
def greet_user():
    """"显示简单的问候语"""
    print("Hello!")
greet_user()
# 向函数传递信息
def greet_user(username):
    """显示简单的问候语"""
    print("hello, " + username.title() + "!")
greet_user('jesse')
# 关键字实参
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='hamster', pet_name='harry')
# 传递列表
def greet_users(names):
    """向列表中的每位用户都发出简单的问候"""
    for name in names:
        msg = "Hello, " + name.title() + "!"
        print(msg)
usernames = ['hannah', 'try', 'margot']
greet_users(usernames)
# 传递任意数量的实参
def make_pizza(*toppings):
    """打印顾客点的所有配料"""
    print(toppings)
make_pizza('pepperoni')
make_pizza('red', 'blue', 'green')
# 使用任意数量的关键字实参
def build_profile(first, last, **user_info):
    """创建一个字典,其中包含我们知道的有关用户的一切"""
    profile = {}
    profile['first_name'] = first
    profile['last_name'] = last
    for key, value in user_info.items():
        profile[key] = value
    return profile
user_profile = build_profile('albert', 'einstein', location='princeton', filed='physics')
print(user_profile)
# 类:根据约定,首字母大写的名称指的是类
class Dog():
    """一次模拟小狗的简单尝试"""
    def __init__(self, name, age):
        """初始化属性name和age"""
        self.name = name
        self.age = age
    def sit(self):
        """模拟小狗被命令时蹲下"""
        print(self.name.title() + " is now sitting")
    def roll_over(self):
        """模拟小狗被命令时打滚"""
        print(self.name.title() + " rolled over!")
my_dog = Dog('willie', 6)
print("My dog's name is " + my_dog.name.title() + ".")
print("My dog is " + str(my_dog.age) + " years old.")
my_dog.sit()
my_dog.roll_over()
# 读取整个excel文件
import openpyxl
wb = openpyxl.load_workbook(r'data_material\data_course.xlsx')
# 获取workbook中所有的表格
sheets = wb.sheetnames
print(sheets)
# 循环遍历所有sheet
for i in range(len(sheets)):
    sheet = wb[sheets[i]]
    print('\n\n第' + str(i + 1) + '个sheet: ' + sheet.title + '->>>')
    for r in range(1, sheet.max_row + 1):
        if r == 1:
            print('\n' + ''.join(
                [str(sheet.cell(row=r, column=c).value).ljust(17) for c in range(1, sheet.max_column + 1)]))
        else:
            print(''.join([str(sheet.cell(row=r, column=c).value).ljust(20) for c in range(1, sheet.max_column + 1)]))
# 读取整个文件
with open(r'data_material\pi_digits.txt') as file_object:
    contents = file_object.read()
    print(contents.rstrip())
# 逐行读取
filename = 'data_material\pi_digits.txt'
with open(filename) as file_object:
    for line in file_object:
        print(line.rstrip())
# 创建一个包含文件各行内容的列表
with open(filename) as file_object:
    lines = file_object.readlines()
for line in lines:
    print(line.rstrip())
# 使用文件内容
pi_string = ''
for line in lines:
    pi_string += line.strip()
print(pi_string)
print(len(pi_string))
# 写入空文件
filename = 'data_material\programming.txt'
with open(filename, 'w') as file_object:
    file_object.write("I love WQ\n")
    file_object.write("YES\n")
# 附加到文件
with open(filename, 'a') as file_object:
    file_object.write("I love WQ\n")
    file_object.write("YES\n")
# 存储数据
import json
numbers = [2, 3, 5, 7, 11, 13]
filename = 'numbers.json'
with open(filename, 'w') as f_obj:
    json.dump(numbers, f_obj)
with open(filename) as f_obj:
    numbers = json.load(f_obj)
print(numbers)
# 保存和读取用户生成的数据
# 如果以前存储了用户名, 就加载它
# 否则,就提示用户输入用户名并存储它
filename = 'username.json'
try:
    with open(filename) as f_obj:
        username = json.load(f_obj)
except FileNotFoundError:
    username = input("What is your name? ")
    with open(filename, 'w') as f_obj:
        json.dump(username, f_obj)
        print("We'll remember you when you come back, " + username + "!")
else:
    print("Welcome back, " + username + "!") 
发布了13 篇原创文章 · 获赞 5 · 访问量 5233

猜你喜欢

转载自blog.csdn.net/lujiebin/article/details/102881017