couple issues with my code I need help working out.
how do I get the header to only print once above the results, and not at all if nothing meetings the criteria?
the else component of my code is no longer working, it used to just print if none of the other scenarios were true but I updated it and now it keeps printing every time. Can anyone spot the issue?
Code:
import Hotels
htl_1= Hotels.Hotels(111,100,1,1)
htl_2= Hotels.Hotels(112,200,2,1)
htl_3= Hotels.Hotels(113,250,2,2)
htl_4= Hotels.Hotels(114,300,3,2)
htl_5= Hotels.Hotels(115,350,3,3)
feeInput=input('Enter maximum per night fee: ')
roomInput=input('Enter minimum number of bedrooms: ')
bathInput=input('Enter minimum number of baths: ')
header='{:10} {:10} {:10} {:10}'.format('Room#','Cost','Rooms','Bathrooms')
print(header)
if int(feeInput)>= htl_1.fee and int(roomInput)<= htl_1.rooms and int(bathInput)<= htl_1.bath:
print(htl_1.gethtl())
if int(feeInput)>= htl_2.fee and int(roomInput)<= htl_2.rooms and int(bathInput)<= htl_2.bath:
print(htl_2.gethtl())
if int(feeInput)>= htl_3.fee and int(roomInput)<= htl_3.rooms and int(bathInput)<= htl_3.bath:
print(htl_3.gethtl())
if int(feeInput)>= htl_4.fee and int(roomInput)<= htl_4.rooms and int(bathInput)<= htl_4.bath:
print(htl_4.gethtl())
if int(feeInput)>= htl_5.fee and int(roomInput)<= htl_5.rooms and int(bathInput)<= htl_5.bath:
print(htl_5.gethtl())
else:
print('Sorry, no rooms available that meet that criteria')
Without knowing the Hotels module I believe this syntax is correct. In order for the else to only activate when none of those if statements are true, you need to change them to elif (after the first if statement) as shown. The .format you used only works inside of a print statment as shown. Thanks
import Hotels
htl_1= Hotels.Hotels(111,100,1,1)
htl_2= Hotels.Hotels(112,200,2,1)
htl_3= Hotels.Hotels(113,250,2,2)
htl_4= Hotels.Hotels(114,300,3,2)
htl_5= Hotels.Hotels(115,350,3,3)
feeInput = int(input('Enter maximum per night fee: '))
roomInput = int(input('Enter minimum number of bedrooms: '))
bathInput = int(input('Enter minimum number of baths: '))
header = True
if feeInput >= htl_1.fee and roomInput <= htl_1.rooms and bathInput<= htl_1.bath:
print(htl_1.gethtl())
elif feeInput >= htl_2.fee and roomInput <= htl_2.rooms and bathInput <= htl_2.bath:
print(htl_2.gethtl())
elif feeInput >= htl_3.fee and roomInput <= htl_3.rooms and bathInput <= htl_3.bath:
print(htl_3.gethtl())
elif feeInput >= htl_4.fee and roomInput <= htl_4.rooms and bathInput <= htl_4.bath:
print(htl_4.gethtl())
elif feeInput >= htl_5.fee and roomInput <= htl_5.rooms and bathInput <= htl_5.bath:
print(htl_5.gethtl())
else:
print('Sorry, no rooms available that meet that criteria')
header = False
if header == True:
print('{0} {1} {2} {3}'.format(RoomVar,CostVar,RoomsVar,BathroomsVar))
You need to change if to elif and move the header printing code to if blocks as well.
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
import math
import random
a = math.floor((random.random())*100)
if a%10 != 00:
c = math.floor(a/10)
a = a - c*10
#to make sure the number isnt over 10
attempts = int(input("enter num of attempts"))
att = attempts
for i in range(0,attempts+1,1):
tr = int(input("try"))
att = att -1
if tr == a:
print("good")
break;
else:
print("no,try again", "you got",att,"more attempts")
if att == 0:
print("game over,the num was", (a))
the game has random num between 0-10 and you need to insert num of attempst, and then guess what number is it, and you got the amount of attempst you have insert to try guessing the num.
You can replace the for loop by a while loop.
This way you have more control, you can use a found boolean and loop while it is False.
Note also that you have to increment i by yourself.
I printed the messages (win/lost) outside of the loop.
It makes the loop code more readable.
I also used randint() to choose the random number to guess.
It does all the work without further computation and is also part of the random module.
from random import randint
a = randint(1, 10)
attempts = int(input("enter num of attempts"))
att = attempts
found = False
i = 0
while i < attempts and not found:
i += 1
att -= 1
tr = int(input("try"))
if tr == a:
found = True
elif att > 0:
print("no,try again", "you got", att, "more attempts")
if found:
print("good")
else:
print("game over,the num was", (a))
I am trying to make a linking memory script in python. Script should select a few words (user determined number) from several lists. These are my lists and a dictionary for taking user number (determines how many word will be displayed).
import random
LIST_THAT_WILL_BE_DISPLAYED = []
Number_of_Every_List = {
"numberObject":0,
"numberVerb":0,
"numberName":0,
"numberTerm":0,
"numberCountryAndCity":0
}
listObject = ["computer","monitor","apple","banana","car"]
listVerb = ["fill","fly","emphasize","probe","write"]
listTerm = ["Protocol","FTP","SSH","VPN","base64"]
listName = ["John","Amy","Math","Elizabeth","Andrew"]
listCountryAndCity = ["Paris","Czech Republic","USA","Mexico","Netherlands"]
Then It should take inputs from user and append all these to the list above.
# TAKING INPUTS FROM USER
Number_of_Every_List["numberObject"] = int(input(f"Number of Object (max {len(listObject)}): "))
Number_of_Every_List["numberVerb"] = int(input(f"Number of Verb (max {len(listVerb)}): "))
Number_of_Every_List["numberName"] = int(input(f"Number of Name (max {len(listName)}): "))
Number_of_Every_List["numberTerm"] = int(input(f"Number of Term (max {len(listTerm)}): "))
Number_of_Every_List["numberCountryAndCity"] = int(input(f"Number of Country&City (max {len(listCountryAndCity)}): "))
while Number_of_Every_List["numberObject"] != 0:
LIST_THAT_WILL_BE_DISPLAYED.append(random.choice(listObject))
# CHECKING IF THERE IS A DUPLICATE IN "LIST THAT WILL BE DISPLAYED"
if LIST_THAT_WILL_BE_DISPLAYED.count(LIST_THAT_WILL_BE_DISPLAYED[-1]) > 1:
LIST_THAT_WILL_BE_DISPLAYED.pop()
else:
Number_of_Every_List["numberObject"] -= 1
while Number_of_Every_List["numberVerb"] != 0:
LIST_THAT_WILL_BE_DISPLAYED.append(random.choice(listVerb))
if LIST_THAT_WILL_BE_DISPLAYED.count(LIST_THAT_WILL_BE_DISPLAYED[-1]) > 1:
LIST_THAT_WILL_BE_DISPLAYED.pop()
else:
Number_of_Every_List["numberVerb"] -= 1
while Number_of_Every_List["numberName"] != 0:
LIST_THAT_WILL_BE_DISPLAYED.append(random.choice(listName))
if LIST_THAT_WILL_BE_DISPLAYED.count(LIST_THAT_WILL_BE_DISPLAYED[-1]) > 1:
LIST_THAT_WILL_BE_DISPLAYED.pop()
else:
Number_of_Every_List["numberName"] -= 1
while Number_of_Every_List["numberTerm"] != 0:
LIST_THAT_WILL_BE_DISPLAYED.append(random.choice(listTerm))
if LIST_THAT_WILL_BE_DISPLAYED.count(LIST_THAT_WILL_BE_DISPLAYED[-1]) > 1:
LIST_THAT_WILL_BE_DISPLAYED.pop()
else:
Number_of_Every_List["numberTerm"] -= 1
while Number_of_Every_List["numberCountryAndCity"] != 0:
LIST_THAT_WILL_BE_DISPLAYED.append(random.choice(listCountryAndCity))
if LIST_THAT_WILL_BE_DISPLAYED.count(LIST_THAT_WILL_BE_DISPLAYED[-1]) > 1:
LIST_THAT_WILL_BE_DISPLAYED.pop()
else:
Number_of_Every_List["numberCountryAndCity"] -= 1
# SHUFFLING LIST SO SAME TYPE WORDS WON'T BE SHOWN RESPECTIVELY
random.shuffle(LIST_THAT_WILL_BE_DISPLAYED)
print(LIST_THAT_WILL_BE_DISPLAYED)
The problem is if I don't give input that bigger than length of lists, it works fine. But if I give 6 for example, script can't go out from while loop.
Why it happens ?
Lastly I know it's an easy question but I couldn't find why it happens despite hours of searching in internet. :/
I am trying to figure out the best way to split up this function into two separate functions. One being Main() and the other being determineStatus(). I have to use Main() to call determineStatus. The code does exactly what I want it to do just not sure a effective way to split it up.
Not really sure a way to split it up without getting tons of errors.
message="How many current credit hours do you have?"
def determineStatus(message):
while True:
try:
userInput = int(input(message))
except ValueError:
print("Please use whole numbers only. Not text nor decimals.")
continue
else:
return userInput
hours = determineStatus(message)
F=30
J=60
S=90
Max=200
if hours <= Max:
if hours < F:
print("You are classified as a Freshman")
if hours > F and hours < J:
print("You are classified as a Sophmore")
if hours >= J and hours < S:
print("You are classified as a Junior")
if hours >= S and hours < Max:
print("You are classified as a Senior")
else:
print("With",hours," hours you are either an Alumni, 2nd Degree seeking student or lying about your hours.")
determineStatus(message)
A right data structure is a great code-cutting tool.
# python 3.x
CLASSIFIER = [
# (min, max, status)
(0, 30, 'Freshman'),
(30, 60, 'Sophomore'),
(60, 90, 'Junior'),
(90, 200, 'Senior'),
]
def classify(hours):
assert hours >= 0, 'WTF, negative hours'
for (lower, upper, status) in CLASSIFIER:
if lower <= hours < upper:
return status
return 'Alumni, 2nd Degree seeking student or lying about your hours'
def ask(message):
while True:
try:
return int(input(message))
except ValueError:
print('Try entering a non-negative whole number again.')
def main():
hours = ask('How many hours? ')
print('With %d hours, you are %s' % (hours, classify(hours)))
# Optional: auto-invoke main() if we're being executed as a script.
if __name__ == '__main__':
main()
I would do it this way.
Create a module
F = 30
J = 60
S = 90
Max = 200
def determineStatus(message):
while True:
try:
userInput = int(input(message))
except ValueError:
print("Please use whole numbers only. Not text nor decimals.")
continue
else:
return userInput
def calculateStatus(hours):
if hours <= Max:
if hours < F:
return "You are classified as a Freshman"
if hours > F and hours < J:
return "You are classified as a Sophmore"
if hours >= J and hours < S:
return "You are classified as a Junior"
if hours >= S and hours < Max:
return "You are classified as a Senior"
else:
return "With {0} hours you are either an Alumni, 2nd Degree seeking student or lying about your hours.".format(hours)
Now create a little script:
import temp
message = "How many current credit hours do you have?"
# You can repeat the lines below by using a while loop
hours = temp.determineStatus(message)
print temp.calculateStatus(hours)
For your multiple ifs, you get a warning from the Department of Redundancy Department!
If hours is not smaller than J, there's no need in checking it's greater than or equal to J.
Also, if hours = F, you'll return that the student is lying.
Finally, you won't return anything for hours = Max.
Here's an optimized determine_status function :
statuses = [
(30, 'Freshman'),
(60, 'Sophomore'),
(90, 'Junior'),
(200, 'Senior')
]
def determine_status(hours):
for max_hours, status in statuses:
if hours < max_hours:
return "You are classified as a %s" % status
return "With %d hours you are either an Alumni, 2nd Degree seeking student or lying about your hours." % hours
print(determine_status(0))
# You are classified as a Freshman
print(determine_status(30))
# You are classified as a Sophomore
print(determine_status(55))
# You are classified as a Sophomore
print(determine_status(75))
# You are classified as a Junior
print(determine_status(100))
# You are classified as a Senior
print(determine_status(205))
# With 205 hours you are either an Alumni, 2nd Degree seeking student or
# lying about your hours.
I have this data in a CSV
34512340,0
12395675,2
56756777,1
My code below is checking what the stock level of each product is. The product is the eight digit number in the csv, and the number after the comma is the amount of available stock.
If the stock level is above 0, all works fine.
However, when the stock level gets to 0, instead out printing the out of stock message, the program prints the new order message. Can anybody work out why this is happening?
def checkstocklevel(code):
with open('stockcontrol.csv',newline='') as f:
for line in f:
if code in line:
data = line.split(",")
stocklevel = int(data[1])
if stocklevel <= 5:
print("New Order Required - Remaining Stock:",data[1],)
elif stocklevel <= 10:
print("Low Stock - Remaining Stock:",data[1],)
elif stocklevel < 1:
print("Sorry, this product is out of stock")
f = open("receipts","a")
f.write(code)
f.write(" Product Out Of Stock\n")
f.close()
else:
print("Normal Stock -",data[1],)
return stocklevel
Thanks
A value of 0 already matches your first condition stocklevel <= 5 so your later condition < 1 is never reached.
Reorder your conditions. Start with the most strict condition, then relax them.
if stocklevel < 1:
print("Sorry, this product is out of stock")
f = open("receipts","a")
f.write(code)
f.write(" Product Out Of Stock\n")
f.close()
elif stocklevel <= 5:
print("New Order Required - Remaining Stock:",data[1],)
elif stocklevel <= 10:
print("Low Stock - Remaining Stock:",data[1],)
else:
print("Normal Stock -",data[1],)