I'm having trouble with the code where the budget variable wasn't deducting throughout the loop. It instead do nothing or sometimes add up - queue

enter image description hereI'm making an inventory system code and I'm a bit stuck finding a solution to the substraction problem, when I choose "ADD" and entering the input the formula wasn't getting the accurate outcome. For example, if I input Paper001 then its quantity, the output is fine at first but when input another item, the deduction instead becoming addition or sometimes doesn't do anything.
I tried dividing the values in the dictionary in 3 conditions but it turns out even worse.
while True:
try:
bg = float(input("Enter your budget : "))
print("-----------------------------------------------------------")
print(" Item name Item code Item price(Per set) \n")
print("1.Bond Paper : Paper001 100 PHP\n2.Yellow Paper : Paper002 50 PHP\n3.Intermediate Paper : Paper003 20 PHP\n\n")
s = bg
except ValueError:
print("PRINT NUMBER AS A AMOUNT")
continue
else:
break
a ={"name":[], "quant":[], "price":[]}
# converting dictionary to list for further updation
b = list(a.values())
# variable na value of "name" from dictionary 'a'
na = b[0]
# variable qu value of "quant" from dictionary 'a'
qu = b[1]
# This loop terminates when user select 2.EXIT option when asked
# in try it will ask user for an option as an integer (1 or 2)
# if correct then proceed else continue asking options
while True:
try:
print("-----------------------------------------------------------")
ch = int(input("1.ADD\n2.STORAGE LIST\n3.Customer purchase\n4.EXIT\nEnter your choice : "))
except ValueError:
print("\nERROR: Choose only digits from the given option")
continue
else:
# check the budget is greater than zero and option selected
# by user is 1 i.e. to add an item
if ch == 1 and s>0:
p_list={'Paper001':100,'Paper002':50,'Paper003':20}
pn = input("Enter item code : ")
if pn in p_list.keys():
q = int(input("Enter quantity : "))
else:
print("-----------------------------------------------------------")
print("Code is invalid")
continue
#checks if item name is already in the list
if pn in na:
ind = na.index(pn)
# remove quantity from "quant" index of the product
qu.remove(qu[ind])
# new value will be added to the previous value of user's quantity
qu.insert(ind, q)
tpr = (q+q)*p_list[pn]
print(f" Total product price:",tpr)
s = bg-tpr
print("\namount left", s)
else:
# append value of in "name", "quantity", "price"
na.append(pn)
# as na = b[0] it will append all the value in the
# list eg: "name"🙁"rice"]
qu.append(q)
# after appending new value the sum in price
# as to be calculated
tpr = q*p_list[pn]
print("\nTotal product price:",tpr)
s = bg-tpr
if s==0:
print("No more budget left")
print("\nAmount left :", s)
elif s>0:
print("\nAmount left :", s)
else:
print("Insufficient budget. Cannot buy item.")
print("Please restart and re-enter your budget.")
break
elif ch ==2 :
print("\n\n\nStorage list")
print("Item name Stocks ")
for i in range(len(na)):
print(f"{na[i]} {qu[i]}")
continue
elif ch == 3:
print("-----------------------------------------------------------")
p_list={'Paper001':100,'Paper002':50,'Paper003':20}
print("\n\n\nStorage list")
print("Item name Stocks ")
for i in range(len(na)):
print(f"{na[i]} {qu[i]}")
co = input("\nEnter customer's order : ")
if co in p_list.keys():
q = int(input("Enter quantity : "))
sl = qu[i]-q
print("Item is sold!")
print("Stocks left :",sl)
if sl <=0:
print("Please add new items!")
else:
print("-----------------------------------------------------------")
print("Code is invalid")
continue
elif ch==4:
print("")
print("\nThank your for shopping with us!")
break
elif s==0:
print("NO BUDGET LEFT. UNABLE TO ADD ITEMS.")
else:
print("ERROR: Choose only the digits given from the option.")

Related

I have a string and a number. I need to find the first sub-string that contain the same characters with the length of the number

For example:
number= 3
my_string= "gghhsstttevvv"
The output:
"ttt"
*if the number was 2, the output is: "gg"
The below script will give you the desired output :
number = input("Enter Number")
string = input("Enter String")
count = dict.fromkeys(string,0)
for i in string:
count[i] += 1
#print(count)
occurences = count.values()
#print(occurences)
result = [k for k,v in count.items() if v == int(number)]
if not result:
print("No matching substring of length " +number+ " found")
else:
print(result) # To print all the characters with the given count
print(result[0]) # To print the first character with the given count
output_char = result[0]
frequency = count[output_char]
output_char = output_char*frequency
print(output_char)
Output:
python3 string.py
Enter Number5
Enter Stringgghhsstttevvv
No matching substring of length 5 found
python3 string.py
Enter Number3
Enter Stringgghhsstttevvv
['t', 'v']
t
ttt

Displaying multiple values in for statement in Swift

Hi I am new to programming. I apologize beforehand if this is a stupid question, but I'm learning about For loops. The below is an example code I understand. I know how to write a basic For loop that iterates through a single variable in each loop, but how do I use a For loop to display multiple values in one loop. Example:
let treeArray = ["Pine", "Oak", "Yew", "Maple", "Birch", "Myrtle"]
for tree in treeArray {
print(tree)
}
I want to be able to print three variables in one loop so the code would print
Pine Oak Yew on one line
Maple Birch Myrtle and on the next
Instead of
Pine
Oak
Yew
Maple
Birch
Myrtle
Thanks!
You could use .enumerated() to pair the index with the element and then print(_:terminator:) using index % 3 to select the appropriate terminator (newline "\n" or space " "):
let treeArray = ["Pine", "Oak", "Yew", "Maple", "Birch", "Myrtle"]
for (index, tree) in treeArray.enumerated() {
print(tree, terminator: index % 3 == 2 ? "\n" : " ")
}
Output:
Pine Oak Yew
Maple Birch Myrtle
The general case: printing n items per line
In general, for printing n items per line:
print(tree, terminator: index % n == n - 1 ? "\n" : " ")
or equivalently:
print(tree, terminator: (index + 1) % n == 0 ? "\n" : " ")
If you want the last item to always be followed by a newline, then add an addition check for that:
print(tree, terminator: index % n == n - 1 || index == treeArray.endIndex - 1 ? "\n" : " ")
Use an array to store trees and
joined(separator: String)
on array to stitch them together.
let treeArray = ["Pine", "Oak", "Yew", "Maple", "Birch", "Myrtle"]
var treeNames = [String]()
for (count, tree) in treeArray.enumerated() {
treeNames.append(tree)
if ((count + 1) % 3) == 0 {
let treeLine = treeNames.joined(separator: " ")
print(treeLine)
treeNames.removeAll()
}
}

Why doesn't function loop, loop on input?

I want to use the function serial_circuit with three different inputs (1,2,3). The function is suppose to accept multiple inputs from user until
user hits return, end program and sums up all inputs. The program only takes one input and display it.
def serial_circuit(num1):
num = 0
while(True):
try:
num += num1
except:
break
return num
print("1.Solve for serial resistance: ")
print("2.Solve for serial coils: ")
print("3.Solve for parallel capacitors: ")
choice = input("Enter choice: ")
if choice == '1':
num1 = float(input("Enter resistor value: "))
num = serial_circuit(num1)
print(f"Total resistance = {(num)} ohms")
elif choice == '2':
num1 = float(input("Enter coil value: "))
num = serial_circuit(num1)
print(f"Total inductance = {(num)} henrys")
elif choice == '3':
num1 = float(input("Enter capacitor value: "))
num = serial_circuit(num1)
print(f"Total capacitance = {(num):.6f} farads")
One of your problems is that you have the return statement inside the loop - notice your indentation - during the first iteration of the loop the last thing that will happen within the loop is returning from the serial_circuit function.
Another problem is that you are asking for the input only once - outside of the loop.
Take a look at this solution:
def serial_circuit(text):
num = 0
finishedEntering = False
while(not finishedEntering):
try:
received_input = input(text)
if received_input == "":
finishedEntering = True
else:
num1 = float(received_input)
num += num1
except:
break
return num
print("1.Solve for serial resistance: ")
print("2.Solve for serial coils: ")
print("3.Solve for parallel capacitors: ")
choice = input("Enter choice: ")
if choice == '1':
num = serial_circuit("Enter resistor value or hit enter to finish: ")
print(f"Total resistance = {(num)} ohms")
elif choice == '2':
num = serial_circuit("Enter coil value or hit enter to finish: ")
print(f"Total inductance = {(num)} henrys")
elif choice == '3':
num = serial_circuit("Enter capacitor value or hit enter to finish: ")
print(f"Total capacitance = {(num):.6f} farads")

find out min and max in python 3

5.2 Write a program that repeatedly prompts a user for integer numbers until the user enters 'done'. Once 'done' is entered, print out the largest and smallest of the numbers. If the user enters anything other than a valid number catch it with a try/except and put out an appropriate message and ignore the number. Enter 7, 2, bob, 10, and 4 and match the output below.
largest = None
smallest = None
while True:
num = input("Enter a number: ")
if num == "done":
break
print(num)
print("Maximum", largest)
and the output must be like this
Invalid input
Maximum is 10
Minimum is 2
somebody please help me with this????? enter image description here
I think this will do your work,
With simple if conditions
# Defining two variables to None.
largest = None
smallest = None
# starting an infinite loop
while True:
num = input("Enter a number: ")
# try block to capture ValueError
try:
if num == "done":
break
# assign the values of largest and smallest to num if its None ( on first iteration)
if largest is None:
largest = int(num)
if smallest is None:
smallest = int(num)
# changing the values of it greater or smaller
if int(num) > largest:
largest = int(num)
if int(num) < smallest:
smallest = int(num)
# capture the type error and ignores.
except ValueError:
print("ignored.")
continue
print("Maximum: " + str(largest))
print("Minimum: " + str(smallest))
By making use of list and it's methods
# Defining an empty list.
myList = []
# starting an infinite loop
while True:
num = input("Enter a number: ")
# try block to capture ValueError
try:
if num == "done":
break
# append the entered number to list if valid
myList.append(int(num))
# catches value error and ignores it
except ValueError:
print("ignored.")
continue
# prints maximum and min
if len(myList) > 0:
print("Maximum: " + str(max(myList)))
print("Minimum: " + str(min(myList)))
else:
print("List is empty")
largest = None
smallest = None
while True:
try:
num = input("Enter a number: ")
if num == "done":
break
num = int(num)
if largest is None or largest < num:
largest = num
elif smallest is None or smallest > num:
smallest = num
except ValueError:
print("Invalid input")
print ("Maximum is", largest)
print ("Minimum is", smallest)
largest = None
smallest = None
while True:
num = input("Enter a number: ")
if num == "done" :
break
try:
n = int(num)
except:
print ('Invalid input')
continue
if largest is None or n > largest:
largest = n
if smallest is None or n < smallest:
smallest = n
print("Maximum is", largest)
print("Minimum is", smallest)
#Print out largest and smallest number
largest=None
smallest=None
while True:
n = input('Enter a number: ')
if n == "done":
break
try:
num=int(n)
if largest is None:
largest = num
elif num > largest:
largest = num
if smallest is None:
smallest = num
elif num < smallest:
smallest = num
except:
print("Invalid input")
print('maximum:', largest)
print('Minimum:', smallest)

BlackJack(Python): Adding the "HIT" card value

I'm writing a code for blackjack in python. So far I've gotten as far as dealing the two initial cards for the player. If it is a natural win, the program identifies it and prints "BlackJack!". If it there is a possibility for a hit then it prompts the user "Hit or Stand? H\S. I am having trouble figuring out how to add the value of that "hit" card to the value of the first two cards.
Here's my code:
import random
def create_hand(hand):
for i in range(2):
pip = random.choice(PIPS)
suit = random.choice(SUITS)
card = (pip,suit)
player_hand.append(card)
def print_hand(hand):
for pip, suit in hand:
print(pip + suit,end=" ")
print()
def sum_hand(hand):
total = 0
for pip,suit in player_hand:
if pip == "J" or pip == "Q" or pip == "K":
total += 10
elif pip == "A" and total < 10:
total += 11
elif pip == "A" and total == 10:
total +=11
elif pip == "A" and total > 10:
total += 1
else:
total += int(pip)
if total == 21:
print("BlackJack!")
return total
def hit_card():
pip = random.choice(PIPS)
suit = random.choice(SUITS)
card = (pip, suit)
return card
def hit(player_hand):
total = sum_hand(player_hand)
choice = input("Hit or Stand? h/s: ")
while choice.lower() == "h":
if total != 21:
player_hand.append(hit_card())
print_hand(player_hand)
CLUB = "\u2663"
HEART = "\u2665"
DIAMOND = "\u2666"
SPADE = "\u2660"
PIPS = ("A","2","3","4","5","6","7","8","9","10","J","Q","K")
SUITS = (CLUB, SPADE, DIAMOND, HEART)
player_hand = []
total = sum_hand(player_hand)
create_hand(player_hand)
print_hand(player_hand)
hit(player_hand)
Strings are for humans: computers use numbers, so my first advice is to represent cards with numbers instead of strings. Will make code simpler and faster.
But, given your existing strings, and your "hand" being a list of cards, hitting is just appending another card. You then just need a better sum_hand() function to total the hand, however many cards are in it. Something like this:
def sum_hand(hand):
total = 0
acefound = False
for card in hand:
pip = card[0]
if ("A" == pip):
total += 1
acefound = True
elif (pip in [ "J", "Q", "K", "10" ]):
total += 10
else:
total += int(pip)
if (acefound and total < 12):
return True, total + 10
return False, total
It's important to get not only a numeric total, but the soft/hard as well, because that can deterimine future actions. So you use this function like:
soft, total = sum_hand(theHand)
And go from there.