每天10分钟,带你一周精通Python:附录E项目答案
练习题1
from random import randint
from os import remove, rename
练习题2
def getUserScore(userName):
try:
input = open('userScores.txt',’r')
for line in input:
content = line.split(',")
if content[0] == userName:
input.close()
return content[1]
input.close()
return "-1"
except IOError:
print ("\nFile userScores.txt not
found. A new file will be created.")
input = open('userScores.txt','w')
input.close()
return "-1"
练习题3
def updateUserPoints(newUser, userName, score):
if newUser:
input = open('userScores.txt', 'a')
input.write('\n' + userName +','.+
score)
input,close()
else:
input = open('userScores.txt','r')
output = open('userScores,.tmp', 'w')
for line in input;
content = line.split(',')
if content[0] == userName:
content[1] = score
line = content[0] +','+
content[1] + ‘\n’
output.write(line)
input.close()
output.close()
remove('userScores.txt')
rename ('userScores. tmp', 'userScores.txt')
练习题4
def generateQuestion():
operandList = [0, 0, 0, 0,0]
operatorList=['','','','']
operatorDict={1:’+’,2:'-',3:'*'4:'**']
for index in range(0, 5):
operandList[index] = randint(1, 9)
for index in range(0, 4):
if index >0 and operatorList[index-
1]!='**':
operator =
operatorDict[randint(1, 4)]
else:
operator =
operatorDict[randint(1, 3)]
operatorList[index] = operator
questionString = str(operandList[0])
for index in range(1, 5):
questionString = questionString +
operatorList[index-1]+ str(operandList[index])
result = eval(questionString)
questionString=
questionString.replace("**","^”)
print ('\n’+ questionString)
userResult = input('Answer: ')
while True:
try:
if int(userResult) == result:
print ("So Smart")
return 1
else:
print ("Sorry, wrong
answer. The correct answer is", result)
return 0
except Exception as e:
print ("You did not enter a
number. Please try again.")
userResult = input('Answer:')
[练习题4.2的解释]
在operatorList中的第二个元素,即索引=1开始,这一行if index>0 and operatorList[index-1]!=’ ** '会检查operatorList中的前一个元素是否是**'符号。
如果不是的话,语句operator=operatorDict[randint(1,4)]将会执行。因为给定randint函数的范围是1到4,所以会生成数字1,2,3或者4。因此,符号“+”“_”,“*”或者“ ** ”将会分配给变量operator。
然而,如果前面的符号是“ ** ”,那么其他的语句(operator=operatorDict[randint(1,3)])将会执行。在这种情况下,输入randint函数的范围是从1到3。因此,“ ** ”符号,在operatorDict中的关键字是4,将不会被分配到operator变量中。
练习题5
try:
import myPythonFunctions as m
userName = input('''Please enter your user
name or
create a new one if this is the first time
you are running the program: ''' )
userScore = int(m.getUserScore(userName))
if userScore == -1;
newUser = True
userScore = 0
else:
newuser = False
userChoice = 0
while userChoice !='-1':
userScore += m.generateQuestion()
print ("Current Score ='',
userScore)
userChoice = input("Press Enter To
Continue or -1 to Exit:")
m.updateUserPoints (newUser, userName,
str(userScore))
except Exception as e:
print ("An unexpected error occurred.
program will be exited.")
挑战自我
对于所有的挑战,你仅仅需要修改函数generateQuestion()。下面是建议的解决方法。
def generateQuestion():
operandList = [0, 0, 0, 0, 0]
operatorList= ['','','','']
operatorDict=(1:'+',2:'-',3:'*',
4:'/', 5:'**')
result = 500001
while result > 50000 or result <-50000:
for index in range(0,5):
operandList[index] =
randint(1, 9)
for index in range(0, 4):
if index >0 and
operatorList[index-1] !='**':
operator =
operatorDict[randint(1, 4)]
else:
operator =
operatorDict[randint(1, 5)]
operatorList[index] = operator
'''
随机生成括号(和)的位置,即如果openBracket=2,
符号(将会放在第三个数字的前面如果closeBracket=3,
符号)将会被放在第四个数字的后面
因为闭括号不能在开括号前面,我们需要从openBracket
+1的位置往后生成闭括号的位置
'''
openBracket = randint(0, 3)
closeBracket=
randint(openBracket+1,4)
if openBracket == 0:
questionString='('+
str(operandList[0])
else:
questionString =
str(operandList[0])
for index in range(1, 5):
if index == openBracket:
questionString =
questionstring + operatorList[index-1]+'('+
str(operandList[index])
elif index == closeBracket:
questionString=
questionString + operatorList[index-1] +
str(operandList[index])+')'
else:
questionString =
questionString + operatorList[index-1]+
str(operandList[index])
result = round(eva1(questionString),
2)
# while循环的结尾
questionString =
questionString.replace(" ** "," ^ ")
print ('\n'+ questionString)
userResult = input('Answer (correct to 2
d.p. if not an integer):')
while True:
try:
if float(userResult) ==
result:
print ("So Smart")
return 1
else:
print ("Sorry, wrong
answer. The correct answer is", result)
return 0
except Exception as e:
print ("You did not enter a
number. Please try again.")
userResult = input ('Answer
(correct to 2 d.p. if not an integer):')
最后一件事
对于我来说,编程就像是一门艺术,也是一门科学。它非常迷人有趣。我希望可以把这份激情尽可能地分享给更多的人。 另外,在此我希望你不要停止学习。
本专栏到此结束,需要项目源代码的朋友可以私信我,免费索取。