您好,登錄后才能下訂單哦!
python實戰,用戶答題分享給大家。
主要包含內容,文件的讀取,更改,保存。不同文件夾引入模塊。輸入,輸出操作。隨機獲取數據操作
隨機生成算數表達式,用戶輸入答案,正確記錄分數,錯誤返回0,并把用戶分數記錄到文本文件中,如用戶名不存在著新建用戶
myPythonFunction.py包含三個函數
#coding=utf-8 from random import randint from os import remove,rename #function 輸入用戶名字,獲得用戶得分,返回得分或者-1 def getUserScore(userName): try: f = open("userScores.txt","r") msg = f.readline() score=-1; while len(msg): msg = msg.strip('\n') msgArr = msg.split(",") if(msgArr[0]==userName): score = msgArr[1] break msg = f.readline() f.close() return score except IOError: f=open("userScores.txt","w") f.close() return -1 #function 更新或者保存用戶名字,用戶得分 def updateUserPoints(userName,score): temp = getUserScore(userName) if(temp==-1): f = open("userScores.txt","a") msg = userName+","+str(score)+"\n" f.write(msg) f.close() else: temp = open("userScores.tmp","w") f = open("userScores.txt","r") msg = f.readline() while len(msg): msg = msg.strip('\n') msgArr = msg.split(",") if(msgArr[0]==userName): msgArr[1] = str(score) temp.write(msgArr[0]+","+msgArr[1]+"\n") msg = f.readline() f.close() temp.close() remove("userScores.txt") rename("userScores.tmp","userScores.txt") #function 獲取隨機生成的數學表達式 ,返回字符串 def getQuestionString(): operandList = [] operatorList = [] operatorDict=("+","-","*","**") questionString = '' for i in range(5): operandList.append(randint(1,9)) for j in range(4): operatorList.append(operatorDict[randint(0,3)]) for k in range(4): questionString += str(operandList[k])+operatorList[k] questionString +=str(operandList[4]) return questionString
mathGame.py作為主函數
# -*- coding:utf-8 -*- import sys if 'H:\\python\func' not in sys.path: sys.path.append('H:\\python\\func') import myPythonFunction as myfunc print("請輸入你的名字:") use = input() use=use.strip("\n") count = 0 if(myfunc.getUserScore(use)==-1): print("你是個新用戶!") myfunc.updateUserPoints(use,0) else: count = int(myfunc.getUserScore(use)) print("你當前分數為:",count) while(1): questionString=myfunc.getQuestionString() result = eval(questionString) print("問題:",questionString.replace("**","^")) print("請輸入你的答案:") userResult = input() userResult = userResult.strip("\n") flag = True if(userResult.startswith("-")): userResult = userResult[1:] flag = False while((not userResult.isdigit()) and userResult!="exit"): print("請輸入數字,你的答案:") userResult = input() userResult = userResult.strip("\n") if(userResult.startswith("-")): userResult = userResult[1:] flag = False if(not flag): userResult = "-"+userResult if(userResult==str(result)): print(1) count = count+1 elif("exit"==userResult): break else: print(0) myfunc.updateUserPoints(use,count) print("你當前分數為:",count) print("謝謝進入,歡迎下次再來!")
文件目錄結構,將myPythonFunction.py放到func文件夾中。userScores.txt存放用戶名和相應的得分
以上就是本文的全部內容,希望對大家的學習有所幫助,也希望大家多多支持億速云。
免責聲明:本站發布的內容(圖片、視頻和文字)以原創、轉載和分享為主,文章觀點不代表本網站立場,如果涉及侵權請聯系站長郵箱:is@yisu.com進行舉報,并提供相關證據,一經查實,將立刻刪除涉嫌侵權內容。