#!/usr/bin/env python3
# python 常用功能和函数
import time
import os
class Learn:
def __init__(self):
self.name = 'wlt'
# 比较
def iftest(self):
num = 10
if num > 1:
print('num > 1')
elif num == 2:
print('num==2 ')
else:
print('num <1 ')
if num < 0 or num > 10: # 判断值是否在小于0或大于10
print('hello')
else:
print('num <1 ')
# 循环
def looptest(self):
# whele 循环
count = 0
while( count < 9 ):
print('count is ', count)
count = count +1
# whele else 循环
count = 0
while count < 5:
print(count, " is less than 5")
count = count + 1
else:
print (count, " is not less than 5")
# for 循环
fruits = ['banana', 'apple', 'mango']
for item in fruits:
print(item)
# 通过序列索引迭代
for index in range(len(fruits)):
print(fruits[index])
# pass
for item in fruits:
if item == 'apple':
pass
print('this is pass ')
print(item)
# 数字
def stringtest(self):
string ='louis'
str1 = 'hello'
print(string[1])
print(string[1:4])
#字符串运算符
print(str1 + string)
print(str1 *2) #重复输入
print('l' in str1)#in
print('l' not in str1)# not in
print('xx %s',21)
print(string.islower()) #是否是小写
print(string.lower()) #转成小写小写
print(string.count('l')) #字符l的数目
# 列表,数组
def listtest(self):
list = ['hello','xx','des']
print(list)
print(list[0])
print(list[0:3])
del list[0] # 删除列表
print(len(list))#列表元素个数
list.append('ini') # 添加ini到list中
list.pop() # 添加ini到list中
# list.remove('ini') #移除ini
def dictest(self):
dic = {'Alice': '2341', 'Beth': '9102', 'Cecil': '3258'}
print(dic['Alice'])
print(len(dic))
dic.keys()
dic.values()
dic['Alice'] = 122 # 赋值
del dic['Name']; # 删除键是'Name'的条目
dic.clear(); # 清空词典所有条目
del dic ; # 删除词典
# 时间常用
def datetest(self):
localtime = time.localtime(time.time())
print (time.strftime("%Y-%m-%d %H:%M:%S", time.localtime()) )
print (time.strftime("%a %b %d %H:%M:%S %Y", time.localtime()) )
time.sleep( 5 )
# io常用
def iotest(self):
str = input("请输入:") #输入
print(str)
fo = open("xx.py", "wb")
print("文件名: ", fo.name)
print("是否已关闭 : ", fo.closed)
print("访问模式 : ", fo.mode)
fo.close()
# 打开文件
file = open("foo.txt",'r+') # 读写
file.write("www.runoob.com!\nVery good site!\n")
string = file.read(10)
print(string)
file.close()
# 文件操作
def filetest(self):
os.remove("test2.txt")
os.mkdir('xexf') #创建目录
os.rmdir('xexf') #删除目录
# 异常处理
def exceptiontest(self):
try:
file = open('xxx.txt','r')
except IOError:
print(IOError.errno)
print(IOError.filename)
else:
print('没有异常')
Test = Learn()
# Test.iftest()
# Test.looptest()
# Test.stringtest()
# Test.listtest()
# Test.dictest()
# Test.datetest()
# Test.iotest()
Test.exceptiontest()
python入门
最新推荐文章于 2024-07-22 22:58:19 发布