Limit the amount of inputs in a Python list - python

I want to set a limit to which the user can input names. This is where I got to and got stuck. How would I set a limit of 10 to the names the user can input into the list and restrict them from entering anymore?
names = []
print ('1 = Add Name ')
print ('2 = Display List ')
print ('3 = Quit ')
while True:
option = input('What would you like to do: ')
if option == '1':
name= input('Enter name: ')
names.append(name)

you can do :
if option == '1':
names = [input('Enter name:') for _ in range(10)]

I hope that following script can help you:
# libraries
import sys
# list variable to store name
names = []
# limits to save name
limit = 10
# function to display menu
def menu():
print("Enter 1 to add Name")
print("Enter 2 to show list")
print("Enter 3 to quit")
choice = int(raw_input("Enter your choice : "))
return choice
# running for infinite times till user quits
while(True):
choice = menu()
if(choice == 1):
name = raw_input("Enter name to add in list : ")
if(len(names) > 10):
print("You cannot enter more names")
else:
names.append(name)
print(name + " - Name saved successfully.")
if(choice == 2):
print("List of names : ")
print(names)
if(choice == 3):
sys.exit()

Related

Unable to pass/exit a python function

Just starting out with python functions (fun_movies in functions.py) and I can't seem to get out (via "no" or False) once in the loop:
main_menu.py
from functions import *
def menu():
print("Press 1 for movies.")
print("Press 2 to exit.")
menu()
option = int(input("Input a number: "))
while option != 0:
#try:
if option == 1:
fun_movies()
elif option == 2:
print("Goodbye! ")
break
else:
print ("Wrong input")
functions.py
global movies
movies = {}
def fun_movies():
name = input("Insert movie name: ")
genre = input("Input genre: ")
movies [name] = [genre]
a = True
while a:
query = input("Do you want to input another movie? (yes/no) ")
if query == "yes":
name = input("Insert movie name: ")
genre = input("Input genre: ")
movies_if = {}
movies_if [name] = [genre]
movies.update(movies_if)
elif query == "no":
break
else:
print ("Wrong input!")
return movies
Code works fine when not called via import. When called via import (in main_menu.py), it keeps asking for infinite movies even when I input a "no". I can't find a way to exit the loop. Initially I had a "pass" but that didn't work.
Thanks in advance!
global movies
movies = {}
def fun_movies():
name = input("Insert movie name: ")
genre = input("Input genre: ")
movies [name] = [genre]
a = True
while a:
query = input("Do you want to input another movie? (yes/no) ")
if query == "yes":
name = input("Insert movie name: ")
genre = input("Input genre: ")
movies_if = {}
movies_if [name] = [genre]
movies.update(movies_if)
elif query == "no":
a = False
else:
print ("Wrong input!")
return movies
A few things:
Firstly, you don't need a==True as this statement returns True when a is True and False when a is False, so we can just use a as the condition.
Secondly, only use the input at the start of the loop as you want to ask once per iteration
Thirdly, place your return outside the loop so you only return when a==False and you don't want to input another movie.
edit:
main file>
from functions import *
def menu():
print("Press 1 for movies.")
print("Press 2 to exit.")
menu()
option = int(input("Input a number: "))
while option != 0:
if option == 1:
fun_movies()
elif option == 2:
print("Goodbye! ")
break
else:
print ("Wrong input")
option = int(input("Input a number"))
global movies
movies = {}
def fun_movies():
name = input("Insert movie name: ")
genre = input("Input genre: ")
movies[name]= genre
a = True
while a:
query = input("Do you want to input another movie? (yes/no) ")
if query == "yes":
name = input("Insert movie name: ")
genre = input("Input genre: ")
movies_if = {}
movies_if [name] = genre
movies.update(movies_if)
elif query == "no":
break
else:
print ("Wrong input!")
# continue
return movies
print(fun_movies())
Hope It works for you!

How to check String input from user inside Class Array

I'm working on an exercise, but I'm stuck on the last part
The section goes here:
Rewrite the function remove_friend so it asks for both the firstname and the lastname and remove all in the list_of_friends for which the first- and last name of the friend object equals the first- and last name entered by the user
In the remove_friends function, I know it's not correct.
In my head, I think I need to compare the delete_first_name and delete_last_name against the first_name and last_name in the new_friends class.
However, I don't know what the syntax would be in order to accomplish this.
Does anyone have hints on how to proceed? I would greatly appreciate if you could give suggestions, and not write the solution.
class Friend:
def __init__(self, first_name, last_name, phone_number):
self.first_name = first_name
self.last_name = last_name
self.phone_number = phone_number
def print_info(self, index):
print(f"\n {self.first_name}, {self.last_name}, {self.phone_number} \n")
list_of_friends = []
def add_friends():
print(" ")
first_name = input("Enter the first name: ")
last_name = input("Enter the last name: ")
phone_number = input("Enter the phone number: ")
new_friend = Friend(first_name.upper(), last_name.upper(), phone_number)
list_of_friends.append(new_friend)
print(f"{new_friend.first_name.title()} {new_friend.last_name.title()} has been added to the list \n")
def view_friends():
if len(list_of_friends):
for counter, new_friend in enumerate(list_of_friends, 0):
print(" ")
new_friend.print_info(counter)
else:
print(" ")
print("List is empty \n")
def remove_friends():
print(" ")
delete_first_name = input("Enter first name to remove: ").upper()
delete_last_name = input("Enter last name to remove: ").upper()
full_name = [delete_first_name, delete_last_name]
if full_name not in list_of_friends:
print(f"{delete_first_name} {delete_last_name} does not exist in the list \n")
else:
list_of_friends.remove(delete_first_name)
list_of_friends.remove(delete_last_name)
print(f"{delete_first_name} {delete_last_name}has been deleted from the list \n")
def print_menu():
menu_string = "\n----Options----\n"
menu_string += "1: Add\n"
menu_string += "2: View\n"
menu_string += "3: Remove\n"
menu_string += "4: Exit\n"
print(menu_string)
user_input = 0
while user_input != 4:
print_menu()
try:
user_input = int(input("Choose one of the above options: "))
if user_input < 1 or user_input > 4:
print("Invalid number. Number must be between 1-4 \n")
elif user_input == 1:
add_friends()
elif user_input == 2:
view_friends()
elif user_input == 3:
remove_friends()
except Exception as err:
print(f"Invalid input: {err}")
print("Exiting \n")
Loop the the list of friends and check first and last name
def remove_friends():
print(" ")
delete_first_name = input("Enter first name to remove: ").upper()
delete_last_name = input("Enter last name to remove: ").upper()
new_list = []
for frnds in list_of_friends:
fnm = frnds.first_name
lnm = frnds.last_name
if(fnm == delete_first_name and lnm == delete_last_name):
# print something meaningfull
continue
else:
new_list.append(frnds)
# new_list will contain the list of friends after removal
The list list_friends has Friend objects and not strings.
you need to access the Friend attributes.
for example like this (function is not complete):
def remove_friends():
first_name=...
last_name = ...
temp_list = list_of_friends[:]
for friend in temp_list :
if first_name == friend.first_name and last_name == friend.last_name:
list_of_friends.remove(friend)
Note that in the beginning I copied the list - do not iterate over a list (or similar) and delete objects from the same list, it is a recipe for bugs.

Python Pulling from Datasheets

I am trying to create code to pull from a data sheet. My goal is to find the longest song, songs by year, and songs by an artist. Problem is, that when I run what I currently have I get a value returned of 0. Obviously this is not correct. What ways can I do to solve this? I have linked the data sheet here. Click here!
def longest_song():
pass
def songs_by_year(year):
total=0
with open('music.csv', 'r') as f:
for line in f:
time = line.split(",")
song = time[34]
if song == year:
total = total + 1
return total
def all_songs_by_artist(artist):
total = int(0)
data = open("music.csv", "r")
for line in data:
name = line.split(",")
song = name[2]
if song == artist:
total = total + 1
return total
# --------------------------------------
def menu():
print()
print("1. Identify longest song.")
print("2. Identify number of songs in a given year.")
print("3. Identify all songs by a given artist.")
print("4. You choose something that is interesting and non-trivial.")
print("5. Quit.")
# --------------------------------------
def main():
choice = 0
while (choice != 5):
menu()
choice = int(input("Enter your choice: "))
if (choice == 1):
longest_song()
elif (choice == 2):
year = int(input("Enter desired year: "))
number = songs_by_year(year)
## print("The number of songs from", "{:,d}".format(number))
print(number)
elif (choice == 3):
artist = input("Enter name of artist: ").lower()
all_songs_by_artist(artist)
number = all_songs_by_artist(artist)
print("There are", "{:,d}".format(number))
elif (choice == 4):
pass
elif (choice != 5):
print("That is not a valid option. Please try again.")
# --------------------------------------
main()
You are converting input artist to lowercase but Not changing the artist from the file to lower case, thus no matches.
You are converting the Year to an int but not doing so to the year from the file.
It is difficult to tell if there are other issues, as your code sample is not indented properly.
I'm guessing but I suppose that it should look something like this.
def longest_song(): pass
def songs_by_year(year):
total=0
with open('music.csv', 'r') as f:
for line in f:
time = line.split(",")
song = time[34]
try:
if int(song) == year:
total = total + 1
except:
pass
return total
def all_songs_by_artist(artist):
total = int(0)
with open("music.csv", "r") as data:
for line in data:
name = line.split(",")
song = name[2].lower()
if song == artist:
total = total + 1
return total
# --------------------------------------
def menu():
print()
print("1. Identify longest song.")
print("2. Identify number of songs in a given year.")
print("3. Identify all songs by a given artist.")
print("4. You choose something that is interesting and non-trivial.")
print("5. Quit.")
# --------------------------------------
def main():
choice = 0
while (choice != 5):
menu()
choice = int(input("Enter your choice: "))
if (choice == 1):
longest_song()
elif (choice == 2):
year = int(input("Enter desired year: "))
number = songs_by_year(year)
## print("The number of songs from", "{:,d}".format(number))
print(number)
elif (choice == 3):
artist = input("Enter name of artist: ").lower()
all_songs_by_artist(artist)
number = all_songs_by_artist(artist)
print("There are", "{:,d}".format(number))
elif (choice == 4):
pass
elif (choice != 5):
print("That is not a valid option. Please try again.")
# --------------------------------------
main()

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?: "))

Using Python's pickle to open and save a dictionary

In the final days of my intro comp sci class, we got to creating dictionaries. A homework program in our book asks us to create something that can look up, add, change, and delete a set of names and email addresses. It asks us to pickle the dictionary, but the kicker for me is that it stipulates that each time the program starts, it should retrieve the dictionary from the file and unpickle it. I don't know if I coded myself into a corner, but I can't figure out how to do this with what I've done so far.
My code:
import mMyUtils
import pickle
LOOK_UP = 1
ADD = 2
CHANGE = 3
DELETE = 4
QUIT = 5
def main():
emails = {}
choice = 0
while choice != QUIT:
choice = getMenuChoice()
if choice == LOOK_UP:
lookUp(emails)
elif choice == ADD:
add(emails)
elif choice == CHANGE:
change(emails)
elif choice == DELETE:
delete(emails)
else:
exit
def getMenuChoice():
print()
print('Name and Email Address Catalog')
print('------------------------------')
print('1. Look up an email address')
print('2. Add a new email address')
print('3. Change an email address')
print('4. Delete an email address')
print('5. Quit the program')
print()
choice = int(input('Enter the choice: '))
while choice < LOOK_UP or choice > QUIT:
choice = int(input('Enter a valid choice: '))
return choice
def lookUp(emails):
name = input('Enter a name: ')
print(emails.get(name, 'Not found.'))
def add(emails):
name = input('Enter a name: ')
address = input('Enter an email address: ')
if name not in emails:
emails[name] = address
pickle.dump(emails, open("emails.dat", "wb"))
else:
print('That entry already exists.')
def change(emails):
name = input('Enter a name: ')
if name in emails:
address = input('Enter the new address: ')
emails[name] = address
pickle.dump(emails, open("emails.dat", "wb"))
else:
print('That name is not found.')
def delete(emails):
name = input('Enter a name: ')
if name in emails:
del emails[name]
else:
print('That name is not found.')
main()
I know I should set my emails variable to be some form of pickle.load, but I can't figure it out for the life of me. mMyUtils is a library I made for try/except logic, I'll put that in once I get the new stuff working.
If you're saving the dictionary like so:
pickle.dump(emails, open('emails.dat', 'wb'))
The following will load it back:
emails = pickle.load(open('emails.dat', 'rb'))
You must load the file and unpickle the data before you can access it, change lookUp() to this:
def lookUp(emails):
with open("emails.dat", "rb") as fo:
emails = pickle.load(fo)
name = input('Enter a name: ')
print(emails.get(name, 'Not found.'))
Consider yourself using ast.literal_eval instead of pickle: http://docs.python.org/2/library/ast.html#ast.literal_eval
>>>import ast
>>> print mydict
{'bob': 1, 'danny': 3, 'alan': 2, 'carl': 40}
>>> string="{'bob': 1, 'danny': 3, 'alan': 2, 'carl': 40}"
>>> type(string)
<type 'str'>
>>> type( ast.literal_eval(string) )
<type 'dict'>
To save/read dict from file, you can do it like with normal string.
The problem was, and I guess I didn't emphasis it enough, was what I was supposed to do if the dictionary didn't exist in the first place. The design doc states that you should load the dictionary every time you run the program. Well if you're running the program for the first time, you don't have a dictionary to load, leading to an error. I got around this by basically doing the function twice using try/except.
My code:
import mMyUtils
import pickle
import dictionaryGenerator
LOOK_UP = 1
ADD = 2
CHANGE = 3
DELETE = 4
QUIT = 5
def main():
hasError = False
try:
emails = pickle.load(open('emails.dat', 'rb'))
choice = 0
while choice != QUIT:
choice = getMenuChoice()
if choice == LOOK_UP:
lookUp(emails)
elif choice == ADD:
add(emails)
elif choice == CHANGE:
change(emails)
elif choice == DELETE:
delete(emails)
else:
print("Good-bye!")
exit
except Exception as err:
hasError = True
mMyUtils.printError("Error: no such file",err)
mMyUtils.writeToErrorLog()
finally:
if hasError:
emails = {}
choice = 0
while choice != QUIT:
choice = getMenuChoice()
if choice == LOOK_UP:
lookUp(emails)
elif choice == ADD:
add(emails)
elif choice == CHANGE:
change(emails)
elif choice == DELETE:
delete(emails)
else:
print("Good-bye!")
exit
def getMenuChoice():
print()
print('Name and Email Address Catalog')
print('------------------------------')
print('1. Look up an email address')
print('2. Add a new email address')
print('3. Change an email address')
print('4. Delete an email address')
print('5. Quit the program')
print()
choice = int(input('Enter the choice: '))
while choice < LOOK_UP or choice > QUIT:
choice = int(input('Enter a valid choice: '))
return choice
def lookUp(emails):
name = input('Enter a name: ')
print(emails.get(name, 'Not found.'))
def add(emails):
name = input('Enter a name: ')
address = input('Enter an email address: ')
if name not in emails:
emails[name] = address
with open("emails.dat", "wb") as infile:
pickle.dump(emails, infile)
else:
print('That entry already exists.')
def change(emails):
name = input('Enter a name: ')
if name in emails:
address = input('Enter the new address: ')
emails[name] = address
with open("emails.dat", "wb") as infile:
pickle.dump(emails, infile)
else:
print('That name is not found.')
def delete(emails):
name = input('Enter a name: ')
if name in emails:
del emails[name]
else:
print('That name is not found.')
main()

Categories

Resources