当前位置: 代码迷 >> python >> Python:另存为字符串时,保存数字错误
  详细解决方案

Python:另存为字符串时,保存数字错误

热度:110   发布时间:2023-06-13 13:40:14.0

我的代码有问题,在这里:

correct = 0

grade_book = {}
File = open('Test.txt', 'r')
for line in File:
     name, scores = line.split(':')
     grade_book[name] = scores.strip()
File.close()
print(grade_book)

name = input("Name: ")
if name in grade_book.keys():
    grade_book[name] += ',' + correct
else:
    grade_book[name] = correct

File = open('Test.txt', 'w')
for name, scores in grade_book.items():
    out_line = str(name) + ':' + str(scores) + "\n"
    File.write(out_line)

File.close()

问题是它给出了错误说明:

TypeError:无法将“ int”对象隐式转换为str

当程序尝试将“正确”保存为文件中的现有名称时,就会在程序中发生这种情况。 我尝试使用以下方法解决此问题:

    name = input("Name: ")
if name in grade_book.keys():
    grade_book[name] += ',' + str(correct)
else:
    grade_book[name] = correct

但是,这样做的问题是,尽管将“正确”分配给大于0的数字(例如8),但打印到文件的数字始终为0。另一方面,它确实会像以前一样给出错误,只是上面的问题。

有什么解决办法吗?

是的,我可能在这里错过了一些明显的东西。

“正确”的代码:

def mainLoop():
    global count
    global correct
    Num1 = randint(1, 10)
    Num2 = randint(1,10)
    Operand= randint(1,3)

    if Operand == 1:
        question = str(Num1) + " + " + str(Num2) + " = "
        answer = Num1 + Num2
    elif Operand == 2:
        question = str(Num1) + " - " + str(Num2) +" = "
        answer = Num1 - Num2
    else:
        question = str(Num1) + " x " + str(Num2) + " = "
        answer = Num1 * Num2

    userAnswer = int(input(question))
    if userAnswer == answer:
        correct += 1

猜猜我将发布整个代码以供参考:

from random import randint
import time
count = 0
correct = 0

def mainLoop():
   global count
   global correct
   Num1 = randint(1, 10)
   Num2 = randint(1,10)
   Operand= randint(1,3)

   if Operand == 1:
       question = str(Num1) + " + " + str(Num2) + " = "
        answer = Num1 + Num2
   elif Operand == 2:
       question = str(Num1) + " - " + str(Num2) +" = "
       answer = Num1 - Num2
   else:
       question = str(Num1) + " x " + str(Num2) + " = "
       answer = Num1 * Num2

 userAnswer = int(input(question))
 if userAnswer == answer:
  correct += 1



grade_book = {}
File = open('Test.txt', 'r')
for line in File:
    name, scores = line.split(':')
   grade_book[name] = scores.strip()
File.close()
print(grade_book)

name = input("Name: ")
if name in grade_book.keys():
   grade_book[name] += ',' + str(correct)
else:
   grade_book[name] = str(correct)

File = open('Test.txt', 'w')
for name, scores in grade_book.items():
    out_line = str(name) + ':' + str(scores) + "\n"
    File.write(out_line)

File.close()

 while count < 10:
    mainLoop()
    count += 1

快了吗,可能是错的

文本文件示例: Test:1,5 John:1,0

将分数写入文件后,您正在运行mainLoop ,因此该文件将不包含正确的分数。 只需将询问问题的代码移动10遍( while count < 10等等)到将分数写到grade_book的代码grade_bookif name in grade_book.keys():等等)。

您可能会发现避免使用全局变量会有所帮助。 取而代之的是,您可以具有一个根据用户是否正确响应而返回TrueFalse的问题函数,然后我们仅使用sum来计算正确和错误的响应。

from random import randint
import time

def question():
   a = randint(1, 10)
   b = randint(1,10)
   operand= randint(1,3)

   if operand == 1:
       sign = '+'
       answer = a + b
   elif operand == 2:
       sign = '-'
       answer = a - b
   else:
       sign = 'x'
       answer = a * b

   user_answer = int(input('{} {} {} = '.format(a, sign, b)))
   return user_answer == answer # returns True if correct, False if not

grade_book = {}
with open('Test.txt', 'r') as file:
    for line in file:
        name, scores = line.split(':')
        grade_book[name] = scores.strip()
print(grade_book)

name = input("Name: ")

# Ask a question 10 times and sum up the correct responses
# (This works because sum counts True as 1 and False as 0)
correct = sum(question() for _ in range(10)) 

if name in grade_book.keys():
   grade_book[name] += ',' + str(correct)
else:
   grade_book[name] = str(correct)

with open('Test.txt', 'w') as file:
    for name, scores in grade_book.items():
        file.write('{}:{}\n'.format(name, scores))

grade_book[name] = correct您可以分配整数值correct 因此应该是:

name = input("Name: ")
if name in grade_book.keys():
    grade_book[name] += ',' + str(correct)
else:
    grade_book[name] = str(correct)

而且您对“正确”不做任何事情。 总是0。