program to look up price in dictionary - python-3.x

I am having issues with creating this program I don't know whether I should use elif or something else.
Here is the question: In the cell below, use the try/except control structure to create a program which looks up a price in a dictionary.
shop_prices = {
'eggs': 1.99,
'milk': 0.99,
'ham': 4.99,
}
# take two inputs - what the customer wants, and how many of the items they want
# always greet the customer
# see if they sell the item and calculate the price
# otherwise say "We don't sell XXX", where XXX is the item
# always say goodbye to the customer

This may be what you're looking for. It asks what you want, and if it isn't available, it asks again. After that, it asks you how many of that item you want, and if that input is valid, it prints out the cost and exits.
shop_prices = { 'eggs': 1.99, 'milk': 0.99, 'ham': 4.99, }
request = input("Hello, what would you like?\n")
while request not in shop_prices.keys():
request = input("That item isn't currently available, please choose another item.\n")
while True:
try:
numof = int(input("How many of that item would you like?\n"))
break
except ValueError:
print("That isn't an integer, please enter an integer.\n")
print("That will be $"+str(numof*shop_prices[request])+". Thank you for shopping here today.\n")

Related

How to change an input() to lower case?

I'm new to python and trying my best to learn. At this moment I'm following to program along with YouTube. But I got stuck with this piece of code where I'm trying to change user input to lowercase and comparing it to a list to see if item is available or not. And ever time I ran code I get Not available. Here is the code:
stock = ['Keyboard', 'Mouse', 'Headphones', 'Monitor']
productName = input('Which product would you like to look up:').lower()
if productName in stock
print('Available')
else:
print('Not Available')
- List item
Change your stock array to be all lowercase, like so:
stock = ['keyboard', 'mouse', 'headphones', 'monitor']
Because you modify the user input to be lowercase, no matter what, and the stock items in the array are capitalized, no matter what, they will never match in your if statement. String comparison in Python is case sensitive (as it is in nearly every programming language).

How do I validate a user's input and make sure it is the correct type and within a given range?

I'm trying to write a program that will help me in my job to write behavioral reports on teenage boys in a therapeutic program. The goal is to make it easier to write the everyday expectations(eating, hygiene, school attendance, etc) so that I can write the unique behaviors and finish the report faster. I'm currently working on how many meals the boy at during the day and am trying to get it to validate that the user input is the correct type of input and within the correct range(0-3). Afterwards I want to change the variable depending on the answer given so it will print a string stating how many meals they ate. I've been able to get the program to validate the type to make sure that the user gave and integer but I cant get it to make sure that the given answer was in the desired range. Any help would be appreciated I only started learning python and programming a month ago so very inexperienced.
Here's what my code looks like so far and what I would like the variable to change to depending on the given answer.
Name=input('Student Name:')
while True:
try:
Meals=int(input('Number of Meals(between 0-3):'))
except ValueError:
print ('Sorry your response must be a value between 0-3')
continue
else:
break
while True:
if 0<= Meals <=3:
break
print('not an appropriate choice please select a number between 0-3')
#if Meals== 3:
#Meals= 'ate all 3 meals today'
#elif Meals==2:
#Meals='ate 2 meals today'
#elif Meals==1:
#Meals='ate only 1 meal today'
#elif Meals==0:
#Meals='did not eat any meals today'
You can check if number of inputted meals falls to valid range and if yes, break from the loop. If not, raise an Exception:
while True:
try:
meals = int(input('Number of Meals(between 0-3):'))
if 0 <= meals <= 3:
break
raise Exception()
except:
print('Please input valid integer (0-3)')
print('Your choice was:', meals)
Prints (for example):
Number of Meals(between 0-3):xxx
Please input valid integer (0-3)
Number of Meals(between 0-3):7
Please input valid integer (0-3)
Number of Meals(between 0-3):2
Your choice was: 2

How to increment a list with a variabe who change his value on each reboot in a loop in Python3?

I have a problem.
I want to make a shopping list who asking to the user what item does it want and how many.
The list will evolve on each time the loop "reboot" by adding the name of the item (a string) and the number it is associated with (an integer).
The only problem is that when the loop "reboot", the contents of the list is reset.
Here is the code:
def shopping(n):
x=0
while x<n:
item={}
nb={}
shopping_cart={}
item[x]=str(input("item?")) #We asking the user the name of the item he wants.
nb[x]=int(input("nb?")) #We asking the user the number he wants.
shopping_cart[x] = item[x],nb[x]
shopping_cart+=shopping_cart[x] #We try to add what the user has entered to a dictionary to not reset what he has entered before.
x+=1
print(shopping_cart)
shopping(2) #To simplify, in this exemple, we imagine that the customer want to buy two differents items.
But, on the console I have this:
TypeError: unsupported operand type(s) for +=: 'dict' and 'tuple'
I don't find a way to not reset what the customer said before...
Ps: Sorry for my English, I'm French... :)
The below function will return a dictionary of the items the user wants to purchase to the number of each item they want.
def shopping(n):
cart = {}
for _ in range(n):
item = input("What would you like to buy?")
amount = int(input("How many would you like?"))
cart[item] = cart.get(item, 0) + amount
return cart

Create a list (length and int values defined by user input) and then find lowest value in list and exclude from proceeding calculation

I am having trouble with making a simple calculator work. There are some requirements I need to meet with it:
Need to be able to calculate the average of however many grades the user wants
Be able to calculate within the same program separate grade averages
for multiple 'users'
Give the option to exclude the lowest value entered for each person
from their individual average calculation.
I have some code, it is pretty much a mess:
def main():
Numberofstudents=eval(input("How many students will enter grades today? "))
Name=input("What is your frist and last name? ")
numberofgrades=eval(input("How many grades do you want to enter? "))
gradecount=0
studentcount=1
lowestgradelisty=[]
while studentcount<=Numberofstudents:
gradetotal=0
while gradecount<numberofgrades:
gradeforlisty=eval(input("Enter grade please: "))
gradetotal=gradetotal+gradeforlisty
gradecount=gradecount+1
Numberofstudents=Numberofstudents-1
studentcount=studentcount+1
lowestgradelisty.extend(gradeforlisty)
min(lowestgradelisty.extend(gradeforlisty))
Drop=(min(lowestgradelisty.extend(gradeforlisty))), "is your lowest grade. do you want to drop it? Enter as yes or no: "
if (Drop=="yes"):
print(Name, "The new total of your grades is", gradetotal-min(lowestgradelisty.append(gradeforlisty)/gradecount))
elif (Drop=="no"):
print("the averages of the grades enetered is", gradetotal/gradecount)
gradecount=0
studentcount=1
main()
Here's a function that does what it sounds like you wanted to ask about. It removes the smallest grade and returns the new average.
def avgExceptLowest(listofgrades):
# find minimum value
mingrade = min(listofgrades)
# remove first value matching the minimum
newgradelist = listofgrades.remove(mingrade)
# return the average of of the new list
return sum(newgradelist) / len(newgradelist)
A number of notes on your code:
The indentation of the code in your question is wrong. Fixing it may solve some of your problems if that's how it appears in your python file.
In Python the convention is to never capitalize a variable, and that's making your highlighting come out wrong.
If you code this correctly, you won't need any tracking variables like studentcount or gradecount. Check out Python's list of built-in functions and use things like len(lowestgradelisty) and loops like for i in range(0, numberofstudents): instead to keep your place as you execute.

Slicing a dictionary to print specific information

This is part of something larger i'm working on but i needed to figure out how to do it for this section in order to move on.
Note: This is not homework, only a personal project.
Roxanne = {'Location': 'Rustboro City', 'Type': 'Rock',
'Pokemon Used': 'Geodude: Lvl 12, Geodude: Lvl 12, Nosepass: Lvl 15'}
user = input("What would you like to learn about: Gym Leaders, Current Team, Natures, or Evolution ")
if user == 'Gym Leaders' or 'gym leaders':
response = input('Who would you like to learn about? '
'Roxanne, Brawly, Wattson, Flannery, Norman, Winona, The Twins, or Juan? ')
if response == 'Roxanne' or 'roxanne':
ask = input('What would you like to know about? Location, Type, Pokemon Used ')
if ask == 'Location' or 'location':
# i need to print the location part of the Roxanne dictionary here, i.e. 'Rustboro City'
I'm just testing to see if I should just print the entire 'Roxanne' dictionary based on user input, or if I should print individual info from it, so that a user can find specific information.
Finally, the only python experience I have is the introductory course I'm taking in Uni right now, so nothing too difficult or complicated. The challenge I set myself was to stay within the boundaries of the course.

Resources