python基础语法

系列文章目录

提示:这里可以添加系列文章的所有文章的目录,目录需要自己手动添加
第一章 基础变量简单数据类型
第二章:列表的简介和对列表的一些操作
第三章:操作列表和元组的介绍
第四章:if-elif-else语句的使用
第五章:字典的使用
第六章:用户输入和while循环的使用(input)
第七章:函数的定义和导入函数模块
第八章:类的定义和使用(初步介绍,面向对象不介绍)


0ce21e5b-b454-4199-b1bf-a4d2da13bb50


前言

提示:本文章仅当作学习用途,欢迎各位大佬指正


一、变量

1.变量的命名

1、不能以数字打头,不能命名为1_message
2、变量名不能包含空格

2.修改字符串的方法

字符串的输出需要f 才可以正常输出
比如:

name = "神仙”
name2 = "牛鬼"
name = f"{name}{name2}"
name = "Ada Lovelace"
print(name.title())
print(name.upper())
print(name.lower())

print函数的end参数
包含end=’ '作为Python内置函数BIF(Built-in function) print()的一个参数,会使该函数关闭“在输出中自动包含换行”的默认行为。其原理是:为end传递一个空字符串,这样print函数不会在字符串末尾添加一个换行符,而是添加一个空字符串。这个只有Python3有用,Python2不支持。

print("hello")
print("world")
#print("hello",end="")
#print(" world")

3.数据类型

1.整数、浮点数
在python里面两个乘号(**)表示乘方运算
2.数的下划线
univer = 14_000_000_000
打印时不会有下划线

二、列表的简介和对列表的一些操作

1.列表的概念:

1.列表是由一系列按特步顺序排列的元素组成。
2.列表元素的访问

bicycles = ['trek','cannonable','redline','specialized']
print(bicycles[0].lower())
#倒数第一个元素
print(bicycles[-1].lower())

2.列表元素的修改

2.1在列表末尾添加元素
append()

motorcycles = ['ducati','honda','yamaha','suzuki']
# print(motorcycles[3])
motorcycles.append('帅哥')

2.2在列表中插入元素
insert()

motorcycles = ['ducati','honda','yamaha','suzuki']
motorcycles.insert(0,'大勇')

2.3在列表中删除元素
del语句

motorcycles = ['ducati','honda','yamaha','suzuki']
del motorcycles[0]

2.4采用pop()方法删除元素

#默认弹出列表的最后一个元素
motorcycles = ['ducati','honda','yamaha','suzuki']
poped_motorcycles = motorcycles.pop()
#打印出弹出元素
print(poped_motorcycles)
#弹出任意位置的元素
#poped_motorcycles = motorcycles.pop(2)

2.5根据值删除元素
remove()

motorcycles = ['ducati','honda','yamaha','suzuki']
#一般可能会再次使用它的值,一般会指出删除的原因。
motorcycles.remove('ducati')
print(motorcycles)

3.对列表进行排序、组织

3.1使用sort()对列表进行永久排序

cars = ['bmw','audi','toyota','subaru']
cars.sort()
print(cars)

3.2使用sorted对列表进行临时排序

cars = ['bmw','audi','toyota','subaru']
print(cars)
print(sorted(cars)

3.3倒序打印列表
reverse()

cars = ['bmw','audi','toyota','subaru']
cars.reverse()
print(cars)

3.4确实列表的长度

cars = ['bmw','audi','toyota','subaru']
print(len(cars)

三.操作列表和元组的介绍

1.用循环操作列表(切记不要忘记冒号和缩进的问题)

1.1用for循环遍历列表以及做一些操作

magicians = ['alice','david','carlina']
for magician in magicians:
	print(f"{magician.upper()}, that was a great trick!")
	print(magician)

2.用range()函数

2.1 range()函数的使用

for value in range (1,6):
    print(value)
    #创建列表
numbers  = list(range(1,6))
print(numbers)

2.2range()函数的具体使用以及简单数值操作


#range(2,11,2)表示生成2到10的数,而且是2,4,6,8,10递增加2的数 
even_numbers = list(range(2, 11,2))
print(even_numbers)
numbers = list(range(1,6,2))
print(numbers)

简单计算:专门的操作数字列表的函数

nums = [1,2,3,4,5,6,7,8,9]
#最小
min(nums)
#最大
max(nums)
#列表求和
sum(nums)

3.列表切片

3.1遍历切片的基础使用

players = ['charles','martina','michael','florence','eli']
print("Here are the first three players on my team:")
for player in players[0:3]:
    print(player.lower())
#也可以查找列表的后面3人
# print(players[-3:])

3.2复制列表的使用
主要可以利用切片创建一个原来列表的副本,

my_foods = ['pizza','falafel','carrot cake','haha']
# 创建副本
friend_foods = my_foods
friend_foods = my_foods[:]
my_foods.append('cannoli')
friend_foods.append('ice crem')
print("My favorite food are:")
# 得到两个列表食品
print(my_foods)
print("\nMy_friend's favorite foods are:")
print(friend_foods)

4.元组使用

定义:Python把不能修改的值成为不可变的,而不可变的列表就被称为元组。
修改元组的变量

dimensions = (200,50)
for dimension in dimensions:
    print(dimension)
# 元组不能修改的操作,z这样的操作是被禁止的
# dimensions[0] = 250

dimensions = (400,100)
for dimension in dimensions:
    print(dimension)

四.if-elif-else语句的使用

4.1 等于和不等于的使用

cars = ['audi', 'bmw', 'subaru', 'toyota']

for car in cars:
    # if car != 'bmw':
    if car == 'bmw':
        print(car.upper())
    else:
        print(car.title())
    ```
### 4.2 检验多个条件的使用
1.and , or , 的使用
```python
e_0 = 21
age_1 = 22
if age_1>=21 and age_0<22 :
    print("true")
if age_1>21 or age_0> 22:
    print("true")
  1. 检验特定值在不在列表中( in , not in )
banned_users = ['andrew','carlina','david']
user = 'andrew'
#判断列表中有无这个特定值
if user in banned_users:
   print("true")
if user not in banned_users:
   print(f"{user.title()}, you can post a response if you wish.")

3.简单if-elif-else语句(分清True 和False)

age = 25

if age<4:
    print("Your admission cost is $0.")
elif age>=4 and age<12:
    print("Your admission cost is $25.")
elif age>=12 and age<18:
	print("你好!")
elif age>=18 and age <35:
    print(" my son,你好")
else:
    print("Your admission cost is $40.")

num1 = 12
# 有些时候else语句可以发挥很大的作用
for num in a:
    if num == num1:
        print(num1)
else:
    print("hh")

五.字典的相关操作和使用

5.1字典的定义和访问

定义:字典是一系列键-值对,用键来访问与之相联的值。

#创建字典以及字典键值访问
alien_0 = {'x_position': 0, 'y_position': 25, 'speed': 'medium'}
print(f"Original position: {alien_0['x_position']}")
# 添加字典元素,修改也同样道理
alien_0['z_position'] = 20

5.2遍历字典中键 和值

遍历items()中主要注意键-值

favorite_languages = {
    'jen':['python','rudy'],
    'sarah':['c'],
    'edward':['rudy','c'],
    'phil':['python','haskell'], 
    }
# 方法items()返回一个键对列表
for name,languages in favorite_languages.items():
    print(f"\n{name.title()}'s favorite language are")
    length = len(languages)
    if length ==1:
        print(f"{languages[length-1].title()}")
    else:
        for language in languages:
            print(f"\t{language.title()}")

keys()方法和values()方法

favorite_languages = {
    'jen':['python','rudy'],
    'sarah':['c'],
    'edward':['rudy','c'],
    'phil':['python','haskell'], 
    }
#遍历字典中所有键
for name in favorite_languages.keys():
	print(f"Hi {name.title()}")
#遍历字典中的值
for language in favorite_languages.values():
    print(language.title())

5.3 字典的嵌套

1.字典列表,在列表中存字典

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)

2.在字典中存放列表

favorite_languages = {
    'jen': 'python',
    'sarah': 'c',
    'edward': 'ruby',
    'phil': 'python',
    }
#先遍历里面的键和列表
for name,languages in favorite_languages.items():
    print(name.title())
    # languages当成一个列表来看
    for language in languages:
        print(language.title())

3.在字典中存放字典

users = {
    'aeinstein':{
        'first':'albert',
        'last':'einstein',
        'location': 'princeton',
    },
    'mcurie':{
        'first':'marie',
        'last':'curie',
        'location':'paris',
    },
}
#先遍历键和其中的字典,user_info就是字典了
for username, user_info in users.items():
    print(f"\nUsername :{username}")
    full_name = f"{user_info['first']}{user_info['last']}"
    location = user_info['location']
    print(f"\t full_name:{full_name.title()}")
    print(f"\tlocation:{location.title()}")

六. 用户输入input和while循环

7.1函数input()的一些原理

prompt = "If you tell us who you are, we can personnalize the message you see."
prompt +="\nWhat is first name?"
#input()方法可以获取文本输入
name = input(prompt)
print(f"\nHello, {name}\n!")

7.2 while循环和break、continue

#用True和False来判断循环结束
prompt = "\n告诉我一些事情,我会重复给你:"

active = True
while active:
    message = input(prompt)
    if message == 'quit':
        #active = False
        break
        #continue
    else:
        print(message)

7.3while循环处理列表和字典

# 先从需要验证的用户开始,
# 和一个空列表来保存已确认的用户
unconfirmed_users = ['alice', 'brian', 'candace']
confirmed_users = []
# 验证每个用户,直到没有未确认的用户为止。
# 将每个已验证的用户移动到已确认的用户列表中。
while unconfirmed_users:
    current_user = unconfirmed_users.pop()
    #删除操作
    #unconfirmed_users.remove('alice')
    
    print(f"验证用户: {current_user.title()}")
    confirmed_users.append(current_user)
#显示所有已确认的用户。
print("\n以下用户已确认:")
for confirmed_user in confirmed_users:
    print(confirmed_user.title())

7.4使用用户输入来填充字典

responses = {}
# 设置一个标志以指示轮询处于活动状态。
polling_active = True

while polling_active:
    # 提示输入此人的姓名和回复。
    name = input("\n你叫什么名字 ")
    response = input("哪天你想爬哪座山?  ")
    
    # 将响应存储在字典中
    responses[name] = response
    
    # 看看是否还有其他人要参加投票
    repeat = input("你想让另一个人回应吗? (是/否) ")
    if repeat == 'no':
        polling_active = False
#投票完成。显示结果。 
print("\n--- 投票结果----")
for name, response in responses.items():
    print(f"{name} 想爬 {response}.")

七.函数的定义和导入函数模块

7.1函数的定义def和传递参数

参数又分形参和实参

#传递位置实参(顺序非常重要)
def describe_pet(pet_name, animal_type):
    """显示有关宠物的信息。"""
    print(f"\nI have a {animal_type}.")
    print(f"My {animal_type}'s name is {pet_name.title()}.")
    
describe_pet('willie','dog')
#关键字实参,这样就可以和名称和值关联起来
describe_pet(animal_type = '犬',pet_name = '二哈')

传递任意数量的参数

#主要是*toppings
def make_pizza(size, *toppings):
    """总结一下我们要制作的披萨。"""
    print(f"\n制作一个 {size}-英寸比萨饼配以下配料:")
    for topping in toppings:
        print(f"- {topping}")
make_pizza(15,"番茄")
make_pizza(15,'番茄','绿豆')

7.2 函数的返回值

1.返回简单值

def get_formatted_name(first_name, last_name, middle_name = ''):
    """返回整洁的名字."""
    if middle_name:
        full_name = f"{first_name}{middle_name}{last_name}"
    else:
        full_name = f"{first_name}{last_name}"
    #返回全名
    return full_name.title()
musician = get_formatted_name('李','龙','云')
print(musician)
musician = get_formatted_name('汪','峰')
print(musician)
  1. 返回字典
def build_person(first_name, last_name,age = None):
    """返回一个字典, 其中包含一个人的所有信息。"""
    person = {'first':first_name, 'last':last_name}
#更新字典的值
    if age:
        person['age'] = age
    return person
musician = build_person('大', '勇',age = 20)
print(musician)

7.3传递列表

def greet_users(names):
    for name in names:
        msg = f"Hello,{name.title()}!"
        print(msg)
    print(names)
usernames = ['张飞', '韩信', '李白']
greet_users(usernames)
#有时候需要禁止函数修改列表,所以可以传递原来列表的副本,对副本修改不会影响到源#列表。
greet_users(usernames[:]) 

7.4导入函数模块

from module_name import function_name
使用as 给函数指定别名
导入函数中所有函数

from pizza import *

总结

提示:这里对文章进行总结:
以上就是python的基础语法了,文件操作的话还没有更新,后期如果需要的话我再更新,如果出现问题的话,欢迎各位大佬指正,本文章是学习的过程中写的。

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值