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],)
Related
import random
MIN_LINES = 1
MAX_LINES = 3
MAX_BET = 100
MIN_BET = 1
ROW = 3
COL = 3
symbol_count = {
"A":2,
"B":4,
"C":6,
"D": 8,
}
def get_slot_machine_spin(rows,cols,symbols):
all_symbols = []
for symbol , symbol_count in symbols.items():
for _ in range(symbol_count):
all_symbols.append(symbol)
columns = [[],[],[]]
for _ in range(cols):
current_symbols = all_symbols[:]
for _ in range(rows):
value = random.choice(current_symbols)
current_symbols.remove(value)
columns.append(value)
columns.append(columns)
return columns
def print_slot_machine(colmuns):
for row in range(len(colmuns[0])):
for i , colmun in enumerate(colmuns):
if i != len(colmun) - 1:
print(colmun[row], end="|")
else:
print(colmun[row], end="")
print()
def deposit():
amount = input("inter the amount of deposit you'd like to add ")
if amount.isdigit():
amount = int(amount)
while amount > 0:
break
else: print("amount must be more than 0")
else: print("Please enter a number ")
return amount
def get_number_of_lines():
lines = input("inter the amount of lines you'd like to add ")
if lines.isdigit():
lines = int(lines)
while MIN_LINES <= lines <= MAX_LINES:
break
else: print("amount must be between 1~3")
else: print("Please enter a number ")
return lines
def get_bet():
while True:
amount = input("Inter the amount of deposit you'd like to bet \n")
if amount.isdigit():
amount = int(amount)
while MIN_BET <= amount <= MAX_BET:
break
else:
print(f"The amount must be between ${MIN_BET}and ${MAX_BET}\n ")
else:
print("Please enter a number ")
return amount
def main():
balance = deposit()
lines = get_number_of_lines()
while True:
bet = get_bet()
total_bet = bet *lines
if total_bet> balance:
print(f"you dont have enough to bet on that amount , your current balance is {balance}")
else:
break
print(f"you're betting {bet},on {lines} lines . total bet is = ${total_bet}")
slots = get_slot_machine_spin(ROW, COL,symbol_count)
print_slot_machine(slots)
main()
I tried changing the two lines in many different ways but it didnt work plz help
slots = get_slot_machine_spin(ROW, COL,symbol_count)
print_slot_machine(slots)
i got this code from a utube video called (Learn Python With This ONE Project!) i wrote the same code as but when he excute the code it shows him the Slot machine results ( abcd ) while am not getting it , i hope my question was clear ,,, all i want is to make the functions work and show the results of the random choices
Your problems are all in the get_slot_machine_spin function. Did you ever do a basic debug print of what it returns? You would have immediately seen that it was wrong.
Look at what you're asking. You're creating columns with three empty lists. You then generate a random thing and add it to THAT list, So, after three runs, you'd have [[], [], [], 'A', 'C', 'D']. Then you append THAT list to ITSELF, and repeat. When you see something like columns.append(columns), that's an immediate indication that something is wrong.
You need to create a separate list to hold the individual column values, then you append that list to your master column list, which should start out empty. Like this:
def get_slot_machine_spin(rows,cols,symbols):
all_symbols = []
for symbol , symbol_count in symbols.items():
for _ in range(symbol_count):
all_symbols.append(symbol)
columns = []
for _ in range(cols):
row = []
current_symbols = all_symbols[:]
for _ in range(rows):
value = random.choice(current_symbols)
current_symbols.remove(value)
row.append(value)
columns.append(row)
print(columns)
return columns
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'm building a command line game using python.A main feature of this game is to get the user's input of either 1 or 2 as integer values.Any other character must be rejected.I used try-except & if-else condition to do this like shown below.I want to know whether there is any better method to get this done in one line or some other way without having to indent a whole bunch of code.
if __name__ == '__main__':
# INITIALIZE THE TOTAL STICKS , DEPTH OF THE TREE AND THE STARTINGG PLAYER
i_stickTotal = 11 # TOTAL NO OF STICKS IN THIS GAME
i_depth = 5 # THE DEPTH OF THE GOAL TREEE THE COMPUTER WILL BUILD
i_curPlayer = 1 # THIS WILL BE +1 FOR THE HUMAN AND -1 FOR THE COMPUTER
print("""There are 11 sticks in total.\nYou can choose 1 or 2 sticks in each turn.\n\tGood Luck!!""")
# GAME LOOP
while i_stickTotal > 0:
print("\n{} sticks remain. How many would you pick?".format(i_stickTotal))
try:
i_choice = int(input("\n1 or 2: "))
if i_choice - 1 == 0 or i_choice - 2 == 0:
i_stickTotal -= int(i_choice)
if WinCheck(i_stickTotal, i_curPlayer):
i_curPlayer *= -1
node = Node(i_depth, i_curPlayer, i_stickTotal)
bestChoice = -100
i_bestValue = -i_curPlayer * maxsize
# Determine No of Sticks to Remove
for i in range(len(node.children)):
n_child = node.children[i]
#print("heres what it look like ", n_child.i_depth, "and",i_depth)
i_val = MinMax(n_child, i_depth-1, i_curPlayer)
if abs(i_curPlayer * maxsize - i_val) <= abs(i_curPlayer*maxsize-i_bestValue):
i_bestValue = i_val
bestChoice = i
#print("Best value was changed # ", i_depth, " by " , -i_curPlayer, " branch ", i, " to ", i_bestValue)
bestChoice += 1
print("Computer chooses: " + str(bestChoice) + "\tbased on value: " + str(i_bestValue))
i_stickTotal -= bestChoice
WinCheck(i_stickTotal, i_curPlayer)
i_curPlayer *= -1
else:
print("You can take only a maximum of two sticks.")
except:
print("Invalid input.Only Numeric Values are accepted")
You can create a function to check user input and use below code.
while True:
var = int(input('Enter value (1 or 2) - '))
if var not in range(1, 3):
print('Invalid entry, please try again...')
continue
else:
break
Write a function that loops, calling input, until the value satisfies your constraint. Perhaps call it get_user_input. Then call that in your main function instead of input. For added value, pass a lambda into that function as a predicate to test the user input value - that'll make get_user_input more general.
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.
Good day friends!
Tell me please, I have the following code:
all_users = UserProfile.objects.all()
for s,usera in enumerate(all_users):
name = usera.nickname
name_id = usera.id
print(s)
if int(s) <= 50:
print('1_iterator')
r = api.request(example)
elif int(s) <= 100:
r = api2.request(example)
elif #a total of seven compounds, api3,api4,api5,api6,api7
try:
for item in r.get_iterator():
#then loop adds data to the database
how do I get a cycle every 50 iterations connect to the new api, and if he reaches seven then again from the beginning, and so has not yet come to an end user in the database?
Advance thanks!
You could set up an itertools.cycle.
apis = itertools.cycle([api1, api2, api3, api4, api5, api6, api7])
for s,usera in enumerate(all_users):
if (s % 50) == 0:
current_api = apis.next()
name = usera.nickname
name_id = usera.id
print(s)
current_api.request(example)
...