Its suppose to print:
no food
breakfast,marmalade
breakfast,coffee
lunch,dessert
dinner
no food
no food
dinner,dessert
def food(input,boolean):
time = int(input)
food_type = ""
if time >= 0 and time < 6 or time >= 22:
food_type = "no food"
if time >= 6 and time <= 10:
food_type = "breakfast"
if time >= 11 and time <= 15:
food_type = "lunch"
if time >= 16 and time < 22:
food_type = "dinner"
dessert = ""
if boolean == True and food_type == "breakfast":
dessert = "marmalade"
if boolean == False and food_type == "breakfast":
dessert = "coffee"
if boolean == True and food_type == "lunch":
dessert = "dessert"
if boolean == True and food_type == "dinner":
dessert = "dessert"
return ','.join((food_type, dessert))
Basically right now, I have a comma between return '' so it will print breakfast, marmalade but then when it comes to no food it adds a comma in the end, so it looks like no food,
Its suppose to look like:
no food
breakfast,marmalade
breakfast,coffee
lunch,dessert
dinner
no food
no food
dinner,dessert
I'm not 100% certain the about the output you want, but I think you want to not have the dessert or the comma if the food_type would be "no food", even if the boolean is True. I can think of at least two different ways to do that.
The first way is to replace
food_type = "no food"
with
return "no food"
Another way would be to replace
return ','.join((food_type, dessert))
with
output = food_type
if output != "no food":
output = ','.join((food_type, dessert))
return output
Some people would prefer the second one since there is only one return.
Related
I'm creating a vending machine program that simulates the action through a loop that ends when the user enters 0 but it doesn't print "0 to cancel" in the output. I tried putting it at the top before the if statements but, I want to be able to enter an input after the if statements are printed. So how could I fix that?
It says that user_val is undefined when I equal it to 0 but I did define it at the bottom.
If someone could help please!
print("*********************************")
print("Welcome to Vending Machine Bravo!")
print("*********************************")
print("If you would like to make a selection, please insert the appropriate currency into the machine.")
# Currency deposit [tag:tag-name]
num_5Dollars = 5.00
num_Dollars = 1.00
num_Quarters = .25
num_Dimes = .10
num_Nickels = .05
num_Pennies = .01
currency = [num_5Dollars, num_Dollars, num_Quarters, num_Dimes, num_Nickels, num_Pennies]
if num_5Dollars == 5.00:
print("5.00 for $5 bills")
if num_Dollars == 1.00:
print("1.00 for $1 bills")
if num_Quarters == .25:
print(".25 for Quarters")
if num_Dimes == .10:
print(".10 for dimes")
if num_Nickels == .05:
print(".05 for nickels")
if num_Pennies == .01:
print(".01 for pennies")
if int(float(user_val)) == 0:
print("0 to cancel")
user_val = float(input())
Your user_val defined under the line if int(float(user_val)) == 0.
And if you want to say to user 0 to cancel, you don't need to check int(float(user_val)) == 0, because while this doesn't happened, it won't print this instruction.
So basically, you need to remove if int(float(user_val)) == 0: line
I'm new in python, and I'm trying to make a simple quit, if the Input is empty or less then One int.
I'm getting an error which says - ValueError: invalid literal for int() with base 10: '', when entering nothing, just a enter on launch.
import sys
import os
import getpass
def clear(): return os.system('clear')
ballance = 500.00
# Garage Stockas
Wood_InStock = 600
Weed_InStock = 300
Gun_InStock = 15
Gun_Ammo_InStock = 500 * 30 # X30 Total 15000
# Kainos
Gun_Ammo_Price = 15.50
Wood_Price = 3.50
Weed_Price = 9.50
Gun_Price = 250.50
# Produktai
medis = '~ Elemental Wood ~'
weed = '~ Indoor Kush ~'
gun = '~ Shotgun ~'
gun_ammo = '~ Shotgun ammo 30x ~'
# Inventory
Wood_Inventory = 0
Weed_Inventory = 0
Gun_Inventory = 0
Gun_Ammo_Inventory = 0
# No Money
Not_Enough_Money = '~ Sorry you dont have enough money'
while True:
Shop_Pasirinkimas = int(input("~ What would you like to buy?\n1. {medis}\n2. {weed}\n3. {gun}\n".format(medis=medis,weed=weed,gun=gun)))
if len(Shop_Pasirinkimas) < 1:
sys.exit("SOrry")
elif Shop_Pasirinkimas == 1:
clear()
WoodPirkimo_Skaic = int(input("How much {medis} would you like to buy? ".format(medis=medis) + "Wood Now in Stock - {woodins}\n".format(woodins=Wood_InStock)))
# Price per wood - 3.50
ballance -= ( Wood_Price * WoodPirkimo_Skaic)
Wood_Inventory += WoodPirkimo_Skaic
Wood_InStock -= WoodPirkimo_Skaic
print("~ In stock of {}, left {}".format(medis,Wood_InStock))
print("~ Successfully bought {}, Your Ballance is {}\n".format(medis,ballance))
print('Inventory:')
print("~ You have {}, of {}\n".format(Wood_Inventory,medis))
Buymore = input("Would you like to buy anything more?... Yes/No\n")
if "Yes" in Buymore or "yes" in Buymore:
continue
elif "No" in Buymore or "no" in Buymore:
break
else:
break
Let's look at only this part of the code:
while True:
Shop_Pasirinkimas = int(input("~ What would you like to buy?\n1. {medis}\n2. {weed}\n3. {gun}\n".format(medis=medis,weed=weed,gun=gun)))
if len(Shop_Pasirinkimas) < 1:
sys.exit("SOrry")
The empty user input will be passed to int(), but an empty string cannot be converted to an int! So an error is raised.
What you should instead is to not convert the input to int first, and treat it as a string:
while True:
Shop_Pasirinkimas = input("~ What would you like to buy?\n1. {medis}\n2. {weed}\n3. {gun}\n".format(medis=medis,weed=weed,gun=gun))
if len(Shop_Pasirinkimas) < 1:
sys.exit("SOrry")
elif int(Shop_Pasirinkimas) == 1: # convert to int here
clear()
...
int(x,base) function will return the integer object from any number or string. Base defaults to 10. If x is the string, its respective numbers should be within possible values with respect to that base.
As, nothing is entered, it's considered as invalid literal.
Hence, Please use the input as string which can solve the issue easily.
If user doesn't input an integer you will encounter an exception in Shop_Pasirinkimas = int(input(...)). Besides int has no len() so this will also cause error len(Shop_Pasirinkimas). You can do the following to accomplish what you are trying
while True:
try:
Shop_Pasirinkimas = int(input("~ What would you like to buy?\n1. {medis}\n2. {weed}\n3. {gun}\n".format(medis=medis,weed=weed,gun=gun)))
if Shop_Pasirinkimas < 1:
sys.exit("SOrry")
elif Shop_Pasirinkimas == 1:
clear()
WoodPirkimo_Skaic = int(input("How much {medis} would you like to buy? ".format(medis=medis) + "Wood Now in Stock - {woodins}\n".format(woodins=Wood_InStock)))
# Price per wood - 3.50
ballance -= ( Wood_Price * WoodPirkimo_Skaic)
Wood_Inventory += WoodPirkimo_Skaic
Wood_InStock -= WoodPirkimo_Skaic
print("~ In stock of {}, left {}".format(medis,Wood_InStock))
print("~ Successfully bought {}, Your Ballance is {}\n".format(medis,ballance))
print('Inventory:')
print("~ You have {}, of {}\n".format(Wood_Inventory,medis))
Buymore = input("Would you like to buy anything more?... Yes/No\n")
if "Yes" in Buymore or "yes" in Buymore:
continue
elif "No" in Buymore or "no" in Buymore:
break
else:
break
except ValueError:
sys.exit("SOrry")
So I am making a camel game and I get a weird error that says
"TypeError: '>' not supported between instances of 'tuple' and 'int'"
and I am not sure what this means, I have posted before and I will state this again I am a beginner coder. Thank you to whoever helps here is the code and I will put a comment where the error is that you!
import random
done = False
milesTraveled = 0
thirst = 0
camelTired = 0
nativesDis = -20
canteens = 5
print('''
Welcome to Camel!
You have stolen a camel to make your way across the great Mobi desert.
The natives want their camel back and are chasing you down! Survive your
desert trek and outrun the natives. ''')
while not done:
oasis = (1,21)
if oasis == 4:
print("You found an oasis!")
canteens = 5
thrist = 0
if thirst > 6:
print("You died of thrist!")
spc = input("")
done = True
if thirst > 4:
print("You are thirsty")
#under here
if camelTired > 8:
print("Your camel DIED!")
spc = input("")
done = True
if camelTired > 5:
print("Your camel is getting tired")
if nativesDis == milesTraveled + 20:
print('The natives caught up with you!')
spc=input("")
done = True
if milesTraveled == 200:
print('You Win!')
spc = input("")
done = True
print('''
A. Drink from your canteen.
B. Ahead full speed.
C. Stop and rest.
D. Status check.
Q. Quit ''')
user_choice = input("")
if user_choice.upper() == 'Q':
done = True
elif user_choice.upper() == 'D':
print('''
Miles Traveled: 0
Drinks In Canteen:''',canteens,'''
Thirstyness:''',thirst,'''
The Natives Are 20 Miles Behind You''')
elif user_choice.upper() == 'C':
camelTired = 0
nativesDis = random.randint(7,15)
elif user_choice.upper() == 'B':
milesTraveled = random.randint(10,22)
print("You traveled",milesTraveled,"miles!")
thirst + 1
camelTired = (1,3)
nativesDis = (7,14)
elif user_choice.upper() == 'A':
if canteens > 0:
canteens = canteens - 1
thirst
= 0
You need to take the number out of the tuple and into a variable that is also an integer.
There are multiple integers in your tuple.
You can access them in the following way:
some_tuple_of_integers = (12, 432, 345)
index_zero_integer = some_tuple_of_integers[0]
index_one_integer = some_tuple_of_integers[1]
index_two_integer = some_tuple_of_integers[2]
print(index_zero_integer)
print(index_one_integer)
print(index_two_integer)
Or just straight from the tuple itself without creating a new variable (This can sometimes get unreadable when working with lots of indexes and tuples).
print(some_tuple_of_integers[0])
print(some_tuple_of_integers[1])
print(some_tuple_of_integers[2])
You can then easily compare between other values.
If, for example you have a string from the tuple that you need to compare with another integer, you can change it by doing:
index_two_integer = int(index_two_integer)
I am new to Python and programming in general. I would like to know how to get rid of this compile error
def health_risk(activity_level, is_smoker):
"""Counts the aliveness of a person"""
alive = "alive?" or "sedentary"
very_low = "low" or "very low"
active = "active" or "very active"
if (activity_level in alive) and is_smoker is True:
xer = "extreme"
elif (activity_level in active) and is_smoker is True:
xer = "medium"
elif (activity_level == alive) and (is_smoker is False):
xer = "high"
elif (activity_level == very_low) and (is_smoker is False):
xer = "medium"
elif activity_level == active and is_smoker is False:
xer = "low"
return xer
level = health_risk('low', True)
print(level)
Thanks for the help and this is my first post, thanks.
Revise your variable statements to be assigned to lists.
alive = ["alive", "sedentary"]
very_low = ["low", "very low"]
active = ["active", "very active"]
Replace all == with in,
Include the missing elif statement.
elif (activity_level in very_low) and (is_smoker is True):
xer = "high" # or medium or whatever
note: to reduce redundancy, you could just put and is_smoker if it's True and and not is_smoker if it's False.
This program is not working right. It seems to be unable to print the cars after "You have the following cars:"
How could I get the variables to change in the def game() section?
Here is a pastebin: http://pastebin.com/pjsuWRYs
import random
car1 = ("car1")
car2 = ("car2")
car3 = ("car3")
car4 = ("car4")
car5= ("car5")
car6 = ("car6")
car7= ("car7")
car8 = ("car8")
car9 = ("car9")
def game():
print ("You have the following cars:")
print (car1)
print (car2)
print (car3)
print (car4)
print (car5)
print (car6)
print (car7)
print (car8)
print (car9)
print ("You selected Grand Thief Auto")
gta = input ("To commit GTA type GTA")
if gta in ("gta", "Gta", "GTA", "a"):
chance = random.randint(0,100)
if chance <= 1:
print ("You stole a Bugatti Veryron")
car1 = ("Bugatti Veryron")
elif chance <= 5:
print ("You stole a Ferrari Spider")
car2 = ("Ferrari Spider")
elif chance <= 10:
print ("You stole a Audi Q7")
car3 = ("Audi Q7")
elif chance <= 15:
print ("You stole a BMW X6")
car4 = ("BMW X6")
elif chance <= 20:
print ("You stole a Jaguar X Type")
car5 = ("Jaguar X Type")
elif chance <= 25:
print ("You stole a Ford Mondeo")
car6 = ("Ford Mondeo")
elif chance <= 30:
print ("You stole a Audi A3")
car7 = ("Audi A3")
elif chance <= 35:
print ("You stole a Ford Fiesta")
car8 = ("Ford Fiesta")
elif chance <= 40:
print ("You stole a Skoda Octavia")
car9 = ("Skoda Octavia")
elif chance <= 100:
print ("You got caught!")
game()
game()
If you want to make the "car"s accessible in the functions, you must set them as global variables.
Try putting
global car1, car2, car3, car4, car5, car6, car7, car8, car9
before the print ("You have the following cars:") and after define game():
I would also suggest using lists or dictionaries instead of defining each variable by itself.
You could have:
cars = ["car1", "car2", "etc"]
# To change a value for "car2" for example, do this:
# List values (indexes) in Python are starting from 0
cars[1] = "Bugatti"
# To print the car name do:
print (cars[0])
print (cars[1])
# Etc.
or:
cars = { "car1" : "Bugatti", "car2" : "Ferarri", "car number" : "car name"}
# To change a value for "car2" for example, do this:
cars["car2"] = "Bugatti"
# And to print the car names:
print (cars["car1"])
print (cars["car2"])
If you chose to use lists or dictionaries, you will have to set the cars variable global as well
To make things look nicer, I would suggest changing input ("To commit GTA type GTA") to (input ("To commit GTA type GTA: ").lower() which will add an extra space for "beauty" and make the input case-insensitive
I would also add newlines (\n) or empty print () statements to make the output prettier and easier to understand. This will just add an empty line wherever you want it to be.