Trying to Build a Sandwich Making Simulator - python

First time using Stackoverflow.
I'm a total noob with Python so I need a little help. I'm trying to make a choice based text adventure game and in the middle of it is going to be a sandwich making simulator (don't ask how my mind works) and I need a little help.
def sandwich():
print("You see bread, meat, cheese and mayo.")
while True:
try:
print(" 1. Bread \n 2. Meat \n 3. Cheese \n 4. Mayo")
print ("Select the ingredients based on number. Which would you like to grab?")
response = set(int(input("Select ingredients: ").strip))
except ValueError:
print("Please enter an integer!")
I only have four choices to keep it simple so I can build from there. Basically I want to make the program check for user integer input and depending on that input give feedback on the sandwich that's created.
for example:
if response == "1234":
print("Wow that's an amazing sandwich")
But I want the program to be able to be smart enough to do this regardless of the order that is given. So if someone puts in "4321" instead of "1234", it can give the same result. Currently I'm using set, int, and strip on line 7 (not sure if that's good or not) so that there can't be duplicates, and if spaces is added it should strip it away. It should also give an error if an integer is not entered.
I'm thinking of using for loops with in, but I have no idea where to begin or if that's even the right path.
Any points in the right direction would be appreciated!

Is better to put the list of ingredients in a dictionary, so you can easily add or substract ingredients, and you have a relation between the number and the ingredient.
Strip is a function call, so it has to be written .strip()
Is better to not add the response directly to the set of ingredients, because you should validate it first.
You need a way to stop adding ingredients. If the user does not writes an integer, you could ask if he wants to stop adding ingredients.
sandwichIngredients = {1: "Bread", 2: "Meat", 3: "Cheese", 4: "Mayo"}
def sandwich():
chosenIngredients=set()
print("You see "+ ", ".join(sandwichIngredients.values())+".")
while True:
try:
print(*[f"{number}. {ingredient}" for number, ingredient in sandwichIngredients.items()], sep="\n")
print ("Select the ingredients based on number. Which would you like to grab?")
response=int(input("Select ingredients: ").strip()) #strip is a function call, so it has to be written .strip()
if response in chosenIngredients:
print("You already have that ingredient.")
continue
elif response not in sandwichIngredients:
print("That is not an ingredient.")
continue
else:
chosenIngredients.add(response)
if len(chosenIngredients)==len(sandwichIngredients):
print("Wow that's an amazing sandwich.")
break
except ValueError:
if input("That is not a number. Do you want to finish the sandwich? (y/n)").lower()=="y":
break
print("Please enter an integer!")
#now you can print the ingredient names by using the dictionary
print("your sandwich has the following ingredients: " + ", ".join([sandwichIngredients[i] for i in chosenIngredients]))
sandwich()

Related

how to detect the specific word to make it as a right answer?

I am making a program like a family feud where the user needs to guess a right answer according to the topic he chose. How can I get the specific word if he inputted only 1 word?
from nltk.corpus.reader import WordListCorpusReader
import os
again = True
print("GUESSING GAME")
print(reader.words('D:/VB/topic1.txt'))
while again:
num = int(input("PICK A NUMBER FOR THE TOPIC [1-3]: "))
if num == 1:
print("1. Name something people are afraid of. ")
print("======================================")
print("You need to guess 10 right answers in order to win. ")
reader = WordListCorpusReader('D:/VB/topic1.txt', ['topic1.txt'])
for i in range(0,10):
element = (input(str(i + 1) + ". "))
topic1.txt file:
Spiders
Heights
Other people
Dying
The dark
Ghosts
Snakes
The IRS
Being alone
Their boss or getting fired
For example, the user guessed: Dark. In my file, the answer is the "The Dark". How can I declare it as a right answer without including the "The". Another example would be "Their boss", I want to make the guess right if the user only input "Boss"

Why won't my branched conditions execute? And, how do I get the program to repeat itself?

I'm trying to do an assignment for MIT OCW (it's a self-development class, not a for-credit class, so don't worry, I'm not cheating on anything).
This is what I have so far:
#This program calculates how many months it will take to buy my dream home
print("Welcome to the dream home calculator.")
total_cost=input("To start, please write down the cost of your dream home. Use only numbers, and do not use commas.\n")
try:
float(total_cost)
if total_cost>1000000:
print("That's quite a pricey home!")
elif total_cost>=200000:
print("That's a decently-priced home.")
else:
print("Are you sure you entered an actual home value in the Bay area?")
except:
print("Please enter only a number, with no commas.")
total_cost
But, no matter what number I input, I don't get any of the text such as "That's a decently-priced home" and the program goes straight to "Please enter only a number, with no commas."
Also, if the user inputs something other than a number, I want the program to ask for the total cost of the home again. How do I get it to do that?
Thank you!
EDIT: NEVERMIND! I figured it out! float(total_cost) didn't actually turn total_cost into a floating point. To solve that, I did: total_cost=float(total_cost)
Still, what about the second question?
About the second question, you can try using a while loop.
# This program calculates how many months it will take to buy my dream home
print("Welcome to the dream home calculator.")
input_flag = False
while input_flag == False:
total_cost = input(
"To start, please write down the cost of your dream home. Use only numbers, and do not use commas.\n")
# if the total_cost is a number string, the input_flag will become True
# Then it will escape the loop
input_flag = total_cost.isnumeric()
try:
total_cost = float(total_cost)
if total_cost > 1000000:
print("That's quite a pricey home!")
elif total_cost >= 200000:
print("That's a decently-priced home.")
else:
print("Are you sure you entered an actual home value in the Bay area?")
except:
print("Please enter only a number, with no commas.")
total_cost
You could do it like that:
def main():
"""Calculate how many months it will take to buy my dream home."""
print('Welcome to the dream home calculator.\n')
# Ask for input
print(
'To start, please write down the cost of your dream home. '
'Use only numbers, and do not use commas.'
)
while True:
total_cost_str = input('>>')
try:
total_cost = float(total_cost_str)
except ValueError:
print("That's the wrong input, try again!")
continue
else:
break
# Evaluate result:
if total_cost > 1_000_000:
print("That's quite a pricey home!")
elif total_cost >= 200_000:
print("That's a decently-priced home.")
else:
print("Are you sure you entered an actual home value in the Bay area?")
if __name__ == '__main__':
main()
Notice that I moved the if-clauses out of the try ... except-block. As you're actually just trying to convert the input to float, it's good practice to keep the exception-handling as narrow as possible.
Now you can be sure that you have a valid floating-point number after the try ... except-block, which makes debugging a lot easier.
Also notice that your exception-clause was too broad. If you're converting to float, the only exception you're concerned with is ValueError, as that one is raised if float() is unable to convert your input.
If you just put except, you might (in some cases that are a little more complex) actually catch a different exception that should not go unnoticed.

Creating Decision Tree for Simple Game

I am currently a new student learning python. This is my first real experience doing much computer coding. For my project I must create a fill in the blank quiz with three different levels of difficulty. Once the user chooses a difficulty the game should print a different paragraph based on the difficulty. Each section of the game works fine but I am having trouble creating the "difficulty chooser." No matter the difficulty I choose, the game rolls through the easy, medium, and the hard level in order and then crashes.
Below I have included the introductory text and the difficulty chooser. I would love some help. I am sure there are really obvious things I don't see. Thank you!
def introduction():
print '''Welcome to Kevin's European Geography Quizzes.
Test your knowledge of European geography. \n'''
difficulty = raw_input('''Do you want to play an easy, medium, or hard game?
Please type the number 1 for easy, 2 for medium, or 3 for hard.\n''' )
game_chooser(difficulty)
def game_chooser(difficulty):
cursor = 0
difficulty_choice = [easy_game(), medium_game(), hard_game()]
#each element of the above list links to a procedure and starts one of the
#mini-games.
while cursor < len(difficulty_choice):
if difficulty != cursor:
cursor += 1
else:
difficulty_choice[cursor]
break
You can do with if else if you only want to print something but if you have separate code block for each level then define a function for each level and use this pattern :
You can define the function blocks and call them basis on user input something like:
# define the function blocks
def hard():
print ("Hard mode code goes here.\n")
def medium():
print ("medium mode code goes here\n")
def easy():
print ("easy mode code goes here\n")
def lazy():
print ("i don't want to play\n")
# Now map the function to user input
difficulty_choice = {0 : hard,
1 : medium,
4 : lazy,
9 : easy,
}
user_input=int(input("which mode do you want to choose : \n press 0 for hard \n press 1 for medium \n press 4 for lazy \n press 9 for easy "))
difficulty_choice[user_input]()
Then invocation of function block will be:
difficulty_choice[num]()
Add a conditional for the input.
if difficulty == 'easy':
print("here is an easy game")
elif difficulty == 'medium':
print('here is a medium game')
elif difficulty == 'hard':
print('here is hard')
else:
print('Please enter valid input (easy, medium, hard)')
Under each if statement put your game code.
The reason your code goes through all the difficulties is because of this line:
difficulty_choice = [easy_game(), medium_game(), hard_game()]
When Python sees something like easy_game(), it calls the easy_game function and replaces it with the result. You don't want to call the function yet though, so you can take off the parenthesis to store just the function instead:
difficulty_choice = [easy_game, medium_game, hard_game]
This will mean you have to call the function after you take it out of the array.
As for the crash, when you use raw_input() you get a string back. That means when you type in the 1 to decide for an easy game, you get the character 1, which is represented by the number 49. That's why your code goes through everything and crashes: Your 1 is really a 49. In fact, if you type 1 < '1' into the interpreter, you'll get True back.
To fix that, you can pass the result of raw_input() to the int() function, which will parse it and give you the proper integer (or throw an exception if it can't be parsed). The last line of introduction would then look like game_chooser(int(difficulty)).
You could also skip most of the code of game_chooser by just indexing into the array (that's what they're for, after all):
def game_chooser(difficulty):
# the lack of parens here means you get the function itself, not what it returns
difficulty_choice = [easy_game, medium_game, hard_game]
#each element of the above list links to a procedure and starts one of the
#mini-games.
# note the parens to actually call the retrieved function now
difficulty_choice[difficulty]()

Issues with lists? Error checking not working

I am relatively new to python, and I just started learning how to use classes. This is the first program I've made where I've tried to integrate them, but I'm coming up with a small issue I can't seem to fix, and I think it has to do with lists. The code is as follows:
(The topic is getting the user to choose what type of seat to purchase).
class SeatBooking:
def __init__(self, seat):
self.seat = seat
possible_types = []
possible_types.extend(["Low_Economy", "Standard_Economy", "High_Economy",
"Business", "First", "Residence"])
possible_types = " ".join(possible_types)
while True:
if self.seat not in possible_types:
print("Sorry, but this is not a valid answer. Please try again!")
self.seat = str(input("What type of ticket would you like? The possible types are: {} "
.format(possible_types)))
else:
print("You have chosen to book a {} ticket.".format(self.seat))
confirmation = str(input("Please confirm with 'Yes' or 'No': ")).lower()
if confirmation == "yes":
print("Excellent decision! Ready to continue")
print("=" * 170)
break
elif confirmation == "no":
self.seat = str(input("What type of ticket would you like? The possible types are: {} "
.format(possible_types)))
else:
print("That doesn't seem to be a valid answer.")
Here is the main file (to execute the different classes I'll make):
import type_seat
# Choose the seat to book
print("=" * 170)
print("Welcome to Etihad! This program can help you organize your flight, payments and usage of miles!")
possible_types = []
possible_types.extend(["Low_Economy", "Standard_Economy", "High_Economy",
"Business", "First", "Residence"])
possible_types = " ".join(possible_types)
seat_type = str(input("What type of ticket would you like? The possible types are: {}. "
.format(possible_types)))
type_seat.SeatBooking(seat_type)
The problem I have is that I seem to be able to enter certain letters and it doesn't count them as an error even though they're not one of the available seats. For example, when I enter the letters "h" or "s", my error checking part of the code doesn't respond to it, but when I enter the letter "b" or random words like "try" it does. It doesn't seem to be completely random though, and it seems to only happen with letters or parts of the first 3 'items' in the possible_types[] list. However, I haven't tested this fully. This is why I thought it had something to do with lists, so if anyone knows what's causing this, I'd really appreciate it if they could help me resolve this and perhaps help me from repeating this mistake in the future!
Note, for the lists I am using .join, but I also tried str().
You don't have a list, you are testing characters against one long string:
possible_types = " ".join(possible_types)
The letters h and s are in that string (in the words High_Economy and Business, respectively), but the sequence try doesn't appear anywhere in the string.
If you only wanted to allow whole words to match, you'd need to leave possbile_types a list, or ideally convert it to a set (as sets allow for fast membership testing). You can define the list, no need for list.extend() here:
possible_types = ["Low_Economy", "Standard_Economy", "High_Economy",
"Business", "First", "Residence"]
or make it a set by using {...}:
possible_types = {"Low_Economy", "Standard_Economy", "High_Economy",
"Business", "First", "Residence"}
Do not join this into a string, just test directly against the object:
if self.seat not in possible_types:
If you still need to show the values to a user in an error message, join the values then, or store the str.join() result in a different variable for that purpose.
Note that you shouldn't deal with user input validation in the class __init__ method. Leave user interaction to a separate piece of code, and create instances of your class after you validated. That way you can easily swap out user interfaces without having to adjust all your data objects too.
possible_types = " ".join(possible_types)
Above statement will create one string as "Low_Economy Standard_Economy High_Economy Business First Residence".
Now you are doing
if self.seat not in possible_types:
This will check for a particular character in the string present or not. In your case you are finding 'h' which is present and 'try' which isn't.
Your program will work if you remove this statement
possible_types = " ".join(possible_types)

Python beginner, text-based game

I'm fairly new to the programming game; I'm 3/4 of the way through Learn Python the Hard Way and I had a question about a little text-based game I made... So in this game my guy is stranded on a desert island and you have the option(raw input) of going left right or into the jungle. After choosing a direction, you're given the option to choose how many miles to walk. Each direction is supposed to have a different end result (and mile distance).
If you enter a number that is less than the number of miles to the destination, you're prompted with a choice to either "turn around or "keep going". If you enter turn around, you're taken back to the beginning, where you're again asked to choose a direction. If you enter keep going, the program returns to miles(), where you can choose a new amount of miles to walk.
def miles():
print "How many miles do you walk?"
miles_choice = raw_input("> ")
how_much = int(miles_choice)
if how_much >= 10:
right_dest()
elif how_much < 10:
turn()
else:
print "You can't just stand here..."
miles()
Ok so here's two questions:
How would I make it so that if the user originally enters a number of miles less than the destination distance, and the second mile input + the first mile input == the amount of miles to the destination, it will add the inputs and run my destination function, not just repeat miles().
Since all three final destinations will have different distances, should I write three separate mile functions? Is there a way to make it so that depending on the original direction chosen, miles() will run the different endpoints?
I'm sorry if this doesn't make a lick of sense... I'm still learning and I'm not sure how to fully explain what I'm trying to get across.
You could store the amount of miles to walk in each direction in a dict, and then check the dict to see if the user has walked far enough:
distances = {
'right': 7,
'left': 17,
'forward': 4
}
direction_choice = raw_input("> ")
miles_choice = raw_input("> ")
if how_much >= distances['direction_choice']:
right_dest()
elif how_much < distances['direction_choice']:
turn()
else:
print "You can't just stand here..."
miles()
Be sure to properly validate and cast the user input, which I have not addressed. Good luck!
I don't fully understand the requirements (the intended behavior and constraints). However, you might consider passing a parameter to your function (through and argument) to convey the maximum number of miles which the play could go in that direction).
For example:
#!/usr/bin/env python
# ...
def miles(max_miles=10):
print "How many miles do you walk?"
while True:
miles_choice = raw_input("> ")
try:
how_much = int(miles_choice)
except ValueError, e:
print >> sys.stderr, "That wasn't a valid entry: %s" % e
continue
if max_miles > how_much > 0:
break
else:
print "That's either too far or makes no sense"
return how_much
... in this case you pass maximum valid number of miles into the function through the "max_miles" argument and you return a valid integer (between 1 and max_miles) back.
It would be the responsibility of this function's caller to then call right_dest() or turn() as appropriate.
Note that I've removed your recursive call to miles() and replace it with a while True: loop, around a try: ... except ValueError: ... validation loop. That's more appropriate than recursion in this case. The code does a break out of the loop when the value of how_much is valid.
(By the way, if you call miles() with no parameter then the argument will be set to 10 as per the "defaulted argument" feature. That's unusual to Python (and Ruby) ... but basically makes the argument optional for cases where there's a sensible default value).
#Question #1: I used Class intern variables. You will maybe need them for further programming parts and should take it to zero when you are done on one direction, to start with zero for next step/lvl.
#Question #2: Dictionaries are the best way to do so,self.dest. Parameter pos used as key to get the value from the dictionary.
class MyGame:
def __init__(self):
self.current_miles = 0
self.dest = {'Left' : 10, 'Into the jungle' : 7, 'Right' : 22}
def miles(self,pos):
print "How many miles do you walk?"
miles_choice = raw_input("> ")
self.current_miles += int(miles_choice)
if self.current_miles >= self.dest.get(pos):
self.miles("Right")
elif self.current_miles < self.dest.get(pos):
print "you went "+ str(self.current_miles) + " miles"
else:
print "You can't just stand here..."
self.miles(pos)
mg = MyGame()
mg.miles('Into the jungle')

Categories