def lists(): #Where list is stored
List = ["Movie_Name",[""],"Movie_Stars",[""],"Movie_Budget",[""]]
print ("Your Movies")
amount_in_list = int(input("How many Movies? "))
x = 1
while x <= amount_in_list:
film = input ("Name of film ... ")
stars = input ("Main stars ...")
Budget = input ("Budget ...")
List.append["Movie_Name"](film)
List.append["Movie_Stars"](stars)
List.append["Movie_Budget"](Budget)
lists()
How do i add the film you enter to the list under the subsetting Movie_Name etc?
A better answer than one which answers your question directly would be: You don't. You definitely need a dictionary for this situation (unless your program develops to a point where you'd prefer creating a custom object)
As a simple demonstration:
def getMovies():
movieinfo = {"Movie_Name": [], "Movie_Stars": [], "Movie_Budget": []}
print ("Your Movies")
amount_in_list = int(input("How many Movies? "))
x = 1
while x <= amount_in_list:
film = input ("Name of film ... ")
stars = input ("Main stars ...")
budget = input ("Budget ...")
movieinfo["Movie_Name"].append(film)
movieinfo["Movie_Stars"].append(stars)
movieinfo["Movie_Budget"].append(budget)
x+=1
return movieInfo
Notice that with a dict you simply use the key string to get the corresponding list (initialized at the start of the function) and append the data as desired.
Edited to provide further information for OP's updated request.
If you want to find a movie's info based on just the movie's name given by the user, you could try something like this:
film = 'The Matrix' # Assuming this is the user's input.
Try:
# The index method will throw an exception if
# the movie cannot be found. If that happens,
# the 'except' clause will execute and print
# the relevant statement.
mIdx = movieinfo['Movie_Name'].index(film)
print '{0} stars {1} and had a reported budget of {2}'.format(
film, movieInfo['Movie_Stars'][mIdx], movieInfo['Movie_Budget'][mIdx])
except ValueError:
print '{0} is not in the movie archives. Try another?'.format(film)
Output:
'The Matrix stars Keanu Reeves and had a reported budget of $80 million'
Or:
'The Matrix is not in the movie archives. Try another?'
I would store the movie information in an object. This way your code will be easier to extend, make changes and reuse. you could easily add methods to your movie class to do custom stuff or add more properties without having to change your code to much.
class Movie:
def __init__(self, name='', actors=[], rating=0 budget=0):
self.name=name
self.actors=actors
self.budget=budget
self.rating=rating
def setName(self, newname):
self.name=newname
def setActors(self, newstars):
self.actors=newstars
def setBudget(self, newbudget):
self.budget=newbudget
def setRating(self, newrating):
self.rating=newrating
# example
mymovies=[]
movie1= Movie('Interstellar',['actor1','actor2','actor3'], 5, 100000)
movie2=Movie()
movie2.setName('other movie')
movie2.setActors(['actor1','actor2','actor3'])
movie2.setBudget(10000)
mymovies.append(movie1)
mymovies.append(movie2)
# or append to your list in a loop
Related
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')
I am learning python from scratch and am stuck with classes what I am trying to achieve as follows:
Problem statement: "Collect the data of different students into an array and display."
I am trying to achieve this using classes.
Below is my code which I am trying out. Need help on how to get the values of different question into one single dimensional array.
i.e.
["brittos school", "Ahmedabad", "Francis", "34", " 36", "anthony's school", "Mumbai", "Sam", "45", " 55"]
Where 34 36 are the marks of the subject.
class Mack:
def getmarks(self,numberofsubjects,numberofstudents,sub):
marks=[]
for i in range(numberofstudents):
self.sname=input("Enter your School Name: ")
a.append(marks)
self.city=input("Enter the School City: ")
a.append(marks)
self.name=input("Enter your Name")
a.append(marks)
a=[]
for j in range(numberofsubjects):
a.append(int(input(f"Enter the Marks for {sub[j]} ")))
marks.append(a)
def show(self):
print("My Name is: ",self.name)
print("My City is: ",self.city)
sub=[]
numberofstudents=int(input("Input the number of students"))
numberofsubjects=int(input("Input the number of subjects"))
for i in range(0, numberofsubjects):
ele = input(f"enter the subject name :{i+1}")
sub.append(ele)
ab=Mack()
for i in range(0,numberofstudents):
ab.getmarks(numberofstudents,numberofsubjects,sub)
First of all, you are using the same loop outside the getmarks function and inside it so for example if I input number of students as 2. It will run 4 times which is incorrect. Loop over number of students once. Secondly a is not defined anywhere so if you want the list of all the input I'd suggest creating a as a member variable of this class.
I think this code below is what you need
class Mack:
def getmarks(self,numberofsubjects,numberofstudents,sub):
marks=[]
a = []
for i in range(numberofstudents):
self.sname=input("Enter your School Name: ")
a.append(self.sname)
self.city=input("Enter the School City: ")
a.append(self.city)
self.name=input("Enter your Name")
a.append(self.name)
for j in range(numberofsubjects):
a.append(int(input(f"Enter the Marks for {sub[j]} ")))
marks.append(a)
return a
def show(self):
print("My Name is: ",self.name)
print("My City is: ",self.city)
sub=[]
numberofstudents=int(input("Input the number of students"))
numberofsubjects=int(input("Input the number of subjects"))
for i in range(0, numberofsubjects):
ele = input(f"enter the subject name :{i+1}")
sub.append(ele)
ab=Mack()
result = ab.getmarks(numberofstudents,numberofsubjects,sub)
print(result)
Although this is a very bad approach to do what you are trying to do. What I would suggest is to create a Student Class like.
class Student:
def __init__(self, name, sname, cname, subjects, marks):
self.name = name
self.sname = sname
self.cname = cname
self.subjects = subjects
self.marks = marks
where subjects and marks would lists of subjects and marks. You can also create a dictionary if you want where subject would be key and marks would be value. After that, you can simple create a list of this class and take input for every element of that Student list.
I’m finding the Python syntax very confusing, mainly concerning variables. I’m trying to learn it using the Microsoft EDX course but I’m struggling when trying to check if a string from an input is in the variable.
Example 1: Check if a flavor is on the list
# menu variable with 3 flavors
def menu (flavor1, flavor2, flavor3):
flavors = 'cocoa, chocolate, vanilla'
return menu
# request data from the user flavorName = input('What flavor do your want? ')
data = input("What flavor do you want? ")
#print the result
print ("It is", data in menu, "that the flavor is available")
Example 2: Print a message indicating name and price of a car
def car (name, price):
name = input(“Name of the car: “)
price = input (“Price of the car: “)
return (name, price)
print (name, “’s price is”, price)
Also, I would like to know what would be the disadvantage of doing something like this for the example 2:
name = input("name of the car: ")
price = input ("price of the car: ")
print (name,"is", price,"dollars")
Could someone please clarify this to me? Thank you very much!
i didnt understand what your trying to do in first example.
But i can partially understand what your trying to do in second example,
def car ():
name = input("Name of the car: ")
price = input ("Price of the car: ")
return name, price
name,price = car()
print ("{}\'s price is {}".format(name,price))
the above code is the one of the way to solve your problem,
python can return multiple variable
use format function in print statement for clean display.
You dont need function parameters for car. since your taking input from in car function and returning it to the main.
Hope it helps you understand.
Example 1
# menu variable with 3 flavors
def menu():
flavors = 'cocoa, chocolate, vanilla'
return flavors #return flavors instead of menu
# request data from the user flavorName = input('What flavor do your want? ')
data = input("What flavor do you want? ")
# print the result
print ("It is", data in menu(), "that the flavor is available") #menu is a function so invoke with menu () instead of menu
Example 2:
def car(): #no input required since you are getting the input below
name = input('Name of the car: ')
price = input('Price of the car: ')
return (name, price)
name, price = car() #call the function to return the values for name and price
print (name, "’s price is", price)
The below approach works and is faster as compared to calling the function although adding small stuff to form functions allows the program to be modularized, making it easier to debug and reprogram later as well as better understanding for a new programmer working on the piece of code.
name = input("name of the car: ")
price = input("price of the car: ")
print (name, "is", price, "dollars")
Just found how to print the result in the way the exercise required. I had difficulty explaining, but here it is an example showing:
def car(name,price):
name_entry = input("Name car: ")
price_entry = input("Price car: ")
return (name_entry,price_entry)
This is the way to print the input previously obtained
print (car(name_entry,price_entry))
Thank you very much for all the explanations!
I want to update a list to include new items added by a user. There are a few conditions such as the code must be 7 digits long. If the code already exists, the system will notify the user. If the user tries to add another copy of 'up' with a different code, the system will not allow it. It will make them try again as the code must be the same. Eventually I will include a video number, so if there are two copies of 'up' they will have two different video numbers but the same video code.
Can someone show me why the following code is not working for me?
all_movies = []
class Movie(object):
movie_list = []
def __init__(self, code, title, director):
self.code = code
self.title = title
self.director = director
Movie.movie_list.append(self)
#staticmethod
def add_movie():
mv_code = input("Code of movie: ")
movie_code = int(mv_code)
movie_title = input("Name of movie: ")
movie_director = input("Director: ")
if len(mv_code) == 7:
all_movies.append(Movie(movie_code, movie_title, movie_director))
print("movie added to database")
else:
print("the code must be 7 digits long, add movie again.")
def check_validity(movie_code, all_movies):
if movie_code in all_movies:
return True
else:
return False
if check_validity(movie_code, all_movies):
all_movies[all_movies] += Movie
print()
print("updated")
else:
all_movies[movie_code] = [movie_code, movie_title, movie_director]
def main():
movie1 = Movie(1122334, 'Up', 'Director')
movie2 = Movie(1231235, 'Taxi Driver', 'Film-maker')
This is the error message that I am receiving:
all_movies[movie_code] = [movie_code, movie_title, movie_director]
IndexError: list assignment index out of range
First of all this structure is not suitable for your desires.
About the error you got, I should say that you have to define you all movies as a dictionary not a list (because of the that you want to use for each movie).
try this:
all_movies = {}
in you add_movie method:
#staticmethod
def add_movie():
mv_code = input("Code of movie: ")
movie_code = int(mv_code)
movie_title = input("Name of movie: ")
movie_director = input("Director: ")
if len(mv_code) == 7:
if movie_code in all_movies.keys():
print("the movie already exists")
# what do you want to happen here ?
else:
all_movies[movie_code] = (movie_code, movie_title, movie_director)
print("movie added to database")
else:
print("the code must be 7 digits long, add movie again.")
This will add a movie to the all_movies and you don't need the rest your code, and i didn't understand the usage of init and movie_list.
Try this, then tell me what happens if the code already exists in the movies, I will update my answer for you.
UPDATE:
According to your desires in comment the method will updated to something like this:
#staticmethod
def add_movie():
mv_code = input("Code of movie: ")
movie_code = int(mv_code)
movie_title = input("Name of movie: ")
movie_director = input("Director: ")
if len(mv_code) == 7:
if movie_code in all_movies.keys():
print("the movie is already exists, adding it with another video number")
# all_movies[movie_code][-1] is the last video with an existing key
# all_movies[movie_code][-1][-1] last video number generated
new_video_number = all_movies[movie_code][-1][-1] + 1
all_movies[movie_code].append([movie_title, movie_director, new_video_number]) # adding it with new video number
print("movie added to database with new video number")
else:
all_movies[movie_code] = []
all_movies[movie_code].append([movie_title, movie_director, 1]) # 1 is the first movie added(video number)
print("movie added to database")
else:
print("the code must be 7 digits long, add movie again.")
This will returns all_movies like this:
{
'1231235':[
['Taxi Driver', 'Film-maker', 1]
]
'1122334':[
['Up', 'Director',1],
['Up', 'Director',2],
['Up', 'Director',3],
]
'1122333':[
['Another movie', 'Another Director',1],
['Another movie', 'Another Director',2],
]
}
The last element of inner list are the video_numbers that generated automatically by system.
I'm well into development of a text-based RPG. Right now, my store system is very long and convoluted, in that there is a lot repeated code. The idea I currently have going on is that I have a list of items available to sell, and based off raw input from the user, it will related those items to if / else statements, assuming I have the proper item and player classes made, i.e.:
store = ['sword', 'bow', 'health potion']
while True:
inp = raw_input("Type the name of the item you want to buy: ")
lst = [x for x in store if x.startswith(inp)
if len(lst) == 0:
print "No such item."
continue
elif len(lst) == 1:
item = lst[0]
break
else:
print "Which of the following items did you mean?: {0}".format(lst)
continue
if item == 'sword':
user.inventory['Weapons'].append(sword.name)
user.strength += sword.strength
user.inventory['Gold'] -= sword.cost
elif item == 'bow'
#Buy item
#Rest of items follow this if statement based off the result of item.
As you can see, I'm using the result of the 'item' variable to determine a line of if / elif / else statements for each item, and what happens if that item name is equal to the variable 'item'.
Instead, I want the player to be able to type in the item name, and then for that raw input to be translated to class names. In other words, if I typed in 'sword', I want Python to pull the information from the 'sword' object class, and apply those values to the player. For example, a weapon's damage is transferred to the player's skill. If a sword does 5 strength damage, the player's strength will be raised by 5. How can I get python to add the values of one class to another without a shit ton of if / else statements?
If you have all your game item classes names in a single place (for example, a module), you can use Python's getattr to retrieve the class itself having its string.
SO, for example, let's suppose you have a items.py file that does something like:
from weapons import Sword, Bow, Axe, MachinneGun
from medicine import HealthPotion, MaxHealthPotion, Poison, Antidote
(or just define those classes right there in the items module)
You can there proceed to do:
import items
...
inp = raw_input("Type the name of the item you want to buy: ")
...
item_class = getattr(items, inp)
user.inventory.append(item_class.__name__)
if hasattr(item_class, strength):
user.strength += item_class.strength
and so on.
You can also simply create a dictionary:
from items import Sword, Bow, HealthPotion
store = {"sword: Sword, "bow": Bow, "health potion": HealthPotion}
...
item_class = store[inp]
...
Note that the text is quoted- it is text data, and the unquoted values are the actual Python classes- which have all the attributes and such.
Thanks to jsbueno, my code now works. Here is my official fix using his dictionary method:
from objects import ironsword
class player(object):
def __init__(self, strength):
self.strength = strength
self.inventory = []
user = player(10)
store = {'iron longsword': ironsword}
while True:
inp = raw_input("Type the name of the item you want to buy: ")
lst = [x for x in store if x.startswith(inp)]
if len(lst) == 0:
print "No such item."
continue
elif len(lst) == 1:
item = lst[0]
break
else:
print "Which of the following items did you mean?: {0}".format(lst)
continue
item_class = store[item]
user.inventory.append(item_class.name)
user.strength += item_class.strength
print user.inventory
print user.strength
Typing even 'iron' into the raw input will pull the correct item. When printing user.inventory, it returns the correct item name, e.g. ['iron longsword'], and when printing the user strength variable, it prints the repsective amount.