Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
223 views
in Technique[技术] by (71.8m points)

Appending variable to text file not working in Python

I am trying to get my program to output two variables to a text file after it finishes running something but all I get is the folder and no text files inside of it. Here is the code in question:

I have edited to include the entire program.

import random #needed for the random question creation
import os #needed for when the scores will be appended to a text file
#import csv #work in progress
answer = 0 #just to ensure a strage error isn't created by the input validation (since converting to a global variable isn't really needed)
global questionnumber #sets the question number to be a global variable so that 
questionnumber = 0
global score
score = 0
global name
name = "a"
def check_input(user_input): #used to verify that input by user is a valid number
    try: #the condition that does the checking
        answer = int (user_input)
    except ValueError: #what to do if the number isn't actually a number
        return fail() #calls the failure message
    return answer #sends the answer back to the rest of the program
def fail(): #the failure message procedure defined
   print("That isn't a whole number! Try again with a different question") #tells the user what's going on
   global questionnumber #calls the global variable for this procedure
   questionnumber = questionnumber - 1 #allows the user, who made a mistake, a second chance to get it right
def questions(): #the question procedure defined
    global name
    name=input("Enter your name: ") #gets the user's name for logging and also outputting messages to them
    print("Hello there",name,"! Please answer 10 random maths questions for this test!") #outputs welcome message to the user
    ClassOfStudent=input("Which class are you in?") #gets the user's class for logging
    finish = False
    while finish == False: #only occurs if "finish" isn't set to true so that the questions asked don't exceed ten
        global questionnumber #calls the global variable
        global score
        choice = random.choice("+-x") #uses the random function to choose the operator
        if questionnumber < 10 | questionnumber >= 0: #validation to ensure the question number is within ten
            number1 = random.randrange(1,12) #uses random numbers from the random function, above 1 and below 12
            number2 = random.randrange(1,12) #same as the abovem for the second number
            print((number1),(choice),(number2)) #outputs the sum for the student to answer
            answer=check_input((input("What is the answer?"))) #asks for the student's answer
            questionnumber = questionnumber + 1 #adds one to the numebvr of questions asked

            if choice==("+"): #if the ramdomly generated operator was plus
                correctanswer = number1+number2 #operator is used with the numbers to work out the right answer
                if answer==correctanswer: #checks the studen't answer is right
                    print("That's the correct answer") #if it is, it tells the student
                    score = score + 1 #adds one to the score that the user has
                else:
                    print("Wrong answer, the answer was",correctanswer,"!") #if the answer is wrong, it tells the student and doesn't add one to the score

            if choice==("x"): #essentially the same as the addition, but with a multiplicatin operator instead
                correctanswer = number1*number2
                if answer==correctanswer:
                    print("That's the correct answer")
                    score = score + 1
                else:
                    print("Wrong answer, the answer was",correctanswer,"!")

            elif choice==("-"): #essentially the same as the addition, but with a subtraction operator instead
                correctanswer = number1-number2

                if answer==correctanswer:
                    print("That's the correct answer")
                    score = score + 1
                else:
                    print("Wrong answer, the answer was",correctanswer,"!")
        else: #if the number of questions asked is ten, it goes on to end the program
            finish = True
    else:
            print("Good job",name,"! You have finished the quiz") #outputs a message to the user to tell them that they've finished the quiz
            print("You scored " + str(score) + "/10 questions.") #ouputs the user's score to let them know how well they've done
            #all below here is a work in progress
            #Create a new directory for the scores to go in, if it is not there already.
            if os.path.exists("Scores") == False:
              os.mkdir("Scores")
            os.chdir("Scores")
            if ClassOfStudent==1: #write scores to class 1 text
                file_var = open("Class 1.txt",'w+')
                file_var.write("name, score")
                file_var.close()
            if ClassOfStudent==2: #write score to class 2 text
                file_var = open("Class 2.txt",'w+')
                file_var.write(name, score)
                file_var.close()
            if ClassOfStudent==3: #write score to class 3 text
                file_var = open("Class 3.txt",'w+')
                file_var.write(name, score)
                file_var.close()
questions()
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

ClassOfStudent is a string rather than a number, so none of the code that writes to the file will get executed. You can easily verify that by adding a print statement under each if so you can see if that code is being executed.

The solution is to compare to strings, or convert ClassOfStudent to an i teger.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...