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
Related
print("Welcome to English, please enter your name,age,and password.")
print("If you have previously signed in, enter using the same name,age,and password")
name = input("Please enter your name: ")
age = input("Now please enter you age: ")
username = name[0:3] + age
password = input("Now please create a password: ")
userpass = (username+","+password)
check = open("logins.txt")
string = check.read().strip().split()
if userpass in string:
print("You have logged in as",username,"The questions will now start. \n")
else:
newlog = input("Looks like you dont have an account with those details, Would you like to create a new one? Y/N: ")
if newlog == "Y" or newlog == "y" or newlog == "yes" or newlog == "Yes":
f = open("logins.txt","a+")
chosen = f.write(username+","+password+"\n")
print("The username",username,"and password",password,"have now been saved, the questions will now start \n")
f.close()
else:
print("Please either sign in or log in and try again.")
welcome()
import random
f = open("English.txt","r")
points = 0
for line in f:
currentLine = line.split(",")
q = currentLine[0]
answer = currentLine[1]
questions = currentLine[1:-1]
random.shuffle(questions)
print(q)
for i in range(len(questions)):
print (i+1,":",questions[i])
userAnswer = int(input("Make a selection :"))
if answer == questions[userAnswer-1]:
points = (points+1)
print ("CORRECT, You have",points,"points")
str(points)
else:
print ("INCORRECT")
f.close()
f = open("scores.txt","a+")
score = f.write(username+","+password+","+points+"\n") #It is giving a type error about this line and I cant seem to understand why
f.close()
The error shown is:
line 193, in english
score = (username+","+password+","+points+"\n")
TypeError: must be str, not int
Please let me know if you have a better way of writing the scores into a text file. THank you.
Replace the error line with: score = f.write(username+","+password+","+str(points)+"\n")
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())
name_list = []
command_list = ["Add" ,"Help"]
def start():
input("Hello please type in a command : ")
start()
if (input == "help" or "Help"):
print("Here are the following commands for this program : ")
i = 0
for i in command_list :
print("'" + i + "'")
start()
if (input == "Add" or "add" ):
name = input("Insert name please : ")
print("Welcome " + name)
name_list.append(name)
So this code is causing me a bit of trouble , upon starting the code everything works fine it asks me to type in a command as it should , and if i type in 'help' it does exactly what its supposed to do, which is list all the commands, after that its supposed to reset via the start() command and once again ask me to input a command , however this time no matter what i write it activates this block of code:
if (input == "Add" or "add" ):
name = input("Insert name please : ")
print("Welcome " + name)
name_list.append(name)
Can someone please help me fix this and or explain why this is happening??
Thank you in advanced.
You have to use a while loop here, also repr(i) more efficient than "'" + i + "'":
name_list = []
command_list = ["Add" ,"Help"]
def start():
return input("Hello please type in a command : ")
a=start()
while a.lower()=='help':
print("Here are the following commands for this program : ")
i = 0
for i in command_list :
print(repr(i))
a=start()
if a.lower()=='add':
name = input("Insert name please : ")
print("Welcome " + name)
name_list.append(name)
else:
print('invalid input')
Example output:
Hello please type in a command : help
Here are the following commands for this program :
'Add'
'Help'
Hello please type in a command : Help
Here are the following commands for this program :
'Add'
'Help'
Hello please type in a command : Add
Insert name please : Bob
Welcome Bob
and also:
print(name_list)
Returns:
['Bob']
Your code has several issues. Here's a version that works.
name_list = []
command_list = ["Add", "Help"]
def start():
return input("Hello please type in a command : ")
name = ""
while not name:
command = start()
if (command.lower() == "add"):
name = input("Insert name please : ")
print("Welcome " + name)
name_list.append(name)
# printing help for everything except add
else:
print("Here are the following commands for this program : ")
i = 0
for i in command_list:
print(repr(i))
if (input == "help" or "Help"):
print("Here are the following commands for this program : ")
i = 0
for i in command_list :
print("'" + i + "'")
start() # <--- your call to start() function does not reset where the interpreter left off reading you code.
Python interpreter simply reads each one of your lines and does something with it. In your if statement, the line start() is called, it ask for an user input and returns None. Then this if statement is complete, then the next line read is as you described:
if (input == "Add" or "add" ):
name = input("Insert name please : ")
print("Welcome " + name)
name_list.append(name)
Solution to your question:
name_list = []
command_list = ["Add" ,"Help"]
def start():
input("Hello please type in a command : ")
while True:
start()
if (input == "help" or "Help"):
print("Here are the following commands for this program : ")
i = 0
for i in command_list :
repr(i)
if (input == "Add" or "add" ):
name = input("Insert name please : ")
print("Welcome " + name)
name_list.append(name)
if input == "something for break condition":
break
name_list = []
command_list = ["Add" ,"Help"]
def start():
inpt = input("Hello please type in a command : ")
if (inpt == "help" or inpt == "Help"):
print("Here are the following commands for this program : ")
print(command_list)
start()
elif (inpt == "Add" or inpt == "add" ):
name = input("Insert name please : ")
print("Welcome " + name)
name_list.append(name)
yn = input("Do you want to add another person? ")
if yn in ['y','Y','yes','Yes','YES']:
start()
else:
print ("Quitting!! all the people entered are")
print(name_list)
return (None)
else:
print("Please type 'help' for help")
start()
Very beginner programmer here in the process of learning. I am just wondering if this simple code I have typed is the most optimal way to do it.
with open('guest_book.txt', 'a') as file_object:
while True:
name=input("What is your name?")
print("Welcome " + name + ", have a nice day!")
file_object.write(name + " has visited! \n")
another = input("Do you need to add another name?(Y/N)")
if another == "y":
continue
elif another == "n":
break
else:
print("That was not a proper input!")
while True:
another = input("Do you need to add another name?(Y/N)")
if another == "y":
a = "t"
break
if another == "n":
a = "f"
break
if a == "t":
continue
else:
break
My questions is in the if statements. When I ask the input("Do you need to add another name?(y/n)", is what I have typed the best way to re-ask the question if I get an answer other than y or n. Basically I want the question to be repeated if I don't get either a yes or no answer, and the solution I found does not seem like the most optimal solution.
You are basically there. You can simply:
with open('guest_book.txt', 'a') as file_object:
while True:
name=input("What is your name?")
print("Welcome " + name + ", have a nice day!")
file_object.write(name + " has visited! \n")
another = input("Do you need to add another name?(Y/N)")
if another == "y":
continue
elif another == "n":
break
else:
print("That was not a proper input!")
continue
You can use function to write your all logic at one place.
def calculate(file_object):
name=raw_input("What is your name?")
print("Welcome " + name + ", have a nice day!")
file_object.write(name + " has visited! \n")
another = raw_input("Do you need to add another name?(Y/N)")
if another == "y":
calculate(file_object)
elif another == "n":
return
else:
print("That was not a proper input!")
calculate(file_object)
if __name__=='__main__':
with open('guest_book.txt', 'a') as file_object:
calculate(file_object)
You can do it this way, but there will not be any invalid input for saying no. It will only check for saying y
with open('guest_book.txt', 'a') as file_object:
another = 'y'
while another.lower() == 'y':
name=input("What is your name?")
print("Welcome " + name + ", have a nice day!")
another = input("Do you need to add another name?(Y/N)")
I have some code, which I will rather not share but this a portion
try_again = input ("Try again?")
if answer == "Y" or answer == "y":
clear()
file_path = os.path.dirname(os.path.realpath(__file__))
open file_path + "maze_game.exe"
exit()
else:
exit()
I want the file to open itself (to start at the beginning) I have tested it and it DOES work but, if the user renames the file (unlikely but possable) clearly this wont work unless they decompile, edit, and recompile. so I want to get the name of itself, store that in a variabe and open like this:
file_name = how ever I get the name
try_again = input ("Try again?")
if answer == "Y" or answer == "y":
clear()
file_path = os.path.dirname(os.path.realpath(__file__))
open file_path + file_name
exit()
else:
exit()
so how might I get the file name?
EDIT: here is my whole code:
import os
import time
clear = lambda: os.system('cls')
name = input ("What is your name? ")
friend = "Charels"
if name == "Charels" or name == "charels" or name == "Charles" or name == "charles":
friend = "Chuck"
print ("Welcome to the Maze Game Dr. " + name)
time.sleep(1.5)
clear()
print ("No one has made it out of Colwoods' labrynth,\nhowever there are rumours of untold riches at the end. \nThe most recent victim of the Maze is your best friend, " + friend)
time.sleep(1.5)
clear()
print ("Are you sure you want to continue?")
answer = input ("Y or N? ")
if answer == "Y" or answer == "y":
("")
else:
friend = friend + " for dead. R.I.P."
print ("Shame on you, you left " + friend)
time.sleep(1.5)
clear()
print ("YOU LOSE")
time.sleep(1.5)
clear()
file_name = how ever I get the name
try_again = input ("Try again?")
if answer == "Y" or answer == "y":
clear()
file_path = os.path.dirname(os.path.realpath(__file__))
open file_path + file_name
exit()
else:
exit()
input ("...")
no, the program is not completed and ignore the last line
Maybe I am misunderstanding what you want, but I think os.path.basename(__file__) will do the trick.
This will give you just the file part of your path, so if you have a filefoo/bar/baz.py and pass that path like os.path.basename('foo/bar/baz.py'), it will return the string 'baz.py'.
So try:
file_name = os.path.basename(__file__)
That being said, your approach seems a little atypical as #Blender points out, and I have never tried to have a program restart itself in this way. I am not sure if this answer will make your program work correctly, but it will give you the name of the file that is running your program, which seems to be what you are looking for.