這是一個相當完整的實現:
import csv
import random
import sys
if sys.hexversion < 0x3000000:
# Python 2.x
inp = raw_input
rng = xrange
opencsvfile = lambda fname: open(fname, "rb")
else:
# Python 3.x
inp = input
rng = range
opencsvfile = lambda fname: open(fname, newline='')
NUM_ANSWERS = 4
def read_csv_file(fname):
with opencsvfile(fname) as inf:
incsv = csv.reader(inf)
for row in incsv:
yield row
def get_yn(prompt):
while True:
response = inp(prompt).strip().lower()
if response in {'y','yes'}:
return True
elif response in {'n','no'}:
return False
def get_int(prompt, lo=None, hi=None):
while True:
try:
val = int(inp(prompt))
if (lo is None or lo <= val) and (hi is None or val <= hi):
return val
except ValueError:
pass
def play_round(qas):
# pick some question/answer pairs at random
questions = random.sample(qas, NUM_ANSWERS)
# decide which question to use
correct = random.randrange(0, NUM_ANSWERS)
# show the question
print("\n{}?".format(questions[correct][0]))
# show the potential answers, numbered from 1
for i,a in enumerate(questions, 1):
print("{}: {}".format(i, a[1]))
# get the user's response
ans = get_int("Enter your answer (1-{}): ".format(NUM_ANSWERS), 1, NUM_ANSWERS)
# was it the right answer?
return (ans - 1 == correct)
def main():
qas = list(read_csv_file("teampositionnumberplayer.csv"))
win, lose = 0, 0
while True:
if play_round(qas):
print("\nYou got it!")
win += 1
else:
print("\nSo close... but NO!")
lose += 1
print("{} wins, {} losses".format(win, lose))
if not get_yn("Play again? (y/n) "):
break
if __name__=="__main__":
main()
我試圖把這個和... – user3349243
嗯... Python版本是您使用了錯誤?如果您不知道,請在您的shell中鍵入python -V。 –
我相信蟒蛇3 – user3349243