IT数码 购物 网址 头条 软件 日历 阅读 图书馆
TxT小说阅读器
↓语音阅读,小说下载,古典文学↓
图片批量下载器
↓批量下载图片,美女图库↓
图片自动播放器
↓图片自动播放器↓
一键清除垃圾
↓轻轻一点,清除系统垃圾↓
开发: C++知识库 Java知识库 JavaScript Python PHP知识库 人工智能 区块链 大数据 移动开发 嵌入式 开发工具 数据结构与算法 开发测试 游戏开发 网络协议 系统运维
教程: HTML教程 CSS教程 JavaScript教程 Go语言教程 JQuery教程 VUE教程 VUE3教程 Bootstrap教程 SQL数据库教程 C语言教程 C++教程 Java教程 Python教程 Python3教程 C#教程
数码: 电脑 笔记本 显卡 显示器 固态硬盘 硬盘 耳机 手机 iphone vivo oppo 小米 华为 单反 装机 图拉丁
 
   -> Python知识库 -> python笔记python基本操作 -> 正文阅读

[Python知识库]python笔记python基本操作


1.简单操作

编码情况、保留小数、字符串格式化、round函数、re正则匹配模块

#!/usr/bin/env python
#_*_ coding:utf-8 _*_
'''默认情况下,Python 源文件是 UTF-8 编码。
在此编码下,全世界大多数语言的字符可以同时用在字符串、标识符和注释中 
— 尽管 Python 标准库仅使用 ASCII 字符做为标识符,这只是任何可移植代码应该遵守的约定。
如果要正确的显示所有的字符,你的编辑器必须能识别出文件是 UTF-8 编码,
并且它使用的字体能支持文件中所有的字符。

你也可以为源文件指定不同的字符编码。为此,在 #! 行(首行)后插入至少一行特殊的注释行来定义源文件的编码:
# -*- coding: encoding -*-
通过此声明,源文件中所有的东西都会被当做用 encoding 指代的 UTF-8 编码对待。
在 Python 库参考手册 codecs 一节中你可以找到一张可用的编码列表。

例如,如果你的编辑器不支持 UTF-8 编码的文件,但支持像 Windows-1252 的其他一些编码,你可以定义:
# -*- coding: cp-1252 -*-
这样就可以在源文件中使用 Windows-1252 字符集中的所有字符了。
这个特殊的编码注释必须在文件中的 第一或第二 行定义。'''
#hello world
print("Hello World!")
message = "Hello python world"
print(message)
message = "Hello Python World!"

保留小数

#保留小数
#保留小数,并四舍五入处理
#1,字符串格式化
x = 3.1415926
print("%.2f"%x)
print("{:.2f}".format(x))
#2,round函数
print(round(x,3))
#3,decimal模块(decimal:小数的,quantize:量化)
from decimal import Decimal
a = Decimal(x).quantize(Decimal("0.00000"))
print(a)
#保留小数,不四舍五入
#1,切片
a = str(x).split(".")[0]+"."+str(x).split(".")[1][:3]
print(a)
#2,re正则匹配模块
import re
a = re.findall(r"\d{1,}?\.\d{2}",str(a))
print(a)

不换行,斐波那契子序列

#不换行,斐波那契子序列
a,b = 0,1;
while b < 10:
	print(b,end = "")
	a,b = b,a+b

5**2计算幂乘方

#/永远返回一个浮点数,若想得到整数结果,用//
#5**2计算幂乘方
x = 2**3
y = 3 + 5j
z = 2 + 6J
print(x)
print(y+z)
print(5//2)

2.变量和简单数据类型

修改大小写 合并(拼接)字符串 #添加空白 #暂时删除空格、rstrip()删头空白、lstrip()删尾空白、strip()删头尾空白
代码如下(示例):

#!/usr/bin/env python   
# _*_ coding:utf-8 _*_  
#1、为了告诉Linux系统,这个是python可执行程序
#2、为了告诉python解释器,按照utf-8编码读取源代码,否则,你在源代码中写的中文输出可能会由乱码

修改大小写

print("I told my friend,'Python is my favorite language!'\n")
name = "ada lovelace"
print(name.title())#每个单词首字母大写
print(name.lower())#变小写
print(name.upper())#变大写

合并(拼接)字符串

first_name = "Abc"
last_name = "def"
full_name = first_name+""+last_name
print(full_name)
full_name = first_name+" "+last_name
print(full_name)

添加空白

print("Python")
print("\tPython")
print("Languages:\nPython\nC\nJavaScript")

暂时删除空格、rstrip()删头空白、lstrip()删尾空白、strip()删头尾空白

language = 'Python '
print(language)
language = language.rstrip()
print(language)

使用函数str()避免类型错误

age = 18
message = "Happy " + str(age) + "th Birthday!"
print(message)

3.列表简介

#!/usr/bin/env python   
# _*_ coding:utf-8 _*_  
bicycles = ['trek','cannondale','redline','specialized']
print(bicycles)
print(bicycles[0])
print(bicycles[0].title())
print(bicycles[-1])#last
print("\n")

message = "My first bicycle was a " + bicycles[0].title() + "."
print(message)
print("\n")

bicycles[0] = "a"
print(bicycles)
print("\n")

在最后加元素:append

bicycles.append('bbq')
print(bicycles)
print("\n")

motorcycles = []
motorcycles.append('honda')
motorcycles.append('yamaha')
motorcycles.append('suzuki')
print(motorcycles)
print("\n")

插入->everywhere:insert

motorcycles.insert(0,'ducadi')
print(motorcycles)
print("\n")

删除->qu.everywhere:del

del motorcycles[0]
print(motorcycles)
print("\n")

删掉最后一个

#pop->qu.last->just like zhan(弹栈顶)
popped_motorcycle = motorcycles.pop()
print(motorcycles)
print(popped_motorcycle)
popped_motorcycle = motorcycles.pop()
print(motorcycles)
print(popped_motorcycle)
popped_motorcycle = motorcycles.pop()
print(motorcycles)
print(popped_motorcycle)
#print(motorcycles[-1])无
print("\n")

删除

#pop->qu.everywhere
abo = ['abc','w','qw']
pop_abo = abo.pop(0)
print(pop_abo)
print(abo)
print("\n")

#remove按值删元素
motor = ['honda','yamaha','suzuki','ducati']
print(motor)
motor.remove('yamaha')#motor.remove
print(motor)
too_expensive = 'ducati'
motor.remove('ducati')
print(motor)
print("\nA " + too_expensive + " is too expensive for me")
print("\n")

组织列表

#组织列表

#永久性sort(按首正/反)
cars = ["bmw",'audi','toyota','subatu']
cars.sort()
print(cars)
cars.sort(reverse = True)
print(cars)
print("\n")

#临时sorted
cars = ["bmw",'audi','toyota','subatu']
print(sorted(cars))
print(cars)
print(sorted(cars,reverse = True))
print(cars)
print("\n")

#倒着打印reverse(反转)
cars.reverse()
print(cars)

#len
print(len(cars))

4.列表操作

包含列表各种操作

#!/usr/bin/env python
#_*_ coding:utf-8 _*_

magicions = ['alice','david','carolina']
for magicion in magicions:												#maohao,suojin
	print(magicion.title()+",that was a great trick!")
print("Thank you,everyone,that's agreat magic show!")

for value in range(3,8):												#maohao!!
	print(value)
	
#创建数字列表
numbers = list(range(2,6))
print(numbers)

#1~10平方
squares = []
for value in range(1,11):
	square = value**2
	squares.append(square)
print(squares)

squares = []
for value in range(1,11):
	squares.append(value**2)
print(squares)

#min,max,sum
digits = [3,5,6,2,7,1,8,0]
print(min(digits))
print(max(digits))
print(sum(digits))

#列表解析(一行代码实现)
squares = [value**2 for value in range(1,11)]
print(squares)

#切片
print(squares[2:5])
print(squares[:2])
print(squares[3:])
print(squares[-3:])

for abc in squares[:-3]:
	print(abc)

#复制列表
my = ['fgh','hji','uui','qqw','rre','tty']
food = my[:]
print(food)

print("The first three items in the list are:")
print(my[:3])

#不可变的列表:元组
dimonsions = (200,50)
for dimonsion in dimonsions:
	print(dimonsion)
dimonsions = (400,60)
print(dimonsions[0])

5.if语句

包含列表各种操作

>>> a = 2
>>> b = 4
>>> a >= 0 and b < 1
False
>>> 
#!/usr/bin/env python
#_*_ coding:utf-8 _*_
age_0 = 3
age_1 = 6
if (age_0 >= age_1) :
	print(age_0)
else:
	print(age_1)

requested_toppings = ['mushrooms','extra cheese']
if 'mushrooms' in requested_toppings:
	print("Adding.")
if 'cabbage' not in requested_toppings:
	print("Sorry,we don't have it.")
print("\n")
	
alien_color = 'yellow'
if alien_color == 'green':
	print("You have got 5 points.")
elif alien_color == 'yellow':
	print("You have got 10 points.")
else :
	print("You have got 15 points.")

available = ['mushrooms','olives','green peppers','pepproni','pineapple','extra cheese']
requests = []
print("Please input 3 kinds of needs.\n")
for i in range(3):
	print("please input")
	temp = input()
	requests.append(temp)
print(requests)
for request in requests:
	if request in available:
		print("Adding" + request + ".")
	else:
		print("Sorry,we don't have " + request + ".")
print("Finished making your pizza!")

6.字典

字典相关操作,字典列表等包含列表各种操作

#!/usr/bin/env python
#_*_ coding:utf-8 _*_
alien_0 = {"color":"green",'point':5}
print(alien_0['color'])
print(alien_0['point'])
newpoint = alien_0['point']
print("You just earned "+str(newpoint)+" points!")
print("\n")

alien_0['x_position'] = 0	#添加键值对
alien_0['y_position'] = 25
print(alien_0)

alien_0['color'] = 'yellow'	#修改字典中的值
print(alien_0)	

del alien_0['point']	#删除键值对
print(alien_0)

user_0 = {'username':'efermi','first':'enrico','last':'fermi'}
for key,value in user_0.items():	#遍历键值对
	print("\nkey:"+key)
	print("Value:"+value)
print('\n')

favorite_language = {'jen':'python','sarah':'c','edward':'ruby','phil':'python'}
for name,language in favorite_language.items():	#值
	print(name.title()+"'s favorite langusge is "+language.title()+".")

for name in favorite_language.keys():	#键
	print(name.title())

for name in sorted(favorite_language.keys()):
	print(name.title()+",thamk you for taking the poll.")
print("\n")

favorite_language = {'jen':'python','sarah':'c','edward':'ruby','phil':'python'}
print("The following languages have been mentioned:")
for language in favorite_language.values():
	print(language.title)
#??

for language in set(favorite_language.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)
print('\n')
	
#现实:自动生成
aliens = []
for alien_number in range(30):
	new_alien = {'color':'green','points':5,'speed':'slow'}
	aliens.append(new_alien)
	
for alien in aliens[:3]:
	if alien['color'] == 'green':
		alien['color'] = 'yellow'
		alien['speed'] = 'medium'
		alien['points'] = 10
	elif alien['color'] == 'yellow':
		alien['color'] = 'red'
		alien['apeed'] = 'fast'
		alien['points'] = 15
		
for alien in aliens[:5]:
	print(alien)
print("...")
print("Total number of aliens: "+str(len(aliens)))
print("\n")

#字典中存列表:pizza
pizza = {
	'crust':'thick',
	'toppings':['mushrooms','extra cheese'],
	}
print('You ordered a '+pizza['crust']+'-crust pizza '+'with the following toppings:')
for topping in pizza['toppings']:
	print('\t'+topping)
#favorite_languages
favorite_languages = {
	'jen':['python','ruby'],
	'sarah':['c'],
	'edward':['ruby','go'],
	'phil':['python','haskell'],
	}
for name,languages in favorite_languages.items():
	if(len(languages) == 1):
		print("\n"+name.title()+"'s favorite language is:")
	else:
		print("\n"+name.title()+"'s favorite languages are:")
	for language in languages:
		print("\t"+language.title())

在字典存储


#在字典中存储字典:用户名与信息
users = {
	'aeinstein':{
		'first':'albert',
		'last':'einstein',
		'location':'princeton',
		},
	'mcurie':{
		'first':'marie',
		'last':'curie',
		'location':'paris',
		},
	}
for username,user in users.items():
	print("\nUsername:"+username)
	full_name = user['first']+' '+user['last']
	location = user['location']
	print("\tFull name:"+full_name.title())
	print("\tLocation:"+location.title())

例子

#	city
cities = {
	'beijing':{
		'country':'China',
		'population':'a',
		'fact':'o',
		},
	'New York':{
		'country':'America',
		'population':'b',
		'fact':'p',
		},
	'Paris':{
		'country':'France',
		'population':'c',
		'fact':'q',
		},
	}
for CityName,city in cities.items():
	print("\ncity:"+CityName)
	country = city['country']
	population = city['population']
	fact = city['fact']
	print("\tcountry:"+country.title())
	print("\tpopulation:"+population.title())
	print("\tfact:"+fact.title())

相关资料整理

1.简单操作
2.变量和简单数据类型
3.列表简介
4.列表操作
5.if语句
6.字典

  Python知识库 最新文章
Python中String模块
【Python】 14-CVS文件操作
python的panda库读写文件
使用Nordic的nrf52840实现蓝牙DFU过程
【Python学习记录】numpy数组用法整理
Python学习笔记
python字符串和列表
python如何从txt文件中解析出有效的数据
Python编程从入门到实践自学/3.1-3.2
python变量
上一篇文章      下一篇文章      查看所有文章
加:2021-12-05 12:00:09  更:2021-12-05 12:01:45 
 
开发: C++知识库 Java知识库 JavaScript Python PHP知识库 人工智能 区块链 大数据 移动开发 嵌入式 开发工具 数据结构与算法 开发测试 游戏开发 网络协议 系统运维
教程: HTML教程 CSS教程 JavaScript教程 Go语言教程 JQuery教程 VUE教程 VUE3教程 Bootstrap教程 SQL数据库教程 C语言教程 C++教程 Java教程 Python教程 Python3教程 C#教程
数码: 电脑 笔记本 显卡 显示器 固态硬盘 硬盘 耳机 手机 iphone vivo oppo 小米 华为 单反 装机 图拉丁

360图书馆 购物 三丰科技 阅读网 日历 万年历 2024年11日历 -2024/11/16 3:18:19-

图片自动播放器
↓图片自动播放器↓
TxT小说阅读器
↓语音阅读,小说下载,古典文学↓
一键清除垃圾
↓轻轻一点,清除系统垃圾↓
图片批量下载器
↓批量下载图片,美女图库↓
  网站联系: qq:121756557 email:121756557@qq.com  IT数码