Python 基础学习
基础知识
使用eclipse运行helloword.py时的报错
- 问题:SyntaxError: Non-UTF-8 code starting with ‘\xc4’ in file
- 解决方案:设置文件的编码格式为UTF-8
第一步:将文件的编码格式修改为UTF-8
第二步:
在对应的python文件中加上注解
# -!- conding: UTF-8 -!-
'''coding:UTF-8'''
Python的命名规范
- 变量名只能包含字母、数字和下划线。变量名可以字母或下划线打头,但不能以数字打头
- 变量名不能包含空格,但可使用下划线来分隔其中的单词。
- 不要将Python关键字和函数名用作变量名。
- 变量名应既剪短又具有描述性。
- 慎用小写字母l和大写字母O,因为他们可能被人错看成数字1和0.
字符串常用的方法
- title() 字符串的首字母大写
- upper() 所有字符都变成大写
- lower() 所有字符都变成小写
- “\t”制表符 “\n”换行
- strip() 去掉字符串两端的空白
- lstrip() 剔除字符串开头的空白
- rstrip()剔除字符串右端的空白
运算
- “+”
- “-”
- “*”
- “/”
【Python2】整数除法的结果只包含整数部分,小数部分被删除,请注意采取的方式不是四舍五入,而是将小数部分直接删除。为了避免这种情况,务必确保至少有一个操作数为浮点数
【Python3】这种整数可以获取到小数部分。 - “**” 乘方运算
- “%”求模运算
number = input("Enter a number,and I'll tell you if it's even or odd:")
number = int(number)
if number%2 ==0:
print("\nThe number "+str(number)+" is even.")
else:
print("\nThe number "+str(number)+" is odd.")
类型转换方法
- str() 将数字转换为字符串
- int() 将字符串转换为数字
列表
列表的下标
列表开始的下标是0(正着数);下标为-1是访问倒数第一个数值,-2,-3依次是倒数第
二,倒数第三
.列表中常用的方法:
- 修改 :List[下标值] = “新的值”
- 添加元素:
(1)使用append的方式进行添加
#列表中添加元素append()方法
motorcycles =[]
motorcycles.append("ducati")
motorcycles.append("yanaha")
motorcycles.append("suzuki")
print(motorcycles)
(2)使用insert的方式进行添加
motorcycles =[]
motorcycles.append("ducati")
motorcycles.append("yanaha")
motorcycles.append("suzuki")
#
# print(motorcycles)
#列表中插入元素
motorcycles.insert(3, 'hhhh')
print(motorcycles)
列表中元素的删除
如果你要从列表中删除一个元素,且不再以任何方式使用它,就是用del语句;如果你要在删除元素后还能继续使用它,就是使用方法pop()
(1)del()方法:del从列表中删除后,就无法使用了
motorcycles =[]
motorcycles.append("ducati")
motorcycles.append("yanaha")
motorcycles.append("suzuki")
#
# print(motorcycles)
#删除元素
del motorcycles[0]
print(motorcycles)
(2)pop方法:从列表中删除后仍可以使用该元素
poped_motorcycles=motorcycles.pop()
print(motorcycles)
print(poped_motorcycles)
(3)根据元素值来删除remove()
too_expensive ='hhhh'
motorcycles.remove(too_expensive)
print(motorcycles)
print("\nA "+too_expensive.title()+" is too expensive for me.")
列表排序
1)sort()对列表进行永久性排序
motorcycles.sort()
print(motorcycles)
motorcycles.sort(reverse=True)
print(motorcycles)
2)sorted()对列表进行临时排序
print("Here is the original list:")
print(motorcycles)
print("\n Here is the sorted list:")
print(sorted(motorcycles))
print("\n Here is the original list:")
print(motorcycles)
倒着打印列表:reverse(),永久性修改列表元素的排列顺序
列表的长度:len()
使用循环去输出一个列表:
magicians =['alice','david','carolina']
for magician in magicians:
print(magician)
range()函数的使用:
1)用于生成一个数字的序列:
numbers = list(range(1,6))
print(numbers)
2)用于生成步长为某一固定值得序列:
even_numbers = list(range(2,11,2))
print(even_numbers)
列表解析:
squares =[value**2 for value in range(1,11)]
# for value in range(1,11):
# squares.append(value**2)
print(squares)
列表的切片: 切片格式:list[下标一:下标二] 下表1为0表示切片从列表的第一个元素开始;下表二为0表示切片从列表的截止至最后一个元素;下表1为-3,表示切片从倒数第三个值开始的。
players =['charles','martina','michael','florence','eli']
print(players[0:3])
列表的复制:对比eg1和eg2会发现,类比于Java中的变量,第一种相当于新建了一个空间存储friend_foods,第二种相当于将第一个变量my_foods的地址赋值给了friend_foods.
eg1:
my_foods = ['pizza','falafel','carrot cake']
friend_foods =my_foods[:]
my_foods.append('cannoli')
friend_foods.append('ice cream')
print("My favorite foods are:")
print(my_foods)
print("\nMy friend's favorite foods are:")
print(friend_foods)
eg2:
my_foods = ['pizza','falafel','carrot cake']
friend_foods =my_foods
my_foods.append('cannoli')
friend_foods.append('ice cream')
print("My favorite foods are:")
print(my_foods)
print("\nMy friend's favorite foods are:")
print(friend_foods)
元组
元组看起来犹如列表,但是用圆括号而不是方括号来标识。定义元组后,就可以像访问列表元素一样。
语法
dimensions =(200,50)
print(dimensions[0])
print(dimensions[1])
特性:不能直接修改某个元素的值【eg1会报错】,但可以重新赋值【eg2会执行成功】。
eg1:dimensions[0] =250
TypeError: ‘tuple’ object does not support item assignment:元组不支持分配
dimensions =(200,50)
print(dimensions[0])
print(dimensions[1]
eg2: dimensions =(400,100),重新赋值dimensions
dimensions =(200,50)
print("Original dimensions:")
for dimension in dimensions:
print(dimension)
dimensions =(400,100)
print("\nModified dimensions:")
for dimension in dimensions:
print(dimension)
元素与列表的区别:元祖不可更改,列表可更改!!!
if语句
- 在Python种检查时会区分大小写
cars =['audi','bwn','subaru','toyato']
for car in cars:
if car == 'bnw':
print(car.upper())
else:
print(car.title())
IF判断中常用的判断类型
1.两个值相等:
参看上一个代码块部分
2.两个值不相等:
requested_topping ='mushroom'
if requested_topping != 'anchovies':
print("Hold the anchovies!")
3.短路与:
age_0 = 22
age_1 = 18
age_0 >= 21 and age_1>=21
age_1=22
age_0 >= 21 and age_1 >=21
4.短路或:
age_0 = 22
age_1 = 18
age_0 >= 21 or age_1>=21
age_1=22
age_0 >= 21 or age_1 >=21
5.检查特定值是否在列表中
requested_toppings =['mushrooms','onlions','pineapple']
print('mushrooms' in requested_toppings)
IF语句的种类
1)IF-ELSE语句:
age = 19
if age >= 18:
print("You are old enough to vote!")
print("Have you registered to vote yet!")
else:
print("Sorry,you are too young to vote.")
print("Please register to vote as soon ")
2)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.")
字典
alien_0 ={'color':'green','points':5}
print(alien_0['color'])
print(alien_0['points'])
字典的读取:字典名【键名】
alien_0 ={'color':'green','points':5}
new_points =alien_0['points']
print("You just earned "+str(new_points)+" points!")
添加键-值对
alien_0 ={'color':'green','points':5}
# new_points =alien_0['points']
# print("You just earned "+str(new_points)+" points!")
#添加键-值对
alien_0['x_position'] = 0
alien_0['y_position'] = 250
print(alien_0)
修改字典中元素的值
alien_0 ={'color':'green','points':5}
#修改字典中的颜色
alien_0['color'] = 'yellow'
print('The alien is now '+alien_0['color']+'.')
删除键值对
alien_0 ={'color':'green','points':5}
print(alien_0)
del alien_0['points']
print(alien_0)
遍历键-值对
user_0 ={
'username':'efemi',
'first':'enrico',
'last':'femi'}
for key,value in user_0.items():
print("\nkey:"+key)
print("Value:"+value)
遍历所有的键
for name in favorite_languages.keys():
print(name.title())
遍历所有的值
set()可以用来去重。
print("The following languages have been mentioned:")
for language in favorite_languages.values():
print(language.title())
---------------------------———————对比上下代码块的执行结果——-———————-------------------
print("The following languages have been mentioned:")
for language in set(favorite_languages.values()):
print(language.title())
嵌套
1)列表里面有字典
#创建一个用于存储外星人的空列表
aliens = []
a = []
#创建30个绿色的外星人
for alien_number in range(30):
new_alien = {'color':'green','points':5,'speed':'slow'}
aliens.append(new_alien)
for alien in aliens[0:3]:
if alien['color'] == 'green':
alien['color'] ='yellow'
alien['speed'] = 'medium'
alien['points'] =10
elif alien['color'] == 'yellow':
alien['color'] = 'red'
alien['speed'] = 'fast'
alien['points'] = 15
#显示前五个外星人
for alien in aliens[:5]:
print(alien)
print("___________")
#显示创建了多少个外星人
print("Total number of aliens:"+str(len(aliens)))
2)字典里面有列表
favorite_languages ={
'jen':['python','ruby'],
'sarah':['c'],
'edward':['ruby','go'],
'phil':['python','haskell']
}
for name,languages in favorite_languages.items():
print("\n"+name.title()+"'s favorite language are:")
for language in languages:
print("\t"+language.title())
3)字典里面有字典
users ={
'aeinstein':{
'first':'albert',
'last':'einstein',
'location':'princeton'}
,
'mcurie':{
'first':'marie',
'last':'curie',
'location':'paris'}}
for username,user_info in users.items():
print("\nUsername:"+username)
full_name = user_info['first']+' '+user_info['last']
location =user_info['location']
print('\t Full name:'+full_name.title())
print('\t Location:'+location.title())
While循环
curren_number = 1
while curren_number <= 5:
print(curren_number)
curren_number += 1
退出循环的方式
1)使用标志:
prompt ='\n Tell me something,and I will repeat it back to you:'
prompt += '\nEnter "quit" to end the program。'
active = True
while active:
message = input(prompt)
if message == 'quit':
active = False
else:
print(message)
2)使用break跳出循环
#使用break
prompt ="\nPlease enter the name of city you have visited:"
prompt += "\n(Enter 'quit' when you are finished.)"
while True:
city = input(prompt)
if city == 'quit':
break
else:
print("I'd love to go to"+city.title()+'.')
3)使用continue来结束本次循环
current_number = 0
while current_number < 10:
current_number += 1
if current_number % 2 ==0:
continue
print(current_number)
While循环的应用
应用一:
#首先,创建一个待验证的用户列表
#和一个用于存储已验证用户的空列表
unconfirmed_users = ['alice','brian','candace']
comfirmed_users =[]
#验证每个用户,直到没有未验证的用户为止
#将每个经过验证的列表都移到已验证的用户列表中
while unconfirmed_users:
current_user =unconfirmed_users.pop()
print("Verifying user "+current_user)
comfirmed_users.append(current_user)
#显示所有已验证的用户
print('\nThe following users have been confirmed:')
for comfirmed_user in comfirmed_users:
print(comfirmed_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 favorite_book(book_name):
print("One of my favorite books is "+book_name)
favorite_book("Alice in Wonderland")
- 同一个函数的不同调用方法:
函数:
def describe_pet(animal_type,pet_name):
"""显示宠物信息"""
print("\nI have a "+animal_type+".")
print("My "+animal_type+"'s name is "+pet_name+"。")
1)位置参数:调用函数时,传入的参数位置要相匹配。
describe_pet('hamster', 'harry')
2)关键字参数:调用函数时,采用关键字的方式传入参数,位置就可以打乱。
describe_pet(animal_type='hamster', pet_name='harry')
describe_pet(pet_name='harry',animal_type='hamster')
3)默认值:注意,这里的默认参数必须放在非默认参数后面,便于Python解读出来位置参数
def describe_pet(pet_name,animal_type='dog'):
"""显示宠物的信息"""
print("\n I have a "+animal_type+".")
print("My "+animal_type+"'s name is "+pet_name+".")
describe_pet(pet_name='willie')
- 使用列表副本的应用
def print_models(unprinted_designs,completed_models):
"""模拟打印每个设计,直到没有未打印的设计为止
打印每个设计后,都将其移到表compeleted_models中"""
while unprinted_designs:
current_design =unprinted_designs.pop()
#模拟根据设计制作3D打印模型过程
print("Printing model:"+current_design)
completed_models.append(current_design)
def show_completed_models(completed_models):
"""显示打印好的所有模型"""
print("\nThe following models have been printed:")
for completed_model in completed_models:
print(completed_model)
unprinted_designs = ['iphone case','robot pendant','dodecahedron']
completed_models = []
print_models(unprinted_designs[:], completed_models) ##重点在这里
show_completed_models(completed_models)
print(unprinted_designs)#校验原始列表是否被更改
- 传递任意数量的实参:形参*toppings中的星号让Python创建一个名为toppings的空元组,并将收到的所有值都封装到这个元组中
def make_pizza(*toppings):
"""打印顾客点的所有配料"""
print(toppings)
make_pizza('pepperoni')
make_pizza('mushrooms','green peppers','extra cheese')
类
创建类
class Dog():
def __init__(self,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.tile()+" rolled over!")
mydog =Dog('willie',6)
print("My dog's name is "+mydog.name.title()+".")
print("My dog is "+str(mydog.age)+" years old.")
Python中日期
实参 | 含义 |
---|---|
%A | 星期的名字,如Monday |
%B | 月份名,如January |
%m | 用数字表示的月份(01~12) |
%d | 用数字表示月份中的一天(01-31) |
%Y | 四位的年份,如2015 |
%y | 两位的年份,如15 |
%H | 24小时制的小时数(00-23) |
%I | 12小时制的小时数(01-12) |
%p | am或pm |
%M | 分钟数(00~59) |
%S | 秒数(00~61) |