Cannot load or save txt. file - python

I wrote a code but apparently It does not save and load to my txt. file. I would greatly appreciate if you took a look into my code and told me what's wrong because I am having really hard time figuring it out myself. I didnt use pickle, as It was creating encoding related difficulties so I tried to find the other way around it and all which saves into my txt. file is "None". Thank you in advance.
def savedata(x):
play_again = input("Are you willing to save existing progress? Y/N")
if (play_again == "Y") or (play_again == "y"):
print("Saving progress...")
file = open('adam_malysz.txt', 'w')
file.write(str(x))
file.close()
print("Your file has been called - adam_malysz.txt")
print("Progress has been successfully saved.")
else:
print("Returning to main menu")
def arrayfancy():
num1 = int(input("Select size of an array: "))
value = []
for i in range(num1):
value.append(random.randint(1, 99))
print("Printing data...")
print(value)
print("Sorting Array...")
bubblesort(value)
print(value)
print("Average value is: ")
print(statistics.mean(value))
print("Minimum value is: ")
print(min(value))
print("Maximum value is: ")
print(max(value))
print("Your data has been successfully printed")
if choice == 1:
savedata(arrayfancy())

Your arrayfancy() has no return statement, so it returns None when it reach the end of the function block. savedata(x) then successfully write "None" to your file.
You can add return value at the end of arrayfancy(), this will solve your issue.
I tested the code bellow and I get the text file containing the array.
def savedata(x):
play_again = input("Are you willing to save existing progress? Y/N")
if (play_again == "Y") or (play_again == "y"):
print("Saving progress...")
file = open('adam_malysz.txt', 'w')
file.write(str(x))
file.close()
print("Your file has been called - adam_malysz.txt")
print("Progress has been successfully saved.")
else:
print("Returning to main menu")
def arrayfancy():
num1 = int(input("Select size of an array: "))
value = []
for i in range(num1):
value.append(random.randint(1, 99))
print("Printing data...")
print(value)
print("Sorting Array...")
bubblesort(value)
print(value)
print("Average value is: ")
print(statistics.mean(value))
print("Minimum value is: ")
print(min(value))
print("Maximum value is: ")
print(max(value))
print("Your data has been successfully printed")
return value
if choice == 1:
savedata(arrayfancy())

Related

How to have python recognize correct value in my code? Dictionaries

for i in range(n):
while len(dictionary)>0:
choice = random.choice(list(dictionary.keys()))
correctAnswer = dictionary[choice]
print("English: ",choice)
guess = input("Spanish: ")
dictionary.pop(choice)
if guess == correctAnswer:
print("\nCorrect!\n")
else:
print("Incorrect\n")
wrongAnswers.append(choice)
break
print("\nYou missed", len(wrongAnswers), "words\n")
Hi, I am trying to create a vocabulary test on python. My code works up until this chunk. After the program prompts the user for their guess, the program will say it is incorrect even if it is the right answer. Is there an error in this code? How can I get around this?
This is what it looks like:
English: white
Spanish: blanco
Incorrect
English: purple
Spanish: morado
Incorrect
Thanks!
Full Code:
def main():
import random
wrongAnswers = []
print("Hello, Welcome to the Spanish-English vocabulary test.")
print(" ")
print("\nAfter the test, this program will create a file of the incorrect answers for you to view")
print("\nTo start, please select from the following options: \nverbs.txt \nadjectives.txt \ncolors.txt \nschool.txt \nplaces.txt") #sk
while True: #SK
selection = input("Insert your selection: ").lower() #user inputs selection #sk
if selection == "verbs.txt" or selection == "adjectives.txt" or selection == 'colors.txt' or selection == 'school.txt' or selection == 'places.txt':
print("You have chosen", selection, "to be tested on.")
break
if False:
print("try again.")
selection = input("Insert your selection: ").lower()
break
file = open(selection, 'r')
dictionary = {}
with file as f:
for line in f:
items = line.rstrip("\n").split(",")
key, values = items[0], items[1:]
dictionary[key] = values
length = len(dictionary)
print(length,'entries found')
n= int(input("How many words would you like to be tested on: "))
while n > length:
print("Invalid. There are only" ,length, "entries")
n= int(input("How many words would you like to be tested on: "))
print("You have chosen to be tested on",n, "words.\n")
for i in range(n):
while len(dictionary)>0:
choice = random.choice(list(dictionary.keys()))
correctAnswer = dictionary[choice]
print("English: ",choice)
guess = input("Spanish: ")
dictionary.pop(choice)
if guess == correctAnswer:
print("\nCorrect!\n")
else:
print("Incorrect\n")
wrongAnswers.append(choice)
break
print("\nYou missed", len(wrongAnswers), "words\n")
if len(wrongAnswers) > 0:
wrong = str(wrongAnswers)
output = input("Please name the file you would like you wrong answers to be saved in: ")
outf = open(output, 'w')
outf.write(wrong)
outf.close()
else:
print("You got all of the problems correct!")
main()

writing a text file on python

import time
def mainmenu ():
print ("1.set values")
print ("2. run formula")
print ("3. export formula results")
maininput = int(input("Enter: "))
if maininput == 1:
set_values ()
elif maininput == 2:
formula ()
elif maininput == 3:
export ()
def set_values ():
set_values.first = int(input("Value 1 between 1 and 10"))
while 1< set_values.first <10:
set_values.second = int(input("Value 2 between 1 and 10"))
while 1< set_values.second <10:
mainmenu ()
else:
print ("That is not a valid value")
return set_values ()
def formula ():
part_1 = set_values.first + set_values.second
print ("Value 1 + value 2 =",part_1)
time.sleep(2)
part_2 = part_1 * 5
print ("Value 1 + value 2 x 5 =",part_2)
time.sleep(2)
def export ():
print ()
mainmenu ()
What code would I use in def export to replace print () so the data printed in formula is written to a text file.
Before the data is written the user should be asked to enter a file name and the code should check if a file with the same name exists and if so ask the user if it should be overwritten. If the user chooses not to overwrite the file they should be returned to the part where they enter the file name.
You should consult the documentation for open and write (link here). Outside of that, the preferred method for writing to a file is the following:
with open('myfile.txt', 'w') as f:
f.write('Writing to files is easy')
This is how to print to a txt file:
file = open("Exported.txt", "w")
file.write("Text to write to file")
file.close()
Another way to do so would to be:
with open('Exported.txt', 'w') as file:
file.write("Text to write to file")
This is a program I made to write a txt file:
import os.path
def start():
print("What do you want to do?")
print(" Type a to write a file")
print(" Type b to read a file")
choice = input(" -")
if choice == "a":
create()
elif choice == "b":
read()
else:
print("Incorrect spelling of a or b\n\n")
start()
def create():
print()
filename = input("What do you want the file to be called?\n")
if os.path.isfile(filename):
print("This file already exists")
print("Are you sure you would like to overwrite?")
overwrite = input("y or n")
if overwrite == "y":
print("File has been overwritten")
write(filename)
else:
print("I will restart the program for you")
elif not os.path.isfile(filename):
print("The file has not yet been created")
write(filename)
else:
print("Error")
def write(filename):
print()
print("What would you like the word to end writing to be?")
keyword = input()
print("What would you like in your file?")
text = ""
filename = open(filename, 'w')
while text != keyword:
filename.write(text)
filename.write("\n")
text = input()
def read():
print()
print("You are now in the reading area")
filename = input("Please enter your file name: -")
if os.path.isfile(filename):
filename = open(filename, 'r')
print(filename.read())
elif not os.path.isfile(filename):
print("The file does not exist\n\n")
start()
else:
print("Error")
start()

adding a new contact information in txt file

I have this long python code and I'm having trouble finishing or fixing it and I need help.
First I have these codes -
This will just display the menus and i have created several def functions. One is for creating data and saving to the txt file, and the other is to use a hash function to split the name. Contact info as data is created in the txt file. Finally, in a while loop I have to somehow call up the menu codes and this is where I get stuck, or I may need to fix the whole thing. Also when I put a phone number in like 555-5555, it makes an error. How would I input a number like this value?
def menu():
print("Contact List Menu:\n")
print("1. Add a Contact")
print("2. Display Contacts")
print("3. Exit\n")
menu()
choice = int(input("What would you like to do?: "))
def data():
foo = open("foo.txt", "a+")
name = input("enter name: ")
number = int(input("enter the number: "))
foo.write(name + " " + str(number))
foo.close()
def contact():
data = open("foo.txt")
file = {}
for person in data:
(Id, number) = person.split()
file[number] = Id
data.close()
while choice !=3:
if choice == 1:
print(data())
if choice ==2:
print(data())
menu()
choice = int(input("What would you like to do?: "))
It seems that the program never stops and I have to use option 3 from the menu to exit the program.
Phone number like 555-5555 is not valid integer number so keep it as a text.
Inside menu() you call menu() which call menu(), etc. It is recursion. When you choose 3 you leave last menu() and return to previous menu().
EDIT:
btw: you have to add "\n" in write
def menu():
print("Contact List Menu:\n")
print("1. Add a Contact")
print("2. Display Contacts")
print("3. Exit\n")
def data():
foo = open("foo.txt", "a+")
name = input("enter name: ")
number = int(input("enter the number: "))
foo.write(name + " " + str(number) + "\n") # new line
foo.close()
def contact():
data = open("foo.txt")
for person in data:
name, number = person.split()
print(name, number)
data.close()
#----------------
menu()
choice = int(input("What would you like to do?: "))
while choice !=3:
if choice == 1:
data()
if choice == 2:
contact()
menu()
choice = int(input("What would you like to do?: "))

Python write to file maths generator

hello i have my code for a random maths quiz and i want it to save the name and there score next to the file and i want it to keep the data and not write over it every time could someone please help me and add this in i would like it so it could reocrd it like this let say i played it i would like the file to be like this then if someone else took the quiz it just adds there name to the list not erase the list first
name score
def quiz():
import random
import time
name=input("What is your name?")
print ("Alright",name,"Welcome to your maths quiz")
score=0
question=0
for question in range (1,11):
ops=['*','+','-']
rand=random.randint(1,10)
rand2=random.randint(1,10)
operation=random.choice(ops)
maths = eval(str(rand) + operation + str(rand2))
print ("Question",question)
time.sleep(0.5)
print (rand,operation,rand2)
question=question+1
d=int(input ("What is your answer:"))
if d==maths:
print ("Correct")
score=score+1
else:
print ("Incorrect. The actual answer is",maths)
if score >=7:
print ("Well done you got",score,"out of 10")
else:
print ("Unlucky you got",score,"out of 10")
percentage=score/10*100
print ("You got",percentage,"%")
f = open('results.txt','w')
f.write('%d' % score)
f.close()
playagain = 'yes'
while playagain == 'yes':
quiz()
print('Do you want to play again? (yes or no)')
playagain = input()
Change
f = open('results.txt','w')
to
f = open('results.txt','a')
Read the python docs for File I/O. 'w' overwrites an existing file
if you want the name with the score
f.write('{} : {}\n'.format(name, score) )

"UnboundLocalError: local variable 'input' referenced before assignment"

I have this code:
def delete():
print("Welcome to the password delete system.")
file = open("pypyth.txt", "w")
output = []
linechoice = input("What password do you want to delete?:\n")
if linechoice == "email":
for line in file:
if "Hotmail" != line.strip():
output.append(line)
print("Password " + linechoice + " deleted.")
y_n = input = ("Do you want to save these changes?\ny/n\n")
if y_n == "y":
file.close()
print("Change saved.")
input("Press enter to go back to menu")
main()
else:
main()
elif linechoice == "skype":
for line in file:
if "Skype" != line.strip():
output.append(line)
print("Password " + linechoice + " deleted.")
y_n = input = ("Do you want to save these changes?\ny/n\n")
if y_n == "y":
file.close()
print("Change saved.")
input("Press enter to go back to menu")
main()
else:
main()
else:
Why do I get an error like so?
linechoice = input("What password do you want to delete?:\n")
UnboundLocalError: local variable 'input' referenced before assignment
You are assigning a string to the variable input in
y_n = input = ("Do you want to save these changes?\ny/n\n")
input now has the value of 'Do you want to save these changes?\ny/n\n'
However, you are also calling the built-in function input in
linechoice = input("What password do you want to delete?:\n")
Consider changing the name of your variable to avoid these conflicts.
Looking at the context of the program, you are probably expecting
y_n = input("Do you want to save these changes?\ny/n\n")
instead of
y_n = input = ("Do you want to save these changes?\ny/n\n")
If you got this error, due to calling input():
UnboundLocalError: local variable 'input' referenced before assignment
than you should check whether your runtime python interpreter is 3.x, if you were assuming it is 2.x.
This Error happened to me while executing on python 3.6:
if hasattr(__builtins__, 'raw_input'):
input = raw_input
input()
So I got rid of this, and instead used:
from builtins import input

Categories

Resources