【问题标题】:my code won't save inputs to a file我的代码不会将输入保存到文件中
【发布时间】:2015-04-15 12:32:10
【问题描述】:

我的代码不会保存文件

#ask for name
name=input("what is your name?")
print("start your quiz " + name + "!")
user=input
class123=('1','2','3')
class123=input("what class are you in 1,2 or 3") 
#get random number
import random
#ask number of questions you want
score=0
count=10
#start while loop
while count != 0:
   num1=random.randint(1,8)
   num2=random.randint(1,8)
   symbol=random.choice(['*','+','-'])
   if symbol=="*":
      user=int(input(str(num1) + "*" + str(num2)))
      count=count-1
      answer=num1 * num2
      if user==answer:
         print("well done your score goes up by 1")
         score=score+1
      else:
         print("this is wrong next question")
   elif symbol=="+":
      user=int(input(str(num1) + "+" + str(num2)))`enter code here`
      count=count-1
      answer=num1 + num2
      if user==answer:
         print("well done your score goes up by 1")
         score=score+1
      else:
         print("this is wrong next question")
   elif symbol=="-":
      user=int(input(str(num1) + "-" + str(num2)))
      count=count-1
      answer=num1 - num2
      if user==answer:
         print("well done your score goes up by 1")
         score=score+1
      else:
         print("this is wrong next question")
#get final score
print(" your score was " + str(score) + " well done ")
#save data into 3 classes

while score == 10 and score >= 0:
    if class123 == '1':
      inFile = open("Class1.txt", 'a')
      inFile.write("\n" + name + ":" + str(score))
      inFile.close()
      score = -1
    elif class123 == '2':
      inFile = open("Class2.txt", 'a')
      inFile.write("\n" + name + ":" + str(score))
      inFile.close()
      score = -1
    elif class123 == '3':
      inFile = open("Class3.txt", 'a')
      inFile.write("\n" + name + ":" + str(score))
      inFile.close()
      score = -1

【问题讨论】:

  • 听起来很糟糕,有没有调试过?
  • 如果这是你的 GCSE 课程,你就远远落后了 - 其他所有作弊的人都是几周前在这里的。
  • 提示:想想while score == 10 and score >= 0: 的含义。
  • 没有底位和 jonrsharpe 这很讨厌,我正在改进它,因为我是一个独立的学习者

标签: python saving-data


【解决方案1】:

如果您希望您的代码正常工作,请首先删除或注释掉第 26 行的“在此处输入代码”部分。可以使用“#”来完成。原因是''是一个字符串,在不应该出现的地方会被解释为字符串。

user=int(input(str(num1) + "+" + str(num2))) #enter code here

第二,它没有被保存,因为 while 永远不会运行,因为 while score == 10 不是真的,所以你写分数的循环永远不会运行。

您可以将其更改为:

while score <= 10 and score >= 0:

我测试了我所做的 2 项调整,您的代码将运行并创建 Class?.txt 文件

但正如其他人所提到的,它的结构并不完全正确。东西的用法不太正确。所以你可能想改进你的代码,但是如果你不介意的话,我在这里只是给你一些修复如何让它真正运行。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-04-23
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-02-19
    相关资源
    最近更新 更多