美文网首页
python基础语法

python基础语法

作者: PPFSaber | 来源:发表于2020-10-20 11:20 被阅读0次
import math
#注释

#返回数字的上入整数 5
print(math.ceil(4.1))
#返回数字的下舍整数 4
print(math.floor(4.9))
#返回数字的绝对值 3.1
print(math.fabs(-3.1))
# 平方根
print(math.sqrt(9))
# e 的x 次幂
print(math.exp(1))

import  random
#即可随机生成一个[0,1)范围内的实数
ran = random.random()
print(ran)
print(random.randint(1,20))

import time

print("hello world")
print(time.time())

a = "Hello"
b = "world"
print(a + "  " + b)
print(a *3 )
print(a[0])
#字符串截取[:] 牢记:左闭右开
print(a[1:3])
print(a[2:4])

# 判断字符串中是否包含给定的字符: in, not in
print('e' in a)
print("e" in a)
print("e" not in a)
# join():以字符作为分隔符,将字符串中所有的元素合并为一个新的字符串
new_str = '-'.join("hellow")
print(new_str)
# 字符串单引号、双引号、三引号
print('hello world')
print("hello world")
print('''hello world''')
# 三引号让程序员从引号和特殊字符串的泥潭里面解脱出来,自始至终保持一小块字符串的格式是所谓的WYSIWYG(所见即所得)格式的。

# In [ ]
print('''I'm going to the movies''')

html = '''
<HTML><HEAD><TITLE>
Friends CGI Demo</TITLE></HEAD>
<BODY><H3>ERROR</H3>
<B>%s</B><P>
<FORM><INPUT TYPE=button VALUE=Back
ONCLICK="window.history.back()"></FORM>
</BODY></HTML>
'''
print(html)
# I'm going to the movies
#
# <HTML><HEAD><TITLE>
# Friends CGI Demo</TITLE></HEAD>
# <BODY><H3>ERROR</H3>
# <B>%s</B><P>
# <FORM><INPUT TYPE=button VALUE=Back
# ONCLICK="window.history.back()"></FORM>
# </BODY></HTML>

# 转义字符 \
print("The \t is a tab")
print('I\'m going to the movies')

# 列表
# 作用:类似其他语言中的数组
#
#
# 声明一个列表,并通过下标或索引获取元素
#
names = ["jack","tom","tonney","superman","jay"]
#          0      1      2         3        4
#          -5     -4     -3        -2       -1
# 正序索引  和 逆序索引
print(names[1])
print(names[-4])

#遍历列表,获取元素
for name in names:
       print(name)
       print("a")

#查询names里面有没有superman
for name in names:
    if name == 'superman':
        print(name)
        break
else:
    print('没有超人')

#更简单的方法,来查询names里有没有superman

if 'superman' in names:
    print('有')
else:
    print('没有')

# 列表元素添加

girls = ['sdf']
#append(),末尾追加
girls.append('迪丽热巴')


#extend(),一次添加多个。把一个列表添加到另一个列表 ,列表合并。
girls.extend(["a",'b'])

#insert():指定位置添加
girls.insert(3,'御坂美琴')
# 列表元素修改,通过下标找到元素,然后用=赋值
girls[0] = 'PPF'
girls[-1] = 'PPFb'
print(girls)

# 替换
'''
将fruits列表中的‘香蕉’替换为‘banana’
'''

fruits = ['apple','pear','香蕉','pineapple','草莓']

fruits[-1] = 'strawberry'

for i in range(len(fruits)):
    if '香蕉' in fruits[i]:
        fruits[i] = 'banana'
        break
print(fruits)

# 列表元素删除
words = ['cat','hello','pen','pencil','ruler']

del  words[0]
print(words)
words.remove('pen')
print(words)
words.pop(0)
print(words)
words.pop(-1)
print(words)

# 列表切片
#
# 在Python中处理列表的部分元素,称之为切片。
#
# 创建切片,可指定要使用的第一个元素和最后一个元素的索引。注意:左闭右开
#
# 将截取的结果再次存放在一个列表中,所以还是返回列表
animals = ['cat','dog','tiger','snake','mouse','bird']

print(animals[2:5])
print(animals[-1:])
print(animals[-3:-1])
# 【-5 到 -1)  每隔2 个取一个
print(animals[-5:-1:2])


'''
需求:生成10个不同的随机整数,并存至列表中
'''
random_list = []
i = 0
while i < 10:
    ran = random.randint(1,20)
    if ran not in  random_list:
        random_list.append(ran)
        i+=1
print(random_list)


#默认升序
random_list = sorted(random_list)
print(random_list)

#降序
random_list = sorted(random_list,reverse=True)
print(random_list)


# 元组
# 与列表类似,元组中的内容不可修改

tupl =()
print(type(tupl))

tuple2 = ('hellow')
print(tuple2)

# 注意:元组中只有一个元素时,需要在后面加逗号!
tuple3 = ('hello',)
print(type(tuple3))

tuple4 = ('hellow',1,['a','b'])
print(tuple4)

# 元组不能修改,所以不存在往元组里加入元素。
#
# 那作为容器的元组,如何存放元素?

random_list = []
for i in range(10):
    ran = random.randint(1,20)
    random_list.append(ran)
print(random_list)

random_tuple = tuple(random_list)
print(random_tuple)

# 元组访问
print(random_tuple)
print(random_tuple[0])
print(random_tuple[-1])
print(random_tuple[1:-3])



print(random_tuple)
#  - 倒序 1 为取的间隔
print(random_tuple[::-1])
print(random_tuple[::1])
print(random_tuple[::2])
#  - 倒序 2 为取的间隔
print(random_tuple[::-2])

# (13, 1, 9, 16, 19, 8, 19, 3, 2, 8)
# (8, 2, 3, 19, 8, 19, 16, 9, 1, 13)
# (13, 1, 9, 16, 19, 8, 19, 3, 2, 8)
# (13, 9, 19, 19, 2)
# (8, 3, 8, 16, 1)

tup = (1,2,3) + (4,5)
print(tup) # (1,2,3,4,5)
tup = (1,2,3) * 2
print(tup) #(1, 2, 3, 1, 2, 3)
print(max(tup))
print(min(tup))
print(sum(tup))
print(len(tup))

#字典
#定义一个空字典
dict1 = {}
dict2 = {'name':'杨超越','weight':45,'age':25}
print(dict2['name'])

#list可以转成字典,但前提是列表中元素都要成对出现
dict3 = dict([('name','杨超越'),('weight',45)])
print(dict3)

dict4 = {}
dict4['name'] = '虞书欣'
dict4['weight'] = 43
print(dict4)

dict4['weight'] = 44
print(dict4)


#字典里的函数 items()  keys() values()
dict5 = {'杨超越':165,'虞书欣':166,'上官喜爱':164}
print(dict5.items())
for key,value in dict5.items():
    if value > 165:
        print(key)


for k,v in dict5.items():
     print(k,v)


#values() 取出字典中所有的值,保存到列表中

results = dict5.values()
print(results)

#求小姐姐的平均身高
heights = dict5.values()
print(heights)
total = sum(heights)
avg = total/len(heights)
print(avg)

#print(dict5['赵小棠'])      #若不存在“赵小棠”,会报错KeyError

print(dict5.get('赵小棠'))
print(dict5.get('赵小棠',170)) #如果能够取到值,则返回字典中的值,否则返回默认值170

dict6 = {'杨超越':165,'虞书欣':166,'上官喜爱':164}
del dict6['杨超越']
print(dict6)

dict6['杨超越'] = 231
print(dict6)
dict6.pop('虞书欣')
print(dict6)
# Python面向对象
# 定义一个类Animals:
#
# (1)init()定义构造函数,与其他面向对象语言不同的是,Python语言中,会明确地把代表自身实例的self作为第一个参数传入
#
# (2)创建一个实例化对象 cat,init()方法接收参数
#
# (3)使用点号 . 来访问对象的属性。

class Animal:
    def __init__(self,name):
        self.name = name
        print('实例化 animal')
    def eat(self):
        print(self.name + '狼行千里吃肉')

    def drink(self):
        print(self.name + '喝酒')


cat = Animal('Lisa')
cat.eat()
cat.drink()
print(cat.name)

class Person:
    def __init__(self,name):
        self.name = name
        print('调用父类的构造函数')

    def eat(self):
        print('调用父类的方法')

class Student(Person):
    def __init__(self):
        print('调用子类的构造函数')

    def study(self):
        print('子类方法 study')


s1 = Student()
s1.eat()
s1.study()

# Python JSON
# JSON(JavaScript Object Notation) 是一种轻量级的数据交换格式,易于人阅读和编写。
#
# json.dumps 用于将 Python 对象编码成 JSON 字符串。
import  json
data = [{'b':2,'a':1,'c':3,'d':4,'e':5,'f':6}]
js = json.dumps(data, sort_keys=True,indent=4,separators=(',', ':'))
print(js)
print(js.__class__)


# json.loads 用于解码 JSON 数据。该函数返回 Python 字段的数据类型。
text = json.loads(js)
print(text)
print(text.__class__)


# Python异常处理
# 当Python脚本发生异常时我们需要捕获处理它,否则程序会终止执行。
#
# 捕捉异常可以使用try/except语句。
#
# try/except语句用来检测try语句块中的错误,从而让except语句捕获异常信息并处理。

try:
    fh = open('/Users/p/Desktop/test3.text','w')
    fh.write('测试写')
except IOError:
    print('Error : 读写失败')
else:
    print('内容写入文件成功')
    fh.close()

# finally中的内容,退出try时总会执行
try:
    f2 = open('/Users/p/Desktop/test2.text','w')
    f2.write('测试读写')
finally:
    print('关闭读写')
    f2.close()


# Python文件操作
# 在 Python 中,读写文件有 3 个步骤:
#
# (1)调用 open()函数,返回一个 File 对象。
#
# (2)调用 File 对象的 read()或 write()方法。
#
# (3)调用 File 对象的 close()方法,关闭该文件。
f = open('/Users/p/Desktop/test4.text','w') #变量名=open(文件路径和文件名,打开模式) 模式:w:写,r:只写;a:追加写
f.write("hello")
f.write("\npython")
f.close()
f3 = open("/Users/p/Desktop/test4.text",'r')  #变量名=open(文件路径和文件名,打开模式) 模式:w:写,r:只写;a:追加写
# print(f.read())     #f.read():从文件中读入整个文件内容,结果为字符串
# print(f.readline()) #f.readline():从文件中读入一行内容,结果为字符串
print(f3.readlines()) #f.readlines():从文件中读取所有行,以每行元素形成一个列表
f3.close()

# 使用open()函数打开的文件对象,必须手动进行关闭,Python 垃圾回收机制无法自动回收打开文件所占用的资源。
#
# 因此,推荐以下写法:
with open("/Users/p/Desktop/test4.text",'a') as  f:
    f.write("python")
    f.write("\nokokok")

相关文章

网友评论

      本文标题:python基础语法

      本文链接:https://www.haomeiwen.com/subject/cnzrmktx.html