电脑上安装了Python 3.7版本
Python3中input得到的为str;Python2的input的到的为int型,Python2的raw_input得到的为str类型)统一一下:Python3中用input,Python2中用row_input,都输入为str
亮常用网站:
http://www.w3school.com.cn/js/index.asp
http://www.runoob.com/regexp/regexp-tutorial.html
编辑工具用的这个 Sublime
示例:简单的hello world
print("hello world")
input("press <Enter>") #程序运行后命令窗口不自动关闭
示例:产生一个随机数,猜数字游戏
参考链接:https://wenku.baidu.com/view/d41dada5561252d381eb6ec6.html?from=search
from random import randint
num = randint(1,100) #num也可以是固定的,比如num = 10
print('猜数字游戏1~100\n')
bingo = False
while bingo == False:
answer = int(input('请输入你猜的数字:')) #input()返回的是str类型,不能直接和整数进行比较
if answer < num:
print ('too small\n')
if answer > num:
print ('too big\n')
if answer == num:
print ('Bingo!猜对啦!\n')
bingo = True
完成上述程序,基本算是开始入门了,某些细节可能并不清楚,没关系,带着一颗追求真相的心,在编程的道路上不断走下去。
示例:点球小游戏
from random import choice
score_you = 0
score_com = 0
direction = ['left','center','right']
for i in range(5):
print ('-----Round %d - You Kick! ----' % (i+1))
print ('选择一个方向射门:')
print ('left,center,right')
you = input() #输入射门方向
print ('You kicked ' + you)
com = choice(direction) #电脑随机扑救方向
print ('Computer saved ' + com)
if you != com:
print ('Goal球进了!\n')
score_you +=1
else:
print ('Oops你输了…')
score_com +=1
print ('Score:%d(you) - %d(com)\n'%(score_you,score_com))
print ('-----Round %d - You Save! ----' % (i+1))
print ('选择一个方向扑救:')
print ('left,center,right')
you = input() #输入扑救方向
print ('You saved ' + you)
com = choice(direction) #电脑随机射门方向
print ('Computer kicked ' + com)
if you == com:
print ('球救了!\n')
score_you +=1
else:
print ('Oops你输了…')
score_com +=1
print ('Score:%d(you) - %d(com)\n'%(score_you,score_com))
如果想要用Python去自动抓取某个网页上的下载链接,就需要对网页的代码进行处理,处理的过程中,免不了要在字符串和list之间进行很多操作。
示例:简单的打开写入处理文件
f = open('data.txt','a') #open('data.txt')仅仅是打开了这个文件
#w模式打开,原来文件中的内容会被新写入的内容覆盖
#a(appending模式不会覆盖之前的内容
f.write('a string you want to new write.\n')
#data = f.read() #read()函数把文件内容读进一个字符串中
#print ('%f',data)
f.close() #关闭文件,释放资源
示例:统计txt文件中学生作业的总得分
注意:for循环中结构语句换行格式不同,循环的截止位置就不同
语句与for位置对齐时表明已经在循环之外了。
f = open('scores.txt')
lines = f.readlines() #用readlines把每一行分开,便于之后的数据处理
#print ('%f',lines)
f.close()
results = []
for line in lines:
#print ('%f',line) #line为每行的字符串
data = line.split() #split()会把字符串按照空格进行分割,最终返回的字符串组成一个list
#split也可以指定按照\n,\t,.等进行分割
#print ('%f',data)
sum = 0
for score in data[1:]:
#print ('%f',score)
sum += int(score)
result = '%s \t:%d\n' % (data[0],sum)
#print ('%f',result)
results.append(result) #append()追加单个元素到list的尾部,参数可以是任何数据类型
#print ('%f',results)
output = open('result.txt','w') #w模式打开,原来文件中的内容会被新写入的内容覆盖
output.writelines(results)
output.close()
print ('goodbye')
示例:异常处理
try:
f = open('scores.txt') #可能引发异常的语句放在try块中
print ('File opened!')
f.close()
except: #处理异常的语句放在except块中
print ('File not exists.')
print('Done')
参考链接:https://blog.csdn.net/w417950004/article/details/54838858
Python的对齐方式很重要,对齐方式决定了函数或者判断条件的作用域。有缩进没有缩进区别很大!!!!
还有一个比较坑爹的地方就是Python对于多行注释的注释符来说也是需要对齐的!
待补充完善~~~