Appending a List at runtime in Python - python

I'm Creating a project in which i have two lists.
One list is user_ids where the user's usernames are stored.
Another is user_ratings where the user's ratings are stored.
At the corresponding index of username, user rating is stored.
If there's a new user, the list is appended dynamically at run-time.
Here's the code:
print("Welcome to Movie Predictor")
print("Enter your user id: ")
user_ids=["Vishnu"]
user_ratings=[3.5]
username=input()
print("Signing in...Please Wait!")
if username in user_ids:
user_index=user_ids.index(username)
avg_rating=user_ratings[user_index]
new_user=0
else:
user_ids.append(username)
user_ratings.append(3.5)
avg_rating=3.5
new_user=1
After my first run of the program, I have entered a username which is not there in the list and here are the arrays.
user_ids=["Vishnu","Power"]
user_ratings=["3.5","3.5"]
But here's the problem. The next time i run it again, My last element "Power" is getting replaced but a new item is not appended in the list.
Here's the list after 2nd run:
user_ids=["Vishnu","Ranger"]
user_ratings=["3.5","3.5"]
How to overcome this problem?

Try saving your data to disk after each run, and reading if back before next run:
import os.path
if not os.path.exists("mydatabase.txt"):
# initialize
user_ids=["Vishnu"]
user_ratings=[3.5]
else:
# read previous data from database file
user_ids=[]
user_ratings=[]
with open("mydatabase.txt", "r") as databasefile:
for line in databasefile:
userid, rating_str = line.split()
rating = float(rating_str)
user_ids.append(userid)
user_ratings.append(rating)
print("Welcome to Movie Predictor")
print("Enter your user id: ")
username=input()
print("Signing in...Please Wait!")
if username in user_ids:
user_index=user_ids.index(username)
avg_rating=user_ratings[user_index]
new_user=0
else:
user_ids.append(username)
user_ratings.append(3.5)
avg_rating=3.5
new_user=1
print("Current user ids: %s" % user_ids)
print("Current user ratings: %s" % user_ratings)
# write data to database file
with open("mydatabase.txt", "w") as databasefile:
for userid, rating in zip(user_ids, user_ratings):
databasefile.write("%s %.1f\n" % (userid, rating))

There is no loop here. You just overwrite the values each time.
try that:
A, B = [], []
while True:
A.append(3.5)
b = input('B value')
if b == '':
break
B.append(b)
print(A, B)

It is unclear which parts of the code you run again, but it seems that you are resetting your user ID and ratings lists in every run (3d and 4th line). Therefore "Powers" is not being replaced. Rather than that, a new list with Vishnu is created and your new input is added to it after the run.

You don't have a loop. The values in the list won't be saved between runs of the script
print("Welcome to Movie Predictor")
print("Enter your user id: ")
user_ids=["Vishnu"]
user_ratings=[3.5]
while True:
username=input()
print("Signing in...Please Wait!")
if username in user_ids:
user_index=user_ids.index(username)
avg_rating=user_ratings[user_index]
new_user=0
else:
user_ids.append(username)
user_ratings.append(3.5)
avg_rating=3.5
new_user=1
print("List of users: " + str(user_ids))

you probably want to use dicts and a while loop for input multiple users. This code keep iterating until user enters 'n' on the second input.
print("Welcome to Movie Predictor")
users = dict(Vishnu = 3.5)
a = 'y'
while a == 'y':
username=input("Enter your user id: ")
print("Signing in...Please Wait!")
if username in users:
print("do something if user exits")
else:
val = float(input(f"Enter value for {username}: "))
users[username] = val
print(users)
avg_rating = sum(users.values()) / len(users)
print(f"average rating: {avg_rating}")
a = ''
while a not in ['y','n']:
a = input("continue? (y/n)")
if a == 'n':
break
else:
continue

Related

How can I create an input that will loop and create a new list each time?

in case it isn't already obvious im new to python so if the answers could explain like im 5 years old that would be hugely appreirecated.
I'm basically trying to prove to myself that I can apply some of the basic that I have learnt into making a mini-contact book app. I don't want the data to save after the application has closed or anything like that. Just input your name, phone number and the city you live in. Once multiple names are inputted you can input a specific name to have their information printed back to you.
This is what I have so far:
Name = input("enter name here: ")
Number = input("enter phone number here: ")
City = input("enter city here: ")
User = list((Name, Number, City))
This, worked fine for the job of giving python the data. I made another input that made python print the information back to me just to make sure python was doing what I wanted it to:
print("Thank you! \nWould you like me to read your details back to you?")
bck = input("Y / N")
if bck == "Y":
print(User)
print("Thank you! Goodbye")
else:
print("Goodbye!")
The output of this, is the list that the user creates through the three inputs. Which is great! I'm happy that I have managed to make it function so far;
But I want the 'Name' input to be what names the 'User' list. This way, if I ask the user to input a name, that name will be used to find the list and print it.
How do I assign the input from Name to ALSO be what the currently named "User" list
You will need to create a variable which can store multiple contacts inside of it. Each contact will be a list (or a tuple. Here I have used a tuple, but it doesn't matter much either way).
For this you could use a list of lists, but a dictionary will be more suitable in this case.
What is a dictionary?
A dictionary is just like a list, except that you can give each of the elements a name. This name is called a "key", and it will most commonly be a string. This is perfect for this use case, as we want to be able to store the name of each contact.
Each value within the dictionary can be whatever you want - in this case, it will be storing a list/tuple containing information about a user.
To create a dictionary, you use curly brackets:
empty_dictionary = {}
dictionary_with_stuff_in_it = {
"key1": "value1",
"key2": "value2"
}
To get an item from a dictionary, you index it with square brackets, putting a key inside the square brackets:
print(dictionary_with_stuff_in_it["key1"]) # Prints "value1"
You can also set an item / add a new item to a dictionary like so:
empty_dictionary["a"] = 1
print(empty_dictionary["a"]) # Prints 1
How to use a dictionary here
At the start of the code, you should create an empty dictionary, then as input is received, you should add to the dictionary.
Here is the code I made, in which I have used a while loop to continue receiving input until the user wants to exit:
contacts = {}
msg = "Would you like to: \n - n: Enter a new contact \n - g: Get details for an existing contact \n - e: Exit \nPlease type n, g, or e: \n"
action = input(msg)
while action != "e":
if action == "n": # Enter a new contact
name = input("Enter name here: ")
number = input("Enter phone number here: ")
city = input("Enter city here: ")
contacts[name] = (number, city)
print("Contact saved! \n")
action = input(msg)
elif action == "g": # Get details for an existing contact
name = input("Enter name here: ")
try:
number, city = contacts[name] # Get that contact's information from the dictionary, and store it into the number and city variables
print("Number:", number)
print("City:", city)
print()
except KeyError: # If the contact does not exist, a KeyError will be raised
print("Could not find a contact with that name. \n")
action = input(msg)
else:
action = input("Oops, you did not enter a valid action. Please type n, g, or e: ")
#can be easier to use with a dictionary
#but its just basic
#main list storing all the contacts
Contact=[]
#takes length of contact list,'int' just change input from string to integer
contact_lenght=int(input('enter lenght for contact'))
print("enter contacts:-")
#using for loop to add contacts
for i in range(0,len(contact_lenght)):
#contact no.
print("contact",i+1)
Name=input('enter name:')
Number=input('enter number:')
City=input("enter city:")
#adding contact to contact list using .append(obj)
Contact.append((Name,Number,City))
#we can directly take input from user using input()
bck=input("Thank you! \nWould you like me to read your details back to you?[y/n]:")
#checking if user wants to read back
if bck=='y':
u=input("enter your name:")
#using for loop to read contacts
for i in range(0,len(Contact)):
#if user name is same as contact name then print contact details
if u==Contact[i][0]:
print("your number is",Contact[i][1])
print("your city is",Contact[i][2])
else:
#if user doesnt want to read back then print thank you
print("Good bye")
For this purpose you should use a dictionary.
The key of every entry should be the string 'User[0]' that corresponds to the person's name.
The contents of every entry should be the list with the information of that user.
I'll give you an example:
# first we need to create an empty dictionary
data = {}
# in your code when you want to store information into
# the dictionary you should do like this
user_name = User[0] # this is a string
data[user_name] = User # the list with the information
If you want to access the information of one person you should do like this:
# user_you_want string with user name you want the information
data[user_you_want]
Also you can remove information with this command:
del data[user_you_want_to_delete]
You can get more information on dictionaries here: https://docs.python.org/3/tutorial/datastructures.html#dictionaries
You should start by defining a class to support name, phone and city. Once you've done that, everything else is easy.
class Data:
def __init__(self, name, city, phone):
self.name = name
self.city = city
self.phone = phone
def __eq__(self, other):
if isinstance(other, str):
return self.name == other
if isinstance(name, type(self)):
return self.name == other.name and self.city == other.city and self.phone == other.phone
return False
def __str__(self):
return f'Name={self.name}, City={self.city}, Phone={self.phone}'
DataList = []
while (name := input('Name (return to finish): ')):
city = input('City: ')
phone = input('Phone: ')
DataList.append(Data(name, city, phone))
while (name := input('Enter name to search (return to finish): ')):
try:
print(DataList[DataList.index(name)])
except ValueError:
print('Not found')

Why IF statement become false , If I write a name present in the nested list

When I input "Ali" it jumps to new user statement. Anyone please explain me why?
Data_base = [["Ali","1234","5000"],["Sara","1234","2000"]]
User_name = input("Enter your name")
if User_name in Data_base:
print("User persent")
elif User_name not in Data_base:
print("New User")
New_User_name = input("Your name: ")
Data_base.append(New_User_name)
print(Data_base)
The problem is that your list is made up of two separate lists.
Data_base = [["Ali","1234","5000"],["Sara","1234","2000"]]
So when you check if the input is in the list, Python checks if any of the internal values are equal to the input. i.e.:
input = ["Ali","1234","5000"] or input = ["Sara","1234","2000"]
By grouping it into a list I assume the second and third values belong to the first value. Instead of the list I would suggest using a dictionary:
Data_base = {"Ali" : ["1234","5000"], "Sara" : ["1234","2000"]}
And then, for checking:
if User_name in Data_base:
print("User persent")
else:
# Do whatever

Python infinite while loop issue

I am trying to make a script that asks for user input in Python, it is supposed to error with the response "Please enter first name", and then return the user back to the initial input question prompt.
This isn't working, instead after asking for both the first and last name if no name is given for both I am thrown into an infinite loop of the first error.
# User input for first name
first_name = input('Enter FIRST name here: ')
# User input for last name
last_name = input('Enter LAST name here: ')
def print_name():
# store user input in separate variable
fname = first_name
lname= last_name
while True:
# throw error if user enters no first name
if len(fname) == 0:
# error msg
print('No FIRST name entered...')
# loop back to prompt asking for first name
continue
else:
# if first name given move on to prompting for last name
# break loop
break
# loop into prompting user for last name
while True:
# throw error if user enters no last name
if len(lname) == 0:
print('No LAST name entered...')
# loop back to prompt asking for last name
continue
else:
# if last name given move on to running print command
# break loop
break
return fname, lname
print(f'your name is {fname} {lname}')
print_name()
Please can someone help me understand whats going wrong here? It should only loop back to asking for a first name (or last name) when nothing is given, other wise it should print the users name to console. both names should be given too, if first name is not given then id expect an error in the first while loop, like wise if last name is not given.
Also is there a better way to do this? using 2 while loops seems wrong?
Don't repeat yourself. If you copy and paste a section of code, stop and think. It should either be a function, or a loop.
def wait_for_input(prompt):
data = ""
while data == "":
data = input(prompt).strip()
return data
def print_name(fname, lname):
print(f'your name is {fname} {lname}')
first_name = wait_for_input('Enter FIRST name: ')
last_name = wait_for_input('Enter LAST name: ')
print_name(first_name, last_name)
Also, don't use comments to repeat what the code says.
The issue is with your infinite loops, you can simplify your function like:
def print_name():
first_name = ""
last_name = ""
# User input for first name
while first_name == "":
first_name = input('Enter FIRST name here: ')
# User input for last name
while last_name == "":
last_name = input('Enter LAST name here: ')
print(f'your name is {first_name} {last_name}')
I have the impression you are new at this:
While-loops generally look as follows:
while <condition>
...
<check_condition>
...
This means that in most cases, at every time the loop is executed, the condition is re-calculated and checked again by the while.
In your case, this would become something like:
while (len(fname) == 0)
<show_error_message>
<get fname again>
The case you have written here (while true) also exists and is used regularly, but in very different cases, like in multi-threaded event-based programs:
while true
<get_event>
This means that a part of the program (a so-called thread) is waiting for an event (like a buttonclick) to be catched and then something happens. This, however, is mostly done in multi-threaded applications, which means that the "main" program is doing something, while a subprogram is handling the events, which are coming in.
I am not fully understanding why you need so many loops. Something like this should do:
def print_name():
fname = input('Enter FIRST name here: ')
if len(fname) == 0:
raise Exception('No FIRST name entered...')
lname= input('Enter LAST name here: ')
if len(lname) == 0:
raise Exception('No LAST name entered...')
print(f"your name is {fname} {lname}")
And if all you wanted is to repeat this loop all you need to do is nest your print_name() function in a loop.
EDIT: Now that I seen other answers, I believe #Tomalak answer is better, was not getting what you really wanted.
Try this code:
def print_name():
# store user input in separate variable
first_name = input('Enter FIRST name here: ')
fname = first_name
while True:
fname = first_name
# throw error if user enters no first name
if len(fname) == 0:
# error msg
print('No FIRST name entered...')
first_name = input('Enter FIRST name here: ')
# loop back to prompt asking for first name
continue
else:
# if first name given move on to prompting for last name
# break loop
break
# loop into prompting user for last name
while True:
last_name = input('Enter LAST name here: ')
lname= last_name
# throw error if user enters no last name
if len(lname) == 0:
print('No LAST name entered...')
# loop back to prompt asking for last name
continue
else:
# if last name given move on to running print command
# break loop
break
return fname, lname
print(f'your name is {fname} {lname}')
print_name()

Unable to get value from converted frozen set python 3

I am self-learning Python (no prior programming experience) and I am trying this question:
ask the user to input as many bank account numbers as they’d like, and store them within a list initially. once the user is done entering information, convert the list to a frozenset and print it out.
This is my code:
# create global variables
b_accounts = []
fzb_accounts = frozenset()
# Create add account function
def addAccount(account):
b_accounts.append(account)
print('Account number: {} has been added'.format(account))
return b_accounts
# create covert from a list to a frozenset function
def convertFz():
if b_accounts:
globals()['fzb_accounts'] = frozenset(b_accounts)
return fzb_accounts
else:
print('List of account does not exist!')
# create show account function
def showAccount():
convertFz()
if fzb_accounts:
#print('Here your enique entered accounts:{}'.format(fzb_accounts))
for acc in fzb_accounts:
print(acc)
else:
print('No account!')
# create main function
def main():
done = False
while not done:
ans = input('Please select add/show/quit account: ').lower()
if ans == 'add':
account = input('Enter account number: ')
addAccount(account)
elif ans =='show':
showAccount()
elif ans =='quit':
done = True
print('Bye!')
else:
print('Invalid option')
main()
I want to add the following account numbers:
1234
12345
1234
the output should be:
1234
12345
Thank all, code updated and work as expected.

Python- Allow user to modify item name in list and then show list with new name?

the code for this part of the program is below. I'm trying to allow a user to edit the name of one of the items and then when he enters the show command in the program the updated name will be there. I'm stuck on what function to use to allow the user to edit the name. thanks
def edit(item_list):
number = int(input("Number: "))
list.insert(item)
item = input("Updated name: ")
print(item +"was updated")
def main():
# this is the item list
item_list = ["wooden staff","wizard hat","cloth shoes"]
so if I enter edit as my command and then I write hello for number 1 item I want it to replace wooden staff with hello.
You can modify a list item by simply reassigning that index:
def edit(item_list):
number = int(input("Number: "))
curr_item = item_list[number]
new_item = input("Updated name: ")
item_list[number] = new_item
print("{} was updated to {}".format(curr_item, new_item))
return item_list
item_list = edit(item_list)
I am assuming that your print statement is meant to indicate what was changed. If you just want to re-print what the user entered, you can change it.
You could try:
def edit(item_list):
pos = int(input("Number: "))
new_value = input("Updated name: ")
item_list[pos-1] = new_value
print"%s was updated" % (new_value)
I hope this help you

Categories