使用变量数据写入文件

时间:2017-08-24 17:13:55

标签: python-3.x

import random #  imports the random module

user_class = "" # Global variable
question_counter = int(0) # sets counter
amount_correct = int(0) # sets score



possible_operators = ("+","-","x") # creates a list of operators

while user_class == "": # Indefinite iteration - Runs until a valid class is given
    user_class = str(input("Please enter your class"))

    if user_class == "Rainbow": # Testing variable class - Will not crash the program
        class_file = open("RainbowClass.txt","a")

    elif user_class == "Sun":
        class_file = open("SunClass.text","a")

    elif user_class == "Moon":
        class_file = open("MoonClass.text","a")

    else:
        print("Not quite. Try again:")
        user_class = ""



name = str(input("Please enter your name"))


while question_counter < 10: # Indeffinate iteration – number of questions

    num1 = random.randint(1,10) # random number generation
    num2 = random.randint(1,10)
    operator = random.choice(possible_operators) # Chooses one of the operators from the list

    if operator == "+":
        answer = num1 + num2
    elif operator == "-":
        answer = num1 - num2
    elif operator == "x":
        answer = num1 * num2

    print("What is the answer to ", num1," "+operator+"" ,num2,"?")
    user_answer = int(input())


    if user_answer == answer:
        question_counter = question_counter + 1
        amount_correct = amount_correct + 1
        print("Correct!")

    else:
        print("Incorrect")
        question_counter = question_counter + 1


final_score = amount_correct
print("Well Done! You scored",amount_correct,"out of",question_counter,".")


amount_correct = str(amount_correct)
class_file.write(user_class)
class_file.write(name)
class_file.write(amount_correct + "\n")

class_file.close

这是我的代码。它在运行时没有出现任何错误,但我试图获取用户的类并根据输入打开文本文件。该文件正在打开,但是当它到达底部时,它不会从我想要的变量内部的测验中写入数据。

这是什么解决方案?

1 个答案:

答案 0 :(得分:0)

未经测试的破解(抱歉,Python在另一个系统上)。我把它分成几块:

import random 

# Got rid of your global 'user_class'
# Moved the counter(s) to local function variables    
# Moved the operator options to local function variables

现在要处理你的第一个while,我会这样做:

def get_class_file():
    while True:
        # Don't need to call str(); input() returns a 'str'
        user_class = input("Please enter your class: ")

        if user_class == "Rainbow":
            class_file = "RainbowClass.txt"
            break
        elif user_class == "Sun":
            class_file = "SunClass.txt"
            break
        elif user_class == "Moon":
            class_file = "MoonClass.txt"
            break
        else:
            print("Not quite. Try again...")

    return class_file

保持这个:

# Don't need to call str(); input() returns a 'str'
name = input("Please enter your name: ")

现在为第二个while,一个类似的功能:

def get_score():
    # Don't need to call int()
    question_counter = 0  
    amount_correct = 0
    # Make this a tuple sequence; they are immutable
    possible_operators = ("+","-","x",)

    while True:
        if question_counter < 10:
            num1 = random.randint(1,10) # random number generation
            num2 = random.randint(1,10) 
            operator = random.choice(possible_operators)

            if operator == "+":
                answer = num1 + num2
            elif operator == "-":
                answer = num1 - num2
            elif operator == "x":
                answer = num1 * num2

            user_answer = int(input("What is the answer to: " 
                                    + str(num1) + operator + str(num2) + "?\n"))

            # Take out of the if/else since we always increment
            question_counter += 1

            if user_answer == answer:
                amount_correct += 1
                print("Correct!")
            else:
                print("Incorrect!")

        else:
            break

    return amount_correct

让我们把它们放在一起,看看我们如何获取变量,然后如何将它们写入您的文件:

import random 

def get_class_file():
    while True:
        # Don't need to call str(); input() returns a 'str'
        user_class = input("Please enter your class: ")

        if user_class == "Rainbow":
            class_file = "RainbowClass.txt"
            break
        elif user_class == "Sun":
            class_file = "SunClass.txt"
            break
        elif user_class == "Moon":
            class_file = "MoonClass.txt"
            break
        else:
            print("Not quite. Try again...")

    return class_file, user_class


def get_score():
    # Don't need to call int()
    question_counter = 0  
    amount_correct = 0
    # Make this a tuple sequence; they are immutable
    possible_operators = ("+","-","x",)

    while True:
        if question_counter < 10:
            num1 = random.randint(1,10) # random number generation
            num2 = random.randint(1,10) 
            operator = random.choice(possible_operators)

            if operator == "+":
                answer = num1 + num2
            elif operator == "-":
                answer = num1 - num2
            elif operator == "x":
                answer = num1 * num2

            user_answer = int(input("What is the answer to: " 
                                    + str(num1) + operator + str(num2) + "?\n"))

            # Take out of the if/else since we always increment
            question_counter += 1

            if user_answer == answer:
                amount_correct += 1
                print("Correct!")
            else:
                print("Incorrect!")

        else:
            break

    return amount_correct, question_counter

class_file, user_class = get_class_file()
name = input("Please enter your name: ")
final_score, num_asked = get_score()  


print("Well Done!\n" 
      "You scored " + str(final_score) + " out of " + str(num_asked) + ".")

# In all methods you called 'a' mode so set that here
# Using 'with open()' automatically closes the file after completion
with open(class_file, 'a') as f:
    f.write(user_class + "\n")
    f.write(name + "\n")
    f.write(str(final_score) + "\n")

让我知道是否有任何问题,错误等。再一次,无法测试。