我的代码不会将输入保存到fi

2024-04-24 00:54:08 发布

您现在位置:Python中文网/ 问答频道 /正文

我的代码无法保存文件

#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

Tags: answernameinputyourifcountrandominfile
1条回答
网友
1楼 · 发布于 2024-04-24 00:54:08

如果你想让你的代码工作,首先删除或注释掉第26行的“在这里输入代码”部分。可以用“#”完成。原因是“”是一个字符串,将被解释为不应该出现的字符串。你知道吗

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

第二,它不会被保存,因为while从不运行,因为while score==10不是真的,所以写入分数的循环从不运行。你知道吗

你可以把它改成:

while score <= 10 and score >= 0:

我测试了我所做的两个调整,你的代码将运行并创建这个类?。txt文件

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

相关问题 更多 >