Function is not being called inside another function:
ch = False
while not ch:
print("""
1. Make a User
2. Login in and Play
3. Quit
""")
a = input("What would you like to do: ")
if a == '1':
un_maker()
elif a == '2':
player1Login()
elif a == '3':
input('\nEnter to exit...\n')
quit()
Where when a is 2, it should move on to player1Login(), it does but it does not go to the next function inside the player1Login().
The code for player1Login() and the function it's supposed to run:
def player1Login():
""" Login for player 1 """
user1 = input("Please enter your usernames[Caps sensitive]: ") # Asking the
user to input there username
pass1 = input("Please also enter your password[Caps sensitive]: ") # Asking the user to input there password
verfi1(user1, pass1)
def verfi1(user1, pass1):
""" Verfications of the user """
with open("data.csv", "r") as f:
reader = csv.reader(f) # makes 'reader' the csv reader of file 'f'
for row in reader: # Looking at rows/records inside the file
if user1 in row: # Looks for username inside the row
if pass1 in row[1]:
print("Player 1 Confirmed")
player2Login()
elif pass1 != row[1] or reader == '':
print("""You have entered the wrong Username/Password for Player 1
This could be due to:
1. Inputed the wrong username/password
2. Inputed the wrong case in username/password
3. Inputed username/password that does not exit
""")
break
else:
#print("Reader")
next(reader)
Basically, the code should output when a is 2, player1Login() then move onto verfi1() function however it does not, it just goes back to the menu.
Answer Found:
def menu():
ch = False
optin = 0
while not ch :
print("""
1. Make a User
2. Login in and Play
3. Quit
""")
optin = input("What would you like to do: ")
if optin == '1':
un_maker()
elif optin == '2':
player1Login()
elif optin == '3':
input('\nEnter to exit...\n')
quit()
def player1Login():
""" Login for player 1 """
user1 = input("Please enter your usernames[Caps sensitive]: ")
pass1 = input("Please also enter your password[Caps sensitive]: ")
boop(user1, pass1)
def boop(user1, pass1):
with open('data.csv', 'r') as f:
reader = csv.reader(f)
for row in reader:
if pass1 in row[1] and user1 in row[0]:
print("Username and Password found, Player 1 Confirmed")
player2Login(user1)
elif pass1 not in row[1] and user1 not in row[0] and row[0] == '' :
print("Player Not found / Password incorrect")
menu()
You skip lines with next and therefore jump over each other user in you data.csv file. This can lead to that if user1 in row is never true even though user1 is in your file but happens to be on a skipped line.
Your code:
for row in reader: # Looking at rows/records inside the file
if user1 in row: # Looks for username inside the row
if pass1 in row[1]:
print("Player 1 Confirmed")
player2Login()
elif pass1 != row[1] or reader == '':
print("""You have entered the wrong Username/Password for Player 1
This could be due to:
1. Inputed the wrong username/password
2. Inputed the wrong case in username/password
3. Inputed username/password that does not exit
""")
break
else:
next(reader) # this skips the next
Remove the elseclause because for row in reader already goes over all lines.
Related
The phonebook cannot store more than one person with the same last name. For example if i have an entry with the last name x and i try to create a new entry with a last name x,it will replace the previous x with the info of the last x input. This is the code.blablablablablabla(i cant say more but it doesnt let me post)
# Used to store the entries in the telephone book
entries = []
new_entries = {}
# Create flag to decide when the program ix exited
exit_program = False
while exit_program == False:
print( "Welcome to the EG-244 Telephone Book" )
print( "------------------------------------\n" )
print( "Please select from one of the following options:" )
print( "\t1. Add a new entry" )
print( "\t2. List entries" )
print( "\t3. Search for an entry" )
print( "\t4. Delete an entry" )
print( "\t5. Add a personal note" )
print( "\t6. Remove a personal note" )
print( "\t7. Quit" )
menu_input = input()
menu_num = int(menu_input)
if menu_num == 1:
print("\nCan i have your Last name, First name,Age and phone number please")
last_name=input("Last name:")
name=input("Name:")
age=input("Age:")
phone=input("Phone number:")
new_entries[last_name] = {'Last Name':last_name, 'First Name':name, 'Age':age, 'Telephone':phone,'Personal Notes':{'1.':'', '2.':''}}
entries.append(new_entries.copy())
entries=sorted(new_entries.keys(), key=lambda x:x.lower())
continue
elif menu_num == 2:
if len(new_entries) == 0:
print("No entries have been submitted yet")
continue
else:
for i in entries:
values=new_entries[i]
print("Last Name:" + i)
print("First Name:"+values['First Name'])
print("Age:"+values['Age'])
print("Phone Number:"+values['Telephone'])
print('Personal Note 1.:'+values['Personal Notes']['1.'])
print('Personal Note 2.:'+values['Personal Notes']['2.'])
print("~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~")
print("Currently there are" + str(len(entries)) + "entries")
continue
elif menu_num == 3:
print("\nInsert the last name:")
last_name=input()
if last_name in new_entries:
print (last_name, new_entries[last_name])
continue
else:
print("\nThe person is not in the phone book")
continue
elif menu_num == 4:
print("\nInsert the Last name of the entry to be deleted:")
last_name=input()
if last_name in new_entries:
del new_entries[last_name]
print("Entry has been deleted")
continue
else:
print("The entry does not exist")
continue
elif menu_num ==5:
print("Can I have your last and first name please:")
last_name=input("Last name:")
name=input("First name:")
note=input("Personal Note:")
note_1=input("Another personal Note:")
name in [x for v in new_entries.values() for x in v]
if last_name in new_entries:
new_entries[last_name]['Personal Notes']['1.']=note
new_entries[last_name]['Personal Notes']['2.']=note_1
print (last_name, new_entries[last_name])
continue
else:
print("This entry does not exist")
continue
if menu_num == 6:
print("Can I have your last and first name please:")
last_name=input("Last name:")
name=input("First name:")
delete=input("Delete note 1 or 2?")
delete=int(delete)
name in [x for v in new_entries.values() for x in v]
if last_name in new_entries:
for notes in new_entries.values():
if delete == 1:
new_entries[last_name]['Personal Notes']['1.']=''
print("1st Note deleted")
elif delete == 2:
new_entries[last_name]['Personal Notes']['2.']=''
print("2nd Note deleted")
continue
else:
print("This entry does not exist")
elif menu_num == 7:
exit_program = True
else:
print( "Error: You entered an invalid choice. Please try again." )
print( "Thank you for using the EG-244 Telephone Book" )
I think that
new_entries[last_name] = {'Last Name':last_name, 'First Name':name, 'Age':age, 'Telephone':phone,'Personal Notes':{'1.':'', '2.':''}}
should be a list containing a dictionary rather than just a dictionary.
new_entries[last_name] = [{'Last Name':last_name, 'First Name':name, 'Age':age, 'Telephone':phone,'Personal Notes':{'1.':'', '2.':''}}]
That way you could append another item to that list stored under the same last_name key.
You'll then have to update the rest of your code to handle this new data structure.
In my program, I have asked the user for certain details (ie date of birth). Details have already been written to the file "Reg and Login" after the user has registered.
I focus on the username and password in order for the user to login. In the file, the username is written on the 4th line, index 3, and the password is written on the 5th line, index 4.
I have created a function. Within the function I used the method "enumerate" file to compare "usern" and "passw" with the existing username and password in the list.
However, there are basic logic errors -it looks at EACH line and outputs: "Username/Password is incorrect", until it finds username or password. It always outputs "You have not logged in" How can I fix this? Tried to use the enumerate method
def loginF(usern,passw):
Login = False
f = open("Reg and Login","r")
data = f.readlines()
User_check = False
Pass_check = False
for usern, line in enumerate(data):
if usern == 3:
print("Username is correct")
User_check = True
if usern != 3:
print("Username is incorrect")
for passw, line in enumerate(data):
if passw == 4:
print("Password is correct")
User_check = True
if passw != 4:
print("Password is incorrect")
if User_check == True and Pass_check == True:
print("You have successfully logged in")
else:
print("You have not logged in")
f.close()
usern = 0
passw = 0
choice = input("Do you want to login (y/n): ")
if choice == "y":
usern = input("Please enter your USERNAME: ")
passw = input("Please enter your PASSWORD: ")
print(loginF(usern,passw))
I am a noob in python and i need help.I have made a phonebook where you can add the contacts.But the problem is that when i exit the program the changes to the list are not saved.I want the user to be able to make permanent changes to the list.I have seen posts about a file=open("something",'w') code to do this(I think) but i dont know where to insert this code and i dont really understand what it is.Could someone help me understand what this is about..Here is the full code:
name = ["ranga","hari"]
number = [9895497777,9]
book = {name[0]:number[0],name[1]:number[1]}
def search():
print("Contacts:")
for x in book:
print(x,':',book[x])
while 1:
count = 0
a = 0
ch1 = input("search: ")
try:
ch1 = int(ch1)
except ValueError:
while a < len(name):
result = name[a].find(ch1)
if result == -1:
a = a + 1
else:
print(name[a],number[a])
a = a + 1
count = count + 1
if count == 0:
print("Not available.Try again")
continue
else:
break
ch1 = str(ch1)
while a < len(number):
sumber = str(number[a])
result = sumber.find(ch1)
if result == -1:
a = a + 1
else:
print(name[a],number[a])
a = a + 1
count += 1
if count == 0:
print("Not available.try again")
continue
else:
break
def add():
print("What is the name of the contact you want to add?")
name1 = input()
name.append(name1)
while 1:
print("What is the number of this contact?")
number1 = input()
try:
number1 = int(number1)
except ValueError:
print("Please type a number..")
continue
number.append(number1)
book[name1] = number1
break
def remoe():
print("Reference:")
for x in book:
print(x,':',book[x])
while 1:
print("What is the name of the contact you want to remove?")
name2 = input()
if name2 in book:
increment = name.index(name2)
name.pop(increment)
number.pop(increment)
del book[name2]
break
else:
print("Not available.Please try again")
while 1:
print("Contacts:")
for x in book:
print(x, ':', book[x])
print("\nWhat do you want to do?\n1.Search for a person\n2.edit the phone book\n3.exit")
choice = input()
try:
choice = int(choice)
except ValueError:
print("Type 1,2 or 3")
continue
if choice == 1:
search()
elif choice == 2:
while 1:
print("Do you want to:\n1.Add a contact\n2.Remove a contact\n3.Go back to main menu")
ch2 = input()
if ch2 in['3']:
break
else:
try:
ch2 = int(ch2)
except ValueError:
print("Type 1 or 2..")
if ch2 == 1:
add()
elif ch2 == 2:
remoe()
elif choice == 3:
exit()
else:
print("Type 1,2 or 3")
I appreciate the help.
When you choose to add a contact, it does properly add the name and number to the list. But, that is it.
When you re-run the program, the list gets re-assigned due to the first 2 lines of your code:
name = ["ranga","hari"]
number = [9895497777,9]
So, you won't see the last changes.
This is where you should maintain a file which lives outside the scope of your code, rather than a list.
You can modify your add function like this:
def add():
print("What is the name of the contact you want to add?")
name1 = input()
#name.append(name1)
# Just add the name1 variable's value to the file
with open('contacts_list.txt', 'a+') as f:
f.write(name1 + '\n')
while 1:
print("What is the number of this contact?")
number1 = input()
try:
number1 = int(number1)
except ValueError:
print("Please type a number..")
continue
#number.append(number1)
# Similarly, append the number1 variable's value to file again.
with open('contacts_list.txt', 'w+') as f:
f.write(number1)
#book[name1] = number1
with open('contacts_list.txt', 'r') as f:
print(f.read())
break
Note: You would also need to change the other functions search and remove to read and write from the file. I've just given you a taste of how things are done. You need to modify your code and make it work.
Let me know if it helps.
I took your advice and made a new text file but i still did not know how to do it but after reading ur answers i understood and at last i came to this..
removelist = []
def search():
while 1:
search = str(input("Search: "))
if search not in["exit", "Exit"]:
with open('output.txt', 'r+') as f:
line = f.readline()
while line:
data = line.find(search)
if not data == -1:
print(line.rstrip('\n'))
line = f.readline()
else:
line = f.readline()
else:
break
f.close()
def add():
print("Type the name of the contact:")
name = input()
while 1:
print("Type the number of this contact:")
number = input()
try:
number = int(number)
except ValueError:
print("Please type a number")
continue
number = str(number)
with open('output.txt', 'a+') as f:
f.write('\n' + name +' ' + number)
break
def remoe(): #this is where the problem comes in
while 1:
remove = str(input("Remove: "))
with open('output.txt', 'r+') as f:
line = f.readline()
while line:
if not remove in["Remove", "remove"]:
removelist.clear()
data = line.find(remove)
if not data == -1:
removelist.append(line) #This saves all the lines coming from the search to a
print(removelist) #removelist which can be accessed when you type in remove
line = f.readline() #But the problem is that if there is a \n at the end of the
else: #string then the remove function does not work
line = f.readline()
else:
print(removelist)
with open('output.txt', 'r') as f:
d = f.readlines()
f.close()
with open('output.txt', 'w') as f:
for i in d:
if i not in removelist:
f.write(i)
f.truncate()
f.close()
break
while 1:
with open('output.txt', 'r') as f:
data = f.read()
print("Contacts:")
print(data)
print('''What do you want to do?
1.Search for a contact
2.Edit contacts
3.Exit''')
f.close()
choice = input()
if choice in["1"]:
search()
elif choice in["2"]:
while 1:
print('''What do you wanna do:
1.Add a contact
2.Remove a contact
3.Exit to main menu''')
ch1 = input()
if ch1 in["1"]:
add()
elif ch1 in["2"]:
remoe()
elif ch1 in["3"]:
break
else:
print("Please type 1,2 or 3")
elif choice in[3]:
print("Ok bye")
else:
print("Please type 1,2 or 3")
Now the problem seems to be the remove function..if i try to remove a line with \n at the end of it then it wont work while the opp. seems to work.Any guess what i am doing here?
And thanks for the help Mayank porwal
At the first you should know name = ["ranga","hari"], number = [9895497777,9] that you have defined are in the code and you can not change those value, and after exit() they will reset to default value.
you should use of file (for example .txt file) in this issue:
1. you must create a .txt file in your project (for example Contacts.txt)
2. and write your information in there (for example in first line: Kourosh +98938....)
3. at the first step in your program you must read Contact.txt and load it in a structure like a list or dictionary (for example
>>> with open('workfile') as f:
... read_data = f.read()
>>> f.closed
)
4.now you can edit, add, remove structure.
5.and finally you can write structure in the file, before exit()
for example:
>>> with open('workfile') as f:
... f.write(s)
>>> f.closed
I am trying to write a quiz program that saves and reads from text files, storing the users details in a unique text file for each user. Each user file is saved in the format:
name, age, (line 1)
username (line 2)
password (line 3)
I currently am getting the error 'IndexError: list index out of range' whilst attempting to read a two lines from a file so the program can decide whether the user has entered the correct login details. I understand that the error is due to the program not seeing line three but I cannot understand why.
import sys
def signUp ():
name=input("Please enter your first name and last name. \n- ")
name = name.lower()
username=name[0:3]
age= input("Please input your age. \n- ")
username = username + age
password = input("Please input a password. \n- ")
print ("Your username is "+username+" and your password is " +password)
userfile = open(name+".txt", "r")
userfile.write(name+", "+age+"\n")
userfile.write(username+"\n")
userfile.write(password+"\n")
userfile.close()
return name, age, username, password
def login():
logname = input("Please enter your first name and last name. \n- ")
logname = logname.lower()
loginFile = open (logname+".txt", "r")
inputuname = input ("Enter your username. \n- ")
inputpword = input("Enter your password. \n- ")
username = loginFile.readlines(1)
password = loginFile.readlines(2)
print (username)
print (password)
loginFile.close()
if inputuname == username[1].strip("\n") and inputpword ==
password[2].strip("\n"):
print("success")
quiz()
else:
print("invalid")
def main():
valid = False
print ("1. Login")
print ("2. Create Account")
print ("3. Exit Program")
while valid != True:
choice =input("Enter an Option: ")
if choice == "1":
login()
elif choice == ("2"):
user = signUp()
elif choice== ("3"):
valid = True
else:
print("not a valid option")
def quiz():
score = 0
topic = input ("Please choose the topic for the quiz. The topics available
are: \n- Computer Science \n- History")
difficulty = input("Please choose the diffilculty. The difficulties
available are: \n- Easy \n- Medium \n- Hard")
questions = open(topic+"questions.txt", "r")
for i in range(0,4):
questions = open(topic+" "+difficulty+".txt", "r")
question = questions.readline(i)
print(question)
answers = open (topic+" "+difficulty+" answers.txt", "r")
answer = answers.readline(i)
print(answer)
userAns = input()
questions.close
answers.close
if userAns == answer:
score = score + 1
return score
main()
You should use with open(....) as name: for file operations.
When writing to a file you should use a for append / r+ for read+write, or w to recreate it - not 'r' that is for reading only.
As for your login():
def login():
logname = input("Please enter your first name and last name. \n- ")
logname = logname.lower()
inputuname = input("Enter your username. \n- ")
inputpword = input("Enter your password. \n- ")
with open(logname + ".txt", "r") as loginFile:
loginfile.readline() # skip name + age line
username = loginFile.readline() # read a single line
password = loginFile.readline() # read a single line
print(username)
print(password)
if inputuname == username.strip("\n") and inputpword == password.strip("\n"):
print("success")
quiz()
else:
print("invalid")
File-Doku: reading-and-writing-files
If the file does not exist your code will crash, see How do I check whether a file exists using Python?
So I originally completed this task with nothing but a few if, elif statements. But it was requested that I break the work of those statements out into a separate functions as an additional exercise. I need to acquire names to add to a list and have the ability to edit or remove the names. But Im struggling to have the functions return their output to the list.
Here is what I have so far
print("Roster Management")
def addplayer():
name=input("Enter new player name: ")
roster = [name]
list(roster)
roster.append(name)
def removeplayer():
name = input('Enter player for removal: ')
roster.remove(name)
def editplayer():
oldname = input('Enter name you want to edit: ')
newname = input('Enter new name: ')
[x.replace(oldname, newname) for x in roster]
while 1==1:
print('---------- Main Menu ------------')
print("Choose from the following options")
print('1. Display Team Roster')
print('2. Add Member')
print('3. Remove Member')
print('4. Edit Member')
print('9. Exit Program')
print(" ")
selection = input("Enter Selection: ")
if selection == '1':
for x in roster:
print(roster)
elif selection == '2':
addplayer()
elif selection == '3':
removeplayer()
elif selection == '4':
editplayer()
elif selection == '9':
print("Closing program...")
break`enter code here`
There're few things that are wrong with your code:
#1
roster = [name] # this creates a new list with a single element in it instead of appending to some existing list
list(roster) # you're trying to convert a list to a list, so not needed
roster.append(name) # you should've some local/global roaster to append to
#2
def removeplayer():
name = input('Enter player for removal: ')
roster.remove(name) # again, you should've some local/global roaster to append to
#in case of local you should return the list for further usage, in case of global you can simply remove
#3
[x.replace(oldname, newname) for x in roster]
# again you're neither updating any existing list/ nor returned anything
# also check if `x==oldname` then replace with new name
#4
for x in roster:
print(roster) # x is what you should be printing, not the whole list (roaster)
So, your updated code with these changes would be something like this:
roster = []
def addplayer():
name=input("Enter new player name: ")
roster.append(name)
def removeplayer():
name = input('Enter player for removal: ')
roster.remove(name)
def editplayer():
global roster
oldname = input('Enter name you want to edit: ')
newname = input('Enter new name: ')
roster = [newname if x == oldname else oldname for x in roster]
print("Roster Management")
while 1==1:
print('---------- Main Menu ------------')
print("Choose from the following options")
print('1. Display Team Roster')
print('2. Add Member')
print('3. Remove Member')
print('4. Edit Member')
print('9. Exit Program')
print(" ")
selection = input("Enter Selection: ")
if selection == '1':
for x in roster:
print(x)
elif selection == '2':
addplayer()
elif selection == '3':
removeplayer()
elif selection == '4':
editplayer()
elif selection == '9':
print("Closing program...")
break
Add
return list
at the end of your definition because right now the definition doesn't know what it is supposed to return. Also in your, if statement you should have
print(def())
instead of just
def()
Hope this helps