create lists with different index in python - python-3.x

I am trying to create a list using a loop, but I want the group to have the same index. Using append, it merges them together. What am I doing wrong?
L=[]
l=[]
def information():
i=0
while i <= 3:
if i==0:
first_name = str(input('First Name : '))
l.append(first_name)
i += 1
elif i==1:
last_name = str(input('Second Name : '))
l.append(last_name)
i += 2
elif i > 2:
wish = str(input('If you wish to continue Press Y/y or Press N/n:'))
if wish == 'y' or wish == 'Y':
L.append(l)
start()
elif wish != 'y' or wish != 'Y':
break
def start():
information()
start()
print('l', l)
print('L ', L)
My desired output is:
[['sachin', 'tendulkar'],['sachin', 'tendulkar'],['sachin', 'tendulkar']]
and I am getting this instead:
['sachin', 'tendulkar','sachin', 'tendulkar']

A little different than what you had going but this might work
Names = []
def information():
wish = str(input("Do you wish to add a name? Press Y/y for yes or Press N/n for no: "))
while ((wish == 'y') or (wish == 'Y')):
fname = str(input('First Name: '))
lname = str(input('Last Name: '))
Names.append([fname, lname])
wish = str(input("Do you wish to add a name? Press Y/y for yes or Press N/n for no: "))
information()
print (Names)

Related

Looking for general feedback + a few small errors

So as the title states I'm simply looking for general feedback on the overall structure of the script, where I could do better (don't have to tell me how, where would be plenty) and things like that. Any feedback, advice, tips or help in general is always greatly appreciated as I'm real keen to learn deeper!
As for the errors...
Errors:
It doesn't seem to save any of the contacts after closing, if the only method of saving it, to save it to a file?
Updating claims to be out of range, which if I'm correct it shouldn't be, unless I'm just not seeing something?
Not exactly an issue but something I've been playing with, with no good result...is it possible to have a for loop w/if statement in a comprehension format without being in a print statement?
My code so far:
"""
This is project that lets the user pretty much create and edit a contact book by giving them options and using their
input to complete the data needed for the contact book.
"""
import sys
contacts = []
lst = []
def ContactBook():
rows, cols = int(input("Please enter the amount of people you want in the contact book: ")), 5
print(contacts)
for i in range(rows):
print(f"All mandatory fields will include *")
for a in range(cols):
if a == 0:
lst.append(input("Enter a name*: "))
if lst[a] == '' or lst[a] == "": sys.exit(f"Failed to provide a name...Exiting the contact book!")
if a == 1: lst.append(input("Enter a number*: "))
if a == 2:
lst.append(input("Enter an email: "))
if lst[a] == '' or lst[a] == "": lst[a] = None
if a == 3:
lst.append(input("Enter a D.O.B (mm/dd/yy): "))
if lst[a] == '' or lst[a] == "": lst[a] = None
if a == 4:
lst.append(input("What category (Family/Friends/Work/Others): "))
if lst[a] == '' or lst[a] == "": lst[a] = None
contacts.append(lst)
print(f"Your contacts are:\n{contacts}")
return contacts
def Menu():
print(f"\t\t\t{'Contact Book':*^70}", flush=False)
print(f"Your options are:\n1. Add a Contact\n2. Searching Contacts\n3. Edit Contacts\n4. Delete Contacts\n"
f"5. View Contacts\n6. Delete Everything\n7. Exit the book")
choice = int(input("Please select an option: "))
return choice
def AddingContacts(cb):
for i in range(len(cb[0])):
if i == 0: contacts.append(input("Enter a name: "))
elif i == 1: contacts.append(int(input("Enter a number: ")))
elif i == 2: contacts.append(input("Enter a email: "))
elif i == 3: contacts.append(input("Enter a d.o.b (mm/dd/yy): "))
elif i == 4: contacts.append(input("Enter a category: "))
cb.append(contacts)
return cb
def SearchContacts(cb):
s = int(input("Select an option:\n1. Name\n2. Number\n3. Email\n4. D.O.B\n5. Category"))
t, c = [], -1
if s == 1:
q = input("Enter who you want to search: ")
for i in range(len(cb)):
if q == cb[i][0]: c = i, t.append(cb[i])
elif s == 2:
q = int(input("Enter the number you want to find: "))
for i in range(len(cb)):
if q == cb[i][1]: c = i, t.append(cb[i])
elif s == 3:
q = input("Enter the email you want to search: ")
for i in range(len(cb)):
if q == cb[i][2]: c = i, t.append(cb[i])
elif s == 4:
q = input("Enter the date you want to search in mm/dd/yy format: ")
for i in range(len(cb)):
if q == cb[i][3]: c = i, t.append(cb[i])
elif s == 5:
q = input("Enter a category you want to search: ")
for i in range(len(cb)):
if q == cb[i][4]: c = i, t.append(cb[i])
else:
print(f"Invalid search inquiry...")
return -1
if c == -1: return -1
elif c != -1:
ShowContent(t)
return c
def ShowContent(cb):
if not cb: print(f"List has nothing in it...: []")
else: print(f"{[cb[i] for i in range(len(cb))]}")
return cb
def UpdateContacts(cb):
for i in range(len(cb[0])):
if i == 0: contacts[0] = (input("Enter a name: "))
elif i == 1: contacts[1] = (int(input("Enter a number: ")))
elif i == 2: contacts[2] = (input("Enter a email: "))
elif i == 3: contacts[3] = (input("Enter a d.o.b: "))
elif i == 4: contacts[4] = (input("Enter a category: "))
cb.append(contacts)
return cb
def RemovingContacts(cb):
q = input("Enter the person you want to remove: ")
x = 0
for i in range(len(cb)):
if q == cb[i][0]: x += 1, print(f"This contact has now been removed: {cb.pop(i)}")
return cb
if x == 0: print(f"Person doesn't exist. Please check the name and try again....")
return cb
def DeleteBook(cb):
return cb.clear()
if __name__ == "__main__":
print(f"Welcome to your new Contact Book! Hope you find it easy to navigate!")
ch = 1
cb = ContactBook()
while ch in (1, 2, 3, 4, 5, 6):
ch = Menu()
if ch == 1: cb = AddingContacts(cb)
elif ch == 2: cb = SearchContacts(cb)
elif ch == 3: cb = UpdateContacts(cb)
elif ch == 4: cb = RemovingContacts(cb)
elif ch == 5: cb = ShowContent(cb)
elif ch == 6: cb = DeleteBook(cb)
else: sys.exit(f"Thank you for using this contact book! Have a great day!")
I plan on using the Pandas module to display the data in table format, is it possible without mySQL?

Python number guessing game not displaying feedback correctly. What's the problem?

So I tried to make a game where the computer chooses a random 4 digit number out of 10 given numbers. The computer then compares the guess of the user with the random chosen code, and will give feedback accordingly:
G = correct digit that is correctly placed
C = correct digit, but incorrectly placed
F = the digit isn't in the code chosen by the computer
However, the feedback doesn't always output correctly.
Fox example, when I guess 9090, the feedback I get is F C F, while the feedback should consist of 4 letters.... How can I fix this?
#chooses the random pincode that needs to be hacked
import random
pincode = [
'1231', '9997', '8829', '6765', '9114', '5673', '0103', '4370', '8301', '1022'
]
name = None
#Main code for the game
def main():
global code
global guess
#Chooses random pincode
code = random.choice(pincode)
#Sets guessestaken to 0
guessesTaken = 0
while guessesTaken < 10:
#Makes sure every turn, an extra guess is added
guessesTaken = guessesTaken + 1
#Asks for user input
print("This is turn " + str(guessesTaken) + ". Try a code!")
guess = input()
#Easteregg codes
e1 = "1955"
e2 = "1980"
#Checks if only numbers have been inputted
if guess.isdigit() == False:
print("You can only use numbers, remember?")
guessesTaken = guessesTaken - 1
continue
#Checks whether guess is 4 numbers long
if len(guess) != len(code):
print("The code is only 4 numbers long! Try again!")
guessesTaken = guessesTaken - 1
continue
#Checks the code
if guess == code:
#In case the user guesses the code in 1 turn
if (guessesTaken) == 1:
print("Well done, " + name + "! You've hacked the code in " +
str(guessesTaken) + " turn!")
#In cases the user guesses the code in more than 1 turn
else:
print("Well done, " + name + "! You've hacked the code in " +
str(guessesTaken) + " turns!")
return
#Sets empty list for the feedback on the user inputted code
feedback = []
nodouble = []
#Iterates from 0 to 4
for i in range(4):
#Compares the items in the list to eachother
if guess[i] == code[i]:
#A match means the letter G is added to feedback
feedback.append("G")
nodouble.append(guess[i])
#Checks if the guess number is contained in the code
elif guess[i] in code:
#Makes sure the position of the numbers isn't the same
if guess[i] != code[i]:
if guess[i] not in nodouble:
#The letter is added to feedback[] if there's a match
feedback.append("C")
nodouble.append(guess[i])
#If the statements above are false, this is executed
elif guess[i] not in code:
#No match at all means an F is added to feedback[]
feedback.append("F")
nodouble.append(guess[i])
#Easteregg
if guess != code and guess == e1 or guess == e2:
print("Yeah!")
guessesTaken = guessesTaken - 1
else:
print(*feedback, sep=' ')
main()
You can try the game here:
https://repl.it/#optimusrobertus/Hack-The-Pincode
EDIT 2:
Here, you can see an example of what I mean.
Here is what I came up with. Let me know if it works.
from random import randint
class PinCodeGame(object):
def __init__(self):
self._attempt = 10
self._code = ['1231', '9997', '8829', '6765', '9114', '5673', '0103', '4370', '8301',
'1022']
self._easterEggs = ['1955', '1980', '1807', '0609']
def introduction(self):
print("Hi there stranger! What do I call you? ")
player_name = input()
return player_name
def show_game_rules(self):
print("10 turns. 4 numbers. The goal? Hack the pincode.")
print(
"For every number in the pincode you've come up with, I'll tell you whether it is correct AND correctly placed (G), correct but placed incorrectly (C) or just plain wrong (F)."
)
def tutorial_needed(self):
# Asks for tutorial
print("Do you want a tutorial? (yes / no)")
tutorial = input().lower()
# While loop for giving the tutorial
while tutorial != "no" or tutorial != "yes":
# Gives tutorial
if tutorial == "yes":
return True
# Skips tutorial
elif tutorial == "no":
return False
# Checks if the correct input has been given
else:
print("Please answer with either yes or no.")
tutorial = input()
def generate_code(self):
return self._code[randint(0, len(self._code))]
def is_valid_guess(self, guess):
return len(guess) == 4 and guess.isdigit()
def play(self, name):
attempts = 0
code = self.generate_code()
digits = [code.count(str(i)) for i in range(10)]
while attempts < self._attempt:
attempts += 1
print("Attempt #", attempts)
guess = input()
hints = ['F'] * 4
count_digits = [i for i in digits]
if self.is_valid_guess(guess):
if guess == code or guess in self._easterEggs:
print("Well done, " + name + "! You've hacked the code in " +
str(attempts) + " turn!")
return True, code
else:
for i, digit in enumerate(guess):
index = int(digit)
if count_digits[index] > 0 and code[i] == digit:
count_digits[index] -= 1
hints[i] = 'G'
elif count_digits[index] > 0:
count_digits[index] -= 1
hints[i] = 'C'
print(*hints, sep=' ')
else:
print("Invalid input, guess should be 4 digits long.")
attempts -= 1
return False, code
def main():
# initialise game
game = PinCodeGame()
player_name = game.introduction()
print("Hi, " + player_name)
if game.tutorial_needed():
game.show_game_rules()
while True:
result, code = game.play(player_name)
if result:
print(
"Oof. You've beaten me.... Do you want to be play again (and be beaten this time)? (yes / no)")
else:
print("Hahahahaha! You've lost! The correct code was " + code +
". Do you want to try again, and win this time? (yes / no)")
play_again = input().lower()
if play_again == "no":
return
main()

A permanent list change(Save python file)

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

Beginner Python list, defining variable

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

Return to main function in python

Working on Python 3.4.3
Let's say I have created three fuctions:
def choosing(mylist=[]):
print("We will have to make a list of choices")
appending(mylist)
done = False
while(done == "False"):
confirm = input("Is your list complete?[Y/N]")
if(confirm == "Y"):
print("Yaay! Choices creation complete."
"{} choices have been added successfully".format(len(mylist)))
done = True
elif(confirm == "N"):
action = input("What do you want to do? [Append/Delete]")
if(action == "Append"):
appending(mylist)
done = False
elif(action == "Delete"):
removing(mylist)
done = False
def appending(mylist1 = []):
print("Please type EOF when you want to stop!")
while True:
c = input("Please enter EOF to stop adding. Please enter a choice: ")
if(c=="EOF"):
break
else:
mylist1.append(c)
print("You have inserted {} choices".format(len(mylist1)))
print("Please verify them below: ")
for x in range(0, len(mylist1)):
print(mylist1[x])
def removing(mylist2 = []):
print("Following are choices: ")
r = input("What do you want to remove? ")
mylist2.remove(r)
print("{} successfully removed!".format(r))
Now problem is I can't just call choices() in append or remove function as choices() function will call append again and again infinitely.
So how do I get back in choices after appending or removing data in list?
As suggested by tobias_k, you should add the contents of choices() into a while loop.
I also found
some other problems:
False does not equal "False", so your while loop never runs.
You use terms like mylist, mylist1, and mylist2 - it's better to rename these to choosing_list, appending_list, and removing_list, so it's clearer.
You also shouldn't use False to define a while loop - instead, make a variable, then set it to True. When you have to stop, set it to False.
Here is the code with those problems fixed:
def appending(appending_list = []):
print("Please type EOF when you want to stop!")
while True:
c = input("Please enter EOF to stop adding. Please enter a choice: ")
if(c=="EOF"):
break
else:
appending_list.append(c)
print("You have inserted {} choices".format(len(appending_list)))
print("Please verify them below: ")
for x in range(0, len(appending_list)):
print(appending_list[x])
return appending_list
def removing(removing_list = []):
print("Following are choices: ")
r = input("What do you want to remove? ")
removing_list.remove(r)
print("{} successfully removed!".format(r))
return removing_list
print("We will have to make a list of choices")
choosing_list = appending()
list_incomplete = True
while list_incomplete:
confirm = input("Is your list complete?[Y/N]")
if(confirm == "Y"):
print("Yaay! Choices creation complete."
"{} choices have been added successfully".format(len(choosing_list)))
list_incomplete = False
elif(confirm == "N"):
action = input("What do you want to do? [Append/Delete]")
if(action == "Append"):
choosing_list = appending(choosing_list)
elif(action == "Delete"):
choosing_list = removing(choosing_list)
Let me know if there's any problems with this code.

Resources