一、sys.exit()提前结束程序。
#提前终止程序
import sys
while True:
print(‘Type exit to exit.‘)
response = input()
if response == ‘exit‘:
sys.exit()
else:
print(‘you typed‘+response+‘‘)
二、global语句
在函数中,如果被声明为global,则全局生效,影响函数外该变量值。
三、一个小程序,猜数字
#猜数字
import random
secretNumber=random.randint(1,20)
print(‘you thinking of 1-20‘)
for guessesTaken in range(1,7):
print(‘please input guess‘)
guess=int(input())
if secretNumber > guess:
print(‘you guess is low‘)
elif guess > secretNumber:
print(‘you guess is greate‘)
else:
break
if guess == secretNumber:
print(‘you are right,you guess in‘+str(guessesTaken)+‘guesses!‘)
else:
print(‘you are not right, this is ‘+str(secretNumber))
四、字典中的setdefault方法
字典存在则为字典中的值,不存在则为0
#setdefault()方法的使用
import pprint
message= "It is dangjingwei,this is myself,this is a boy"
count={}
for character in message:
count.setdefault(character,0)
count[character]=count[character]+1
pprint.pprint(count) ----漂亮的打印,如下,好看多了!!!
原文:https://www.cnblogs.com/dangjingwei/p/14799678.html