python版本3.6
运行软件spyder
# -*- coding: utf-8 -*-
"""
Created on Tue Mar 3 11:19:18 2020
@author: Administrator
"""
print("hello world")
print("hello world"+"23")
print("")
"""
运算
%取余 //取整 **乘方
"""
#循环
condition = 1
while condition <5:
print(condition)
condition+=1
#for循环
for i in range (5):
print(i)
for i in range(2,10):
print(i)
print("end")
for i in range(2,10,2):
print(i)
print("end")
for i in[1,2,3,4]:
print(i)
print("end")
for i in(1,2,3,4):
print(i)
#列表
a_list = [1,2,23,23,34,45]
print(a_list)
print(a_list[1]) #打印列表第一个元素
print(a_list[-2]) #从右往左数第二个
print(a_list[1:4]) #从第一个打印到第四个
print(a_list[:-2]) #从头打印到倒数第二个
print(len(a_list))
for content in a_list:
print(content)
print(a_list.index(23)) #打印位置
a_list.sort() #排序
print(a_list) #
a_list.sort(reverse=True)
print(a_list)
#列表操作
a_list[1] = 100 #修改元素内容
print(a_list)
a_list.append(200) #在元素末尾添加一个元素
a_list.insert(3,300) #在元素3位置插入元素
del a_list[2] #删除列表第二个元素‘
a_list.remove(1) #列表中删除一个具体的数
a = a_list.pop() #将最后一个元素出栈
print(a)
#多维数组
b_list = [[1,2,3],
[3,4,5],
[7,8,9]]
print(b_list[1]) #打印第一行的 [3,4,5]
print(b_list[1][2]) #打印第一行第二列的
#元组 能和数组一样查看元素 但是不能修改元素
a_tuple = (1,23,4,453,5)
b_tuple = 2,23,4,56,6,3
print(a_tuple[1]) #打印第一个元素
#条件语句 if ==等于 != 不等于
a = 2
b = 3
c = 5
d = 9
if a<b:
print(b)
else:
print(a)
#多条件
if a==b:
print("right")
elif a==c:
print("right")
elif a==d:
print("right")
else:
print("error")
#and or if中的使用
if a<b and a<c:
print(a)
colors = ['red','blue','black','green']
for color in colors:
if color=='black':
print(color)
break #跳出循环
elif color=='blue':
print(color)
continue #跳出单次循环
else :
print(color)
if 'red' in colors: #判断列表中是否有red若无则返回时Flase 有True
print('red')
#字典
d = {'pen':7,'apple':3,'applepen':9} #key:value 键/值
d2 = {1:'q',3:'s',2:'v'}
d3 = {23:'s','d':23,5:'2'}
d4 = {'a':[1,2,3],'b':[2,34,5],'c':{'aa':2,'ss':44}}
print(d4['c']['aa'])
d['pen'] = 39 #修改键的值
print(d)
del d['apple'] #删除一个键值对
for key,value in d.items(): #遍历整个键值对
print('key',key,'\t','value',value)
for key in d.keys(): #a遍历整个字典的键
print('key:',key)
for value in d.values(): #遍历整个字典的值
print('value',value)
for key in sorted(d2.keys()): #将键排序
print('key',key)
#函数
def function(): #定义函数
a = 2
b = 34
c = a + b
print ("c",c)
function()
def function2(a,b): #定义一个带参数的函数 a,b 为形参 (局部变量),只有在函数内部发生作用
#若函数中的局部变量和全局变量重复的话 默认使用局部变量 若要使用则加global
c = a+b
print ("c",c)
function2(23,34)
def function3(a,b=35): #设置默认值
c = a+b
print ("c",c)
function3(23)
function3(45,234)
def add(a,b):
c=a+b
return c
d = add(23,45)
print(d)
#模块 模块内为已经定义好的函数
#可以在其他文件中使用import max(模块名) 导入 然后在命令中使用max.funcmax(定义的函数名)进行操作
#或者 from max import func_max 从该模块中导入func_max中的函数 使用 直接func_max 不需模块名
#或from max import * 从该模块中导入所有的函数
#import max as m 重命名该模块
import os
print(os.getcwd())
#类
class human: #定义类
def __init__(self,name='someone',age=20): #初始化 创建对象时会执行 传入两个对象值 注init必须要前面后面两个下划线
self.name=name
self.age = age
print("human init")
# #类的属性
# name = 'someone'
# age = 100
#类的方法
def my_name(self):
print("my name is :",self.name)
def my_age(self):
print("my age is :",self.age)
def eat(self):
print("eat")
def think(self,a,b):
print(a+b)
#person1 = human() #创建一个person的对象
#person1.name
#person1.name = 'zhangsan'
#print(person1.name)
#person1.think(23,25)
person2 = human('xiaoming',10)
person2 = human(name='xiaohong',age=10)
person2.my_name()
#类的继承
class student(human): #子类继承父类
pass
stu1 = student()
stu1.my_name()
class student(human): #子类继承父类
def __init__(self,grade=1,school='MIT'):
super().__init__() #父类的初始化
self.school = school
self.grade = grade
self.scroe = 100
print("student init")
#添加子类自己的方法
def learn(self):
print('learning')
def my_school(self):
print('my school is',self.school)
#子类可以重写父类方法
def think(self,a,b):
print(a*b)
stu2 = student(4)
stu2.my_age()
stu2.learn()
stu2.my_school()
stu2.think(3,5)
#文件读写
text = 'Writing a text \n hello world'
print(text)
my_file = open('file1.txt','w') #以写入方式打开文件 如果文件不存在则会在当前文件目录创建文件 或者在指定路径创建文件
my_file.write(text)
my_file.close()
with open('file2.txt','w') as f2: # 清空文件 然后写入 使用with的话就不用使用close命令
f2.write('hahaha\n123123')
with open('file2.txt','a') as f2: # 在文件最后追加内容 使用with的话就不用使用close命令
f2.write(text)
with open('file2.txt','r') as f2: # 以读取方式打开文件 使用with的话就不用使用close命令
content = f2.read() # 读取全部内容
print(content)
with open('file2.txt','r') as f2: # 以读取方式打开文件 使用with的话就不用使用close命令
content = f2.readline() # 读取文件第一行 若要读取多行用readlines 会将所有行存放到一个列表中
print(content)
#将所有的行打印出来‘
filename = 'file2.txt'
with open(filename) as f:
for line in f:
print(line) #若要去除换行符 用line.rstrip()
#异常处理
#file = open('hahaha','r+') #先去读一个文件 如果能打开的话就可以写入显然会出现错误
try:
file = open('hahaha','r+')
except Exception as e:
print(e)
try:
file = open('hahaha','r+')
except Exception as e:
print(e)
response = input('Do you want to creat it ')
if(response=='yes'):
with open('hahaha','w') as f:
pass
print('The file was created successfully')
else:
pass
else: #如果文件没有出错
file.write('hahahahahahahahahah')
file.close()
#数据存储
import json
a_dict = {'user_id':'qdf','user_name':'assf',100:200}
with open('example.json','w')as f:
json.dump(a_dict,f)
with open('example.json')as f:
content = json.load(f)
print(content)
#猜数字小游戏
import random
n = random.randint(1,100) #生成一个1-100的随机整数
step = 0 #游戏的步数
print ('Game start')
def get_number():
guess = input('Please enter an integer from 1 to 100:')
while True:
if guess.isdigit(): #判断输入内容是否是数字
guess = int(guess)
return guess
else:
guess = input('Please enter an integer from 1 to 100:')
guess = get_number()
low=0
high=100
while True:
step+=1
print('step',step)
if guess ==0: #退出游戏
print('quit')
break
if guess<n:
print(guess,'is low')
low = guess+1
elif guess>n:
print(guess,'is high')
high = guess+1
else:
print('You win!')
break
print('You can try ',low,'to',high)
guess = get_number()
print('Game over')