My append command won't work (Python) - python

I am a new programmer and I am teaching myself using Sams Teach Yourself Python in 24 Hours, and one of the excersises told me to rewrite a piece of code that allows the clerk to work out orders at a restraunt and it told me change it so to include the price, so I did, but I want to use the user's input of the price and to put it into a list to sum it up and print out the total. However, it doesn't work. What should I do?
Here is the code:
breakfast_special = "Texas Omelet"
breakfast_notes = "Contains brisket, horseradish cheddar"
lunch_special = "Greek patty melt"
lunch_notes = "Like the regular onem but with tzatziki sauce"
dinner_special = "Buffalo Steak"
dinner_notes = "Top loin with hot sauce and blue cheese, NOT BUFFALO MEAT"
while True:
meal_time = raw_input("Which mealtime do you want? [breakfast, lunch, dinner, q to quit]")
if meal_time == "q":
break
price = raw_input("Price: $")
price.append(price)
total_price = sum.price
if meal_time == "breakfast":
print "Specials for {} :".format(meal_time)
print breakfast_special
print breakfast_notes
elif meal_time == "lunch":
print "Specials for {} :".format(meal_time)
print lunch_special
print lunch_notes
elif meal_time == "dinner":
print "Specials for {} :".format(meal_time)
print dinner_special
print dinner_notes
else:
print "Sorry, but {} isn't a valid choice".format(meal_time)
print "Goodbye!"
print "Price: ${}".format(total_price)

raw_input() takes a string input.
So when you try to do price = raw_input() , the user input is saved as string type to your variable 'price'. To convert that value to int/float, you can do int(price) or float(price)
Note: You have to make sure the user_input is actually a number. If the variable 'price' has characters, converting it to int/float will result in a ValueError
To achieve what you're trying to do, let's do the following.
first: allocate a new list to hold all the prices you are taking as input. lets call it price_list.
price_list = []
now let's take floating point input form the user for price and append it to the price_list
price = float(raw_input('Price for the item :'))
price_list.append(price)
now that we have a list of prices, lets get the sum of all the prices.
sum(price_list)
That should give you the total sum.
Hope it helps!

Related

Reading a random line from a word doc and printing it

So I have a small project with python.
A random song name and artist are chosen.
The artist and the first letter of each word in the song title are displayed.
The user has two chances to guess the name of the song.
If the user guesses the answer correctly the first time, they score 3 points. If the user guesses
the answer correctly the second time they score 1 point. The game repeats.
The game ends when a player guesses the song name incorrectly the second time.
So far I've created a text document and put a few lines of song titles.
In my code I have used the following:
random_lines = random.choice(open("songs.txt").readlines())
This randomly picks a line in the code and does nothing with it.
I am asking where I go from here. I need to display the first letters of each word on the line. I then need a counter or some sort to add chances. I also need to write something that will check to see if they have it correct and add to a score counter.
OK, now just continue with your plan, it's good. Now you have to get the first letter from each word in line. You can do that with:
res = []
for i in line.split():
res.append(i[0])
There you are, you have the first letter of every word in the list res. Now you need to check if the user entered the title correctly. Maybe the best idea would be to keep everything lower-cased (in your file and in the user input) for easier checking. Now you just have to transform the user input to lower-case. You can do it with:
user_entry = input('Song title:')
if user_entry.lower() == line.lower():
score += 3
else:
user_entry_2 = input('Song title:')
if user_entry_2.lower() == line.lower():
score += 1
else:
print('Game over.')
sys.exit()
You should make this into a function ad call it in a loop until user misses. The function could return the current score which you could print out (in that case you should remove sys.exit() call)
I hope this is clear enough. If not, write the question in the comments :)
Assuming your random choice string contains the data in the format {songname} - {artist}
Then you first need to get the song name and the artist as a separate strings.
Print the first letters and ask for input.
After which you need to compare the strings and do some logic with the points.
points = 0;
while(1):
random_line = 'Song - artist' #change this with your random string
song, artist = random_line.split('-')
print("{0} - {1}".format(song.strip()[:2], artist.strip()[:2]))
for i in range(0,3):
if (i == 2):
print('You died with {} points'.format(points))
exit(0)
elif(random_line.lower() == input('Gues the song: ').lower()):
points += 2 - i
print('correct guess. points: ' + str(points))
break
else:
print('Try again')

Repeating for loop within a function Python 3

I have been working on this problem for an Intro to Programming with Python class for days now. The goal is to create a program that generates random movie titles from a list of user-inputed words. The output should look something like this:
Please enter a list of words: ["Space", "Show", "Adventure", "Story",
"Love", "Wild", "Life"]
Please enter a number of movies you'd like to generate: 3
Output:
Welcome to Randoplex! Currently playing movies are:
Adventure Life Space
Show Love Story
Wild Space Life
I have been able to generate random titles, but cannot find anyway to generate different titles based on the user-inputed number. This is the closest I have gotten:
import random
def random_movies(word_list = eval(input("Please enter a list of words:"))):
for word in word_list:
titles = ' '.join(random.choice(word_list) for i in range(3))
return titles
def repeat():
titles = random_movies()
movie_num = eval(input("Please enter the number of movies you'd like to generate:"))
for i in range(movie_num):
random_movies()
print(titles)
titles1 = repeat()
print("Welcome to Randoplex! Currently playing movies are:")
print()
print(titles1)
This allows me to print the same randomized title for the value movie_num that the user enters. But, I just cannot figure out how to create multiple different randomized movie titles. I have tried using the range() function in many different ways, and have looked all over the internet for advice. I truly don't know what else to try at this point, any help would be greatly appreciated. It is important to mention that my class is very elementary, we haven't been introduced to "while" loops yet and I don't think I am allowed to use them because of that. Thank you in advance.
Does this do what you're looking for?
import random
def random_movies(word_list):
for word in word_list:
titles = ' '.join(random.choice(word_list.split()) for i in range(3))
return titles
word_list = input("Please enter a list of words:")
movie_num = int(input("Please enter the number of movies you'd like to generate:"))
print("Welcome to Randoplex! Currently playing movies are:")
for i in range(movie_num):
print(random_movies(word_list))
Your functions are working correctly however in your for loop where you print the movie titles you forgot to reassign your variable to the newly generated movie title. Your different titles are generated but you print only the first one.
import random
def random_movie(word_list = eval(input("Please enter a list of words:"))):
for word in word_list:
title = ' '.join(random.choice(word_list) for i in range(3))
return title
def repeat():
movie_num = eval(input("Please enter the number of movies you'd like to generate:"))
for i in range(movie_num):
title = random_movie()
print(title)
print("Welcome to Randoplex! Currently playing movies are: ")
print()
repeat()
another way to achieve similar result.
import itertools
import random
noofmovies = 3
movies = ["Space", "Show", "Adventure", "Story", "Love", "Wild", "Life"]
newmovies = []
def random_movie(movies):
for r in range(2,len(movies)):
for elem in itertools.combinations(movies, r):
newmovies.append(" ".join(elem))
def repeat():
random.shuffle(newmovies)
for elem in newmovies[0:noofmovies]:
print (elem)
print("Welcome to Randoplex! Currently playing movies are: ")
random_movie(movies)
repeat()
output:
Show Adventure Story Wild Life
Story Wild Life
Show Adventure Story Love Wild Life
In case you want only 3 movie names to be joined always, remove for r in range(2,len(movies)): loop and hardcode r to 3

Searching for 2 word key in dictionary

im new in python and world of programming. get to the point. when i run this code and put input let say chicken, it will reply as two leg animal. but i cant get reply for two words things that has space in between like space monkey(althought it appear in my dictionary) so how do i solve it???
my dictionary: example.py
dictionary2 = {
"chicken":"chicken two leg animal",
"fish":"fish is animal that live under water",
"cow":"cow is big vegetarian animal",
"space monkey":"monkey live in space",
my code: test.py
from example import *
print "how can i help you?"
print
user_input = raw_input()
print
print "You asked: " + user_input + "."
response = "I will get back to you. "
input_ls = user_input.split(" ")
processor = {
"dictionary2":False,
"dictionary_lookup":[]
}
for w in input_ls:
if w in dictionary2:
processor["dictionary2"] = True
processor["dictionary_lookup"].append(w)
if processor["dictionary2"] is True:
dictionary_lookup = processor["dictionary_lookup"][0]
translation = dictionary2[dictionary_lookup]
response = "what you were looking for is: " + translation
print
print "Response: " + response
You need to explain your purpose to get better help.
In your case you seem to be only interested in looking up words and then this code should be sufficient. Notice the .format() syntax which cleans up your code drastically.
updated code : now a list is created with the combinations found in the input. This however might need modification to fit needs.
dictionary2 = {
"chicken":"chicken two leg animal",
"fish":"fish is animal that live under water",
"cow":"cow is big vegetarian animal",
"space monkey":"monkey live in space"}
print("how can i help you?")
user_input = raw_input()
print("You asked: {}.".format(user_input))
split = user_input.split(" ")
combos = [' '.join(split[x:y]) for x in range(len(split)) for y in range(len(split)+1) if ' '.join(split[x:y]) != ""]
# Create an empty dictionary to insert found item
response = {}
for item in combos:
if dictionary2.get(item):
response[item] = "what you were looking for is: {}.".format(dictionary2[item])
# If dictionary is empty do this
if not response:
print("Response: I will get back to you!")
# If not, loop over keys(k) and values(v) and print them with an index(ind)
for ind, (k,v) in enumerate(response.iteritems()):
print("Response {}: {} ({})".format(ind+1, v, k))
I've redone my answer even though an answer is chosen as this was an interesting problem and I was close to a fair solution in given time.
This answers can take human like questions instead of just words.
Although, for true machine learning nltk is a better option. For start we can use something like below.
It used builtin library difflib to match question against dictionary keys and decided which has higher probability.
Warning: Exception handling is not implemented. It will just pick up max probable match.
We then use re to remove words in key from answer and put everything back together. This provides a more natural answer than just displaying key values.
import re
from difflib import SequenceMatcher
def similarity(a, b):
return SequenceMatcher(None, a, b).ratio()
dictionary2 = {
"chicken":"chicken two leg animal",
"fish":"fish is animal that live under water",
"cow":"cow is big vegetarian animal",
"space monkey":"monkey live in space",}
user_input = raw_input("User Question:")
#Check which key has greater probability match
similarity_list = []
for i in dictionary2.keys():
similarity_list.append((i,similarity(user_input,i)))
key_match = max(similarity_list, key=lambda x:x[1])
uin = ('|'.join(key_match[0].split()))
p = re.compile(r"\b(" + uin + ")\\W", re.I)
ans = p.sub('', dictionary2[key_match[0]])
print "answer: {} {}".format(key_match[0], ans)
Result
Python 2.7.9 (default, Dec 10 2014, 12:24:55) [MSC v.1500 32 bit (Intel)] on win32
Type "copyright", "credits" or "license()" for more information.
>>> ================================ RESTART ================================
>>>
User Question:what is a chicken?
answer: chicken two leg animal
>>> ================================ RESTART ================================
>>>
User Question:Where does space monkey live?
answer: space monkey live in space
>>> ================================ RESTART ================================
>>>
User Question:Where does fish live?
answer: fish is animal that live under water
>>> ================================ RESTART ================================
>>>
User Question:what is a cow?
answer: cow is big vegetarian animal
>>>
The problem with your code is when you use for w in input_ls and what you passed was "space monkey", it looks for space, then it looks for monkey. If you want the desired results with this specific script, it'd look like this
print "how can i help you?"
print
user_input = raw_input()
print
print "You asked: " + user_input + "."
response = "I will get back to you. "
input_ls = user_input
processor = {
"dictionary2":False,
"dictionary_lookup":[]
}
if input_ls in dictionary2:
processor["dictionary2"] = True
processor["dictionary_lookup"].append(input_ls)
if processor["dictionary2"] is True:
dictionary_lookup = processor["dictionary_lookup"][0]
translation = dictionary2[dictionary_lookup]
response = "what you were looking for is: " + translation
print
print "Response: " + response
note I also changed input_ls = user_input.split(" ") to input_ls = user_input because that turns your string into an array of individual words, which wouldn't return what you're looking for if you're trying to look up specific phrases instead of individual words, and made this important change here
if input_ls in dictionary2:
processor["dictionary2"] = True
processor["dictionary_lookup"].append(input_ls)
--edit--
I had to clock out for work, but now that I'm home I can address this better. When trying to accomplish this goal using a dictionary, here's how I would've done it.
dictionary2 = {
"red":"the color red",
"blue":"fish is animal that live under water",
"red and blue":"these colors make blue",
"blue and yellow":"these colors make green"
}
user_input = raw_input('what would you like?\t')
user_input = user_input.split(' ')
print
for word in user_input:
for key,val in dictionary2.iteritems():
if word in key:
print '%s: %s' % (key,val)
When trying to iterate through a dictionary, you need to use either:
dictionary2.iteritems() for both key and val
dictionary2.iterkeys() for your keys
dictionary2.itervalues() for your values

How to check if a set of results exactly match any list of strings in a list in python

as the title says I am trying to get a exact match from any list of strings in a lists. I'm finding it hard to explain so ill show code now.
List = [['BOB','27','male'],['SUE','32','female'],['TOM','28','unsure']]
This would be an example of the lists layout, then i want to send information through from a web scrape to see if anything matches any of the item[0]+item[1]+item[2] in the list, the problem i am having is that the web scrape is using a for argument:-
HTML = requests.get(url).content
match = re.compile('Name"(.+?)".+?Age"(.+?)".+?Sex"(.+?)"').findall(HTML)
for name,age,sex in match:
Then my next part also using a for argument:-
for item in List:
if item[0] == name and item[1] == age and item[2] == sex:
pass
else:
print 'Name = '+name
print 'Age = '+age
print 'Sex = '+sex
But obviously if the result matches any of the single sets of lists it cannot match the other 2 so it will not pass, is there a way i can achieve it to check to see if it matches anything set of 3 results in the list name,age,and sex being item[0],item[1],item[2] exactly? I have also tried:
if all(item[0] == name and item[1] == age and item[2] == sex for item in List):
pass
This does not work, I'm assuming its because its not a direct match in all the lists of list and if i change all to any i get results coming back that skip if any of the strings match, ie age is 27,32 or 28. I know my regex is poor form and not the ideal way to parse HTML but its all I can use confidently at the moment sorry. Full code below for easier reading.
List = [['BOB','27','male'],['SUE','32','female'],['TOM','28','unsure']]
HTML = requests.get(url).content
match = re.compile('Name"(.+?)".+?Age"(.+?)".+?Sex"(.+?)"').findall(HTML)
for name,age,sex in match:
for item in List:
if item[0] == name and item[1] == age and item[2] == sex:
pass
else:
print 'Name = '+name
print 'Age = '+age
print 'Sex = '+sex
Any help would be greatly appreciated, I am still a beginner and have not used forum's much so I will apologise in advance if it's not grammatically correct or I have asked in the wrong way.
re.findall returns tuples, so you can simplify the comparison if the items in your list match the return type:
import re
# Changed sub-lists to tuples.
items = [('BOB','27','male'),('SUE','32','female'),('TOM','28','unsure')]
html = '''\
Name"BOB" Age"27" Sex"male"
Name"PAT" Age"19" Sex"unsure"
Name"SUE" Age"31" Sex"female"
Name"TOM" Age"28" Sex"unsure"
'''
for item in re.findall('Name"(.+?)".+?Age"(.+?)".+?Sex"(.+?)"', html):
if item in items:
name,age,sex = item
print 'Name =', name
print 'Age =', age
print 'Sex =', sex
print
Output:
Name = BOB
Age = 27
Sex = male
Name = TOM
Age = 28
Sex = unsure
You can also use item not in items if you want the ones that don't match.
First change the name of the list. List is not a reserved keyword,but it's not a good practice to use abstract names. My suggestion is to make the data a list. If I understood right your question, it's a matter of getting everything differently. So:
for sublist in my_list:
if (sublist[0] != weblist[0]) and (sublist[1] != weblist[1]) and (sublist[2] != weblist[2]):
print("List is different")

Avoid printing identical output

I am making a troubleshooting program, which will ask the user for an input, search through some lists to find the problem and give them a solution.
f=open('problem.txt')
lines=f.readlines()
problem1 = ["cracked", "phone", "screen", "dropped"]
problem2 = ["charging", "port", "phone"]
problem3 = ["slow", "phone", "freeze"]
problem_input = input ("What is your problem? ")
list_split = (problem_input.split( ))
for i in problem1:
if i in list_split:
print (lines[0])
for i in problem2:
if i in list_split:
print (lines[1])
But if i input, "my phone is cracked", the output will be printed twice. How do I only print this once?
You're cycling through a list of problem cases and your input matches twice. The matches are "phone" and "cracked". To prevent that, stop at the first match like that:
for i in problem1:
if i in list_split:
print (lines[0])
break
The break keyword will quit the cycle.
You are looping through your "problems" lists and getting multiple matches for your condition.
You could return your matched problem by making this into a function:
f=open('problem.txt')
lines=f.readlines()
problem1 = ["cracked", "screen", "dropped"]
problem2 = ["charging", "port"]
problem3 = ["slow", "freeze"]
problems = [problem1, problem2, problem3]
def troubleshoot():
problem_input = input("What is your problem? ")
list_split = (problem_input.split())
for idx, problem in enumerate(problems, 1):
if any(i in problem for i in list_split):
return "problem{}".format(idx)
# or return lines[0]
It would run as the following:
>>> troubleshoot()
What is your problem? my phone is slow and freezing up
'problem3'
>>> troubleshoot()
What is your problem? my phone is not charging
'problem2'
>>>
>>> troubleshoot()
What is your problem? my phone dropped and the screen is cracked
'problem1'
Alternatively, if there isn't a reason for having "phone" in each of the problem lists, you might be better off using a dict here:
problems = {'cracked':1, 'screen':1, 'dropped':1,
'charging':2, 'port':2,
'slow':3, 'freeze':3}
user_problems = {problems[i] for i in problem_input.split()}
Note: I removed "phone" from both of these because it matches for every list

Categories