How can I keep this line short in Python - if-statement

I would like to keep if statement line short. Is there any way?
pizza = input("Welcome to Python pizza deliveries.\nWhich pizza would you like to order. S M or L")
bill = 0
if pizza == "s" or pizza == "S" or pizza == "m" or pizza == "M" or pizza == "l" or pizza == "L":
if pizza == "s" or pizza == "S":
print("You ordered small pizza. That costs $15.")
bill += 15
elif pizza == "m" or pizza == "M":
print("You ordered medium pizza. That costs $20.")
bill += 20
elif pizza == "l" or pizza == "L":
print("You ordered Large pizza. That costs $25.")
bill += 25
# add pepperoni for small pizza $2 for mediun and large $3
pepperoni = input("Do you like to add pepperoni on your pizza? Y or N")
if pepperoni =="Y" or pepperoni =="y":
if pizza == "s" or pizza == "S":
bill += 2
else:
bill += 3
# for extra cheese $1.
extra_cheese = input("Do you like to add extra_cheese on your pizza? Y or N")
if extra_cheese == "Y" or extra_cheese == "y":
bill += 1
print(f"Your total bill is: {bill}")
else:
print("Wrong keyword. Try again.")
This line I want to keep it short or want to know to write another way. How can I fix this?
if pizza == "s" or pizza == "S" or pizza == "m" or pizza == "M" or pizza == "l" or pizza == "L":

you could just do
if pizza.lower() in ["s","m","l"]:
do_something()
BUT
I suggest modifying your code in another way:
move the else statement upwards and avoid even checking the letters condition twice. just return from the order handler if it's the wrong value.
(you could also take the input before calling the order handler and send it as a parameter.)
def order_handler():
pizza = input("Welcome to Paython pizza deliveries.\nWhich pizza would you like to order. S M or L")
bill = 0
if pizza == "s" or pizza == "S":
print("You ordered small pizza. That costs $15.")
bill += 15
elif pizza == "m" or pizza == "M":
print("You ordered medium pizza. That costs $20.")
bill += 20
elif pizza == "l" or pizza == "L":
print("You ordered Large pizza. That costs $25.")
bill += 25
else:
print("Wrong keyword. Try again.")
return
# add pepperoni for small pizza $2 for mediun and large $3
pepperoni = input("Do you like to add pepperoni on your pizza? Y or N")
if pepperoni == "Y" or pepperoni == "y":
if pizza == "s" or pizza == "S":
bill += 2
else:
bill += 3
# for extra cheese $1.
extra_cheese = input("Do you like to add extra_cheese on your pizza? Y or N")
if extra_cheese == "Y" or extra_cheese == "y":
bill += 1
print(f"Your total bill is: {bill}")

Create a list containing those letters and then check if pizza in list
myList = ["s","S","m","M","L","l"]
if pizza in myList:
do something

You could write it like this:
if pizza.lower() in [*"sml"]:

Related

Python; printing outputs based on user input

This is a simple code where the script would ask for the user's name, age, sex, and height and give an output based on that. My current code is as follows:
print "What is your name?"
name = raw_input()
print "How old are you?"
age = raw_input()
print "Are you male? Please answer Y or N"
sex = raw_input()
if sex == "Y" or sex == "y":
sex = "Male"
else:
sex = "Female"
print "How tall are you? Please enter in feet such as 5.5"
height = raw_input()
if sex == "Male" and height >= 6.0:
t = "You are tall for a male"
elif sex == "Male" and height < 6.0:
t = "You are below average for a male"
elif sex == "Female" and height >= 5.5:
t = "You are tall for a female"
else:
t = "You are below average for a female"
print "Hello %s. You are %s years old and %s feet tall. %s." % (name, age, height, t)
I am getting hung up on the if, elif, else statement:
if sex == "Male" and height >= 6.0:
t = "You are tall for a male"
elif sex == "Male" and height < 6.0:
t = "You are below average for a male"
elif sex == "Female" and height >= 5.5:
t = "You are tall for a female"
else:
t = "You are below average for a female"
The code will differentiate if sex is Male or Female, but will always return "You are tall for a xxx". I can not figure out how to get the "You are below average" return.
That's because raw_input() returns a string, not a float, and comparison is always the same way between a string and a float in Python 2.
>>> "1.0" > 6.0
True
Do this:
height = float(raw_input())
height = input() would have worked too but is discouraged (security issues because of evaluation)
Note: this has been fixed in Python 3 (probably because it wasn't very useful, and error-prone): trying to do this results in
TypeError: unorderable types: str() > float()
which is explicit and would have allowed to realize your mistake.
Note: same issue if you try to compare age (age = raw_input() should be age = int(raw_input()))

day of the week issue always prompts monday no matter the entry

The outcome of this is when you enter any number 1-7 you will get the day of that number. for some reason it will always prompt Monday. How can I fix this?
'#Enter a number range 1-7 for the day of the week Example 1=Monday
#variables to represent the days of the week
num = float(input ("Enter the number for the day of week"))
Monday_number = 1
Tuesday_number = 2
Wednesday_number = 3
Thursday_number = 4
Friday_number = 5
Saturday_number = 6
Sunday_number = 7
Other_number = 8
#the day of the week
if Monday_number == 1:
print('Monday')
elif Tuesday_number == 2:
print('Tuesday')
elif Wednesday_number == 3:
print('Wednesday')
elif Thursday_number == 4:
print('Thursday')
elif Friday_number == 5:
print('Friday')
elif Saturday_number == 6:
print('Saturday')
elif Sunday_number == 7:
print('Sunday')
else:
if Other_number > 7:
print('Invalid number entered')'
You're not comparing num, the user input, to anything. In your if statements, you should be sequentially comparing num to each of the day of week constants. Better yet, you could be using a lookup table:
days = ['Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday', 'Saturday', 'Sunday']
user_input = input('Enter the day of the week: ')
print(days[int(user_input)])
Step through your algorithm mentally, line-by-line. What happens when you get to the first if statement?

How to write an if statement with an interval?

I can't figure it out.
So far I have, but it isn't working, no matter what age I input it tells me I can be president.
import math
(x) = input("Please enter your name:")
(y) = input("Please enter your age:")
print ("Hello" + x)
print ("Your age is" + y)
if ("y")> ("0") and ("y") < ("18"):
print("You are a minor.")
if ("y")>=("18") and ("y") < ("25"):
print("You can vote.")
if ("y")>= ("25") and ("y") < ("35"):
print("You can rent a car.")
if ("y") >= ("35"):
print("You can be president.")
else:
print ("You have not entered a valid response. Must be a positive integer.")
How to get the intervals properly?
Writing an inequality range is a lot simpler in Python than doing distinct cut-offs; you can use math-style ranges.
Here's an example:
if 0 < y < 18:
print("You are a minor.")
You shouldn't quote your variable, as that will treat it like a string literal.
With help from the awesome Makoto, it's fixed! :D
import math
(x) = input("Please enter your name:")
(y) = int(input("Please enter your age:"))
print ("Hello" + x)
print ("Your age is" , y)
if 0 < (y) < 18:
print("You are a minor.")
elif 18 <= (y) < 25:
print("You can vote.")
elif 25 <= (y) < 35:
print("You can rent a car.")
elif (y) >= 35:
print("You can be president.")
else:
print ("You have not entered a valid response. Must be a positive integer.")

Using a dictionary to choose scenes in a game, but it's not playing the correct scene. Why?

At the start, if a random integer = 1, it will play a random event. The random event should be selected (also randomly) from a dictionary containing each scene name. Instead, it doesn't try to access the other scenes. It only runs each method(function?) in the order written. What am I doing wrong? Is this a bad way to go about this?
I'm still learning, so any pointers are appreciated!
from random import randint
from time import sleep
class RandomEvent(object):
def __init__(self, wallet):
self.wallet = wallet
def old_man(self):
#insert art
print "\nExcuse me, I have an unusual request."
print "My horoscope tells me it's my lucky day,"
print "but I don't have any money."
print "\nIf you'll let me borrow some money, I"
print "promise to give you half of all the winnings."
print "Do we have a deal?"
give_money = raw_input("(y)es or (n)o? ")
if give_money.lower() == "y":
print "\nFunds: $", self.wallet
how_much = int(raw_input("How much money will you give? $"))
if how_much <= self.wallet:
how_much *= randint(2,3)
print "Haha! I won $%d! Here's your share of the money, kiddo." % (how_much*2)
self.wallet += how_much
else:
print "Eh, kids these days... no faith in their elders... (grumble grumble)..."
sleep(2)
print "\nA few moments later you see the old man hit the jackpot at a slot machine."
return self.wallet
def robber(self):
#insert art
print "\nPsssst! Hey, you!"
#sleep(1)
print "\nYou glance down to see a knife discreetly placed"
print "to your stomach."
#sleep(1)
print "\nHand over all your cash. No funny business."
print "\nFunds: $", self.wallet
how_much = int(raw_input("How much money will you give? $"))
lie_success = randint(1,3)
if how_much == self.wallet:
self.wallet = 0
print "\nNice doin' business with ya."
print "The robber quickly disappears into a nearby crowd,"
print "taking all your money with him."
if how_much != self.wallet and lie_success == 1:
self.wallet -= how_much
print "\nNice doin' business with ya."
print "The robber quickly disappears into a nearby crowd,"
print "taking your money with him."
else:
print "\nYou think you're a wise guy, eh?"
sleep(2)
print "\nYou are dead. GAME OVER"
sleep(2)
exit()
return self.wallet
def pretty_woman(self):
pass
###----------------------GAME CODE BELOW---------------
funds = 500
encounter = 1
while True:
if encounter == randint(1, 1): # 1,1 FOR TESTING
story = RandomEvent(funds)
scene_list = {1: story.old_man(), 2: story.robber(), 3: story.pretty_woman()}
funds = scene_list[2] #randint(1,3)] FOR TESTING
else:
print "\n\n\nWelcome to Dreams Casino."
print "Where would you like to go?"
print "(1) Slot Machines"
print "(2) Roulette Table"
print "(3) Leave the Casino"
print "\nFunds: $", funds
game_choice = int(raw_input("> "))
You're calling the functions when creating your dictionary:
scene_list = {1: story.old_man(), 2: story.robber(), 3: story.pretty_woman()}
Since you want scene_list[1] to refer to your function, pass the function:
scene_list = {1: story.old_man, 2: story.robber, 3: story.pretty_woman}

Roulette program will not recognize correct guess. Why?

The following is the roulette portion of a casino game I'm putting together, but I can't seem to get it to work correctly. It won't recognize when the player chooses the correct number, and I'm hoping someone can tell me why. Obviously, a few other parts have not been completed, but I'm just trying to get the basics running. Also, I'm pretty new at this, so feel free to critique anything else! Thanks.
from random import randint
from time import sleep
funds = 50
### Straight Up number bet = 35:1
### Odd/Even payout = 1:1
class RouletteTable(object):
def __init__(self, wallet):
self.wallet = wallet
def spin(self, bets):
print "Spinning..."
sleep(2)
print "The winner is..."
sleep(1)
winner = 25 #randint(0, 36) #FOR TESTING
print "Number ", winner
if winner in bets == True:
bets = True
return bets
else:
print "You bet on: ", bets
print "Better luck next time."
bets = False
return bets
def game(self):
while self.wallet >= 0:
print "\n\nWelcome to Roulette."
print "Test your luck, and place your bets!"
print "Current funds: $", self.wallet
print "\n(1)Place bet or (2)Exit"
choice = raw_input("> ")
if choice == "1":
bets = []
print '''\n\n\n
__________
[ 0 ]
[ 1][ 2][ 3]
[ 4][ 5][ 6]
[ 7][ 8][ 9]
[10][11][12]
[13][14][15]
[16][17][18]
[19][20][21]
[22][23][24]
[25][26][27]
[28][29][30]
[31][32][33]
[34][35][36]
[ODD] [EVEN]
'''
print "How much will you bet (per number)?"
bet_amount = int(raw_input("> $"))
print "Type a number to bet on, and press Enter."
print "When finished choosing, just press Enter."
while True:
print "Funds: $", self.wallet
print "Current Bets: ", bets
number_choice = raw_input("> ")
if number_choice != "":
bets.append(int(number_choice))
self.wallet -= bet_amount
else:
# start spin
self.spin(bets)
# payout for bets
if bets == True:
print "You win $", bet_amount*35
self.wallet += bet_amount*35
break
if choice == "2":
return self.wallet
break
if self.wallet == 0:
print "You're out of money!\n"
roulette = RouletteTable(funds)
funds = roulette.game()
Your main error was this:
# start spin
self.spin(bets)
# payout for bets
It should read:
#start spin
bets = self.spin(bets)
# payount bets
the modified code below does it correctly. Overwriting bets with a different type isn't good style, I'd suggest using a different variable. Also win in bets doesn't need to explicitly compared to True (unless for clarification during learning).
Hope that helps, if you have further questions, just comment ;-)
from random import randint
from time import sleep
funds = 50
### Straight Up number bet = 35:1
### Odd/Even payout = 1:1
class RouletteTable(object):
def __init__(self, wallet):
self.wallet = wallet
def spin(self, bets):
print "Spinning..."
sleep(2)
print "The winner is..."
sleep(1)
winner = 25 #randint(0, 36) #FOR TESTING
print "Number ", winner
if winner in bets:
return True
else:
print "You bet on: ", bets
print "Better luck next time."
return False
def game(self):
while self.wallet >= 0:
print "\n\nWelcome to Roulette."
print "Test your luck, and place your bets!"
print "Current funds: $", self.wallet
print "\n(1)Place bet or (2)Exit"
choice = raw_input("> ")
if choice == "1":
bets = []
print '''\n\n\n
__________
[ 0 ]
[ 1][ 2][ 3]
[ 4][ 5][ 6]
[ 7][ 8][ 9]
[10][11][12]
[13][14][15]
[16][17][18]
[19][20][21]
[22][23][24]
[25][26][27]
[28][29][30]
[31][32][33]
[34][35][36]
[ODD] [EVEN]
'''
print "How much will you bet (per number)?"
bet_amount = int(raw_input("> $"))
print "Type a number to bet on, and press Enter."
print "When finished choosing, just press Enter."
while True:
print "Funds: $", self.wallet
print "Current Bets: ", bets
number_choice = raw_input("> ")
if number_choice != "":
bets.append(int(number_choice))
self.wallet -= bet_amount
else:
# start spin
did_win = self.spin(bets)
# payout for bets
if did_win == True:
ammount = bet_amount*35
self.wallet += ammount
print "You win $", ammount
break
if choice == "2":
return self.wallet
break
if self.wallet == 0:
print "You're out of money!\n"
roulette = RouletteTable(funds)
funds = roulette.game()