(Python) There are no errors, but the program is not running - python

I need to calculate shipping costs based on package type, weight, and how many zones the delivery goes through. I didn't get all the hard numbers from him so I'm using some placements, but that shouldn't matter much. The problem is that even though no errors are listed, running the program only returns a blank page, no prompts to enter numbers or anything like that.
Here's the code.
def main():
packageType = input('Please enter the package type: ')
rate = 0
zoneRate = 0
if packageType == 1:
rate += 1.25
elif packageType == 2:
rate += 1.5
elif packageType == 3:
rate += 1.75
elif packageType == 4:
rate += 2
weight = input('Please enter the weight: ')
if weight <= 2:
rate += 3.10
elif weight > 2 and weight <= 6:
rate += 4.20
elif weight > 6 and weight <= 10:
rate += 5.30
elif weight > 10:
rate += 6.40
zones = input('Please enter how many zones are crossed: ')
if zones == 1:
zoneRate += 5
if zones == 2:
zoneRate += 10
if zones == 3:
zoneRate += 15
cost = rate * zoneRate
print(('The shipping cost is: '), cost)

You need to have
def main():
# all of your code
# goes here
main()

Related

Python change calculator

I need to create a program that will input a money amount in the form of a floating point number. The program will then calculate which dollars and coins to make this amount. Coins will be preferred in the least number of coins. If any of the values is zero, I need to not output the value. IE: if the change is 26 cents you only need to tell the user they will receive 1 quarter and 1 penny. No more, no less.
Below is what I have so far, the only thing I cant figure out is to make the program not output the zero values
# calculate amount of change needed
dollar = 100
quarter = 25
dime = 10
nickel = 5
penny = 1
def main():
calc = True
while calc:
lst = []
mon = ['dollars', 'quaters', 'dimes', 'nickels', 'pennys']
doll = 0
quart = 0
dimes = 0
nick = 0
pen = 0
total = int(float(input('Enter amount of change: '))*100)
amount = total
while amount - dollar >= 0:
amount -= dollar
doll += 1
while amount - quarter >= 0:
amount -= quarter
quart += 1
while amount - dime >= 0:
amount -= dime
dimes += 1
while amount - nickel >= 0:
amount -= nickel
nick += 1
while amount - penny >= 0:
amount -= penny
pen += 1
lst.append(doll)
lst.append(quart)
lst.append(dimes)
lst.append(nick)
lst.append(pen)
print('\nThe change owed is: ')
print(" ")
for i, e in zip(lst, mon):
print(i, e)
calc = input("\nPress 'Y' to try again or any other key to exit: ")
if calc != 'y' and calc != 'Y':
calc = False
if __name__ == "__main__":
main()
else:
pass
I ended up solving it
if doll >= 1:
lst.append(doll)
mon.append("dollars")
if quart >= 1:
lst.append(quart)
mon.append("quarters")
if dimes >= 1:
lst.append(dimes)
mon.append("dimes")
if nick >= 1:
lst.append("nickles")
if pen >= 1:
lst.append(pen)
mon.append("pennies")
this seems to have worked

I don't know what is wrong with my condition statements

Its not working this is what I am trying to do.
finding out the tax of a person and subtract some based on their status and dependents my expected output is the user will enter its income then will multiply how much tax will be deducted and will also deduct some based on their status and how many dependents
They have:
Income: 500000
Status: Married
Dependents= 3
Tax = 25000
income = float(input("your income: "))
if income <= 100000:
initialIncome = income * .5
elif income in range (100001,250000):
initialIncome = income * .10
elif income in range (250001,500000):
initialIncome = income * .15
elif income >= 500001:
initialIncome = income * .20
status = input("status (s,m,w,d) ")
if status == "S":
S = 10000
elif status == "M":
S = 20000
elif status == "W":
S = 10000
elif status == "D":
S = 30000
dependents = float(input("dependents num: "))
if dependents >= 5:
dependentsPrice = 50000
if dependents <= 5:
dependentsPrice = 10000 * dependents
totalTax = initialIncome - (status + dependents)
print(totalTax)
Code:
You are using status in totalTax instead of S.
You must add .upper() to convert all the input strings to upper case as you have used uppercase in if statements.
income = float(input("your income: "))
if income <= 100000:
initialIncome = income * .5
elif income in range (100001,250000):
initialIncome = income * .10
elif income in range (250001,500001):
initialIncome = income * .15
elif income >= 500001:
initialIncome = income * .20
else:
print("Invalid input")
initaialIncome = 0
# Here you must add upper to convert all the strings to upper case
status = input("status (s,m,w,d) ").upper()
#To prevent undefined error
S =
if status == "S":
S = 10000
elif status == "M":
S = 20000
elif status == "W":
S = 10000
elif status == "D":
S = 30000
#In case user enters wrong input.
else:
print("Invalid input")
dependents = float(input("dependents num: "))
if dependents >= 5:
dependentsPrice = 50000 *dependents
if dependents <= 5:
dependentsPrice = 10000 * dependents
# Here status is string. I suppose you are trying to use S.
#here use dependsPrice
totalTax = initialIncome - (S + dependentsPrice)
print(totalTax)

Why are my replys looping instead of whole program

can someone help me troubleshoot my code the reply from going through the code at the end just loops instead of begining the program again completely would be brilliant is someone could help me thanks and i know its very basic and maybe not the best way to do it but as long as it works its fine.
start = input("Do you want to make an order? ")
while start == "Y" or start == "y" :
title = input("Enter book title: ")
sPrice = float(input("Enter price of book: "))
voucher = input("Do you have a voucher? ")
while sPrice >0 :
amount = float(input("Enter amount of books: "))
while amount >= 1 and amount <= 80 :
if amount >= 5 and amount <= 10 :
disc = 5
elif amount >= 11 and amount <= 50 :
disc = 7.5
elif amount >= 51 and amount <= 80 :
disc = 10
else :
disc = 0
base = sPrice * amount
discVal = (base * disc) / 100
dPrice = base - discVal
if voucher == "Y" or voucher == "y" and dPrice >= 25 :
voucherValue = 25
else :
voucherValue = 0
fPrice = dPrice - voucherValue
print (f"Discount rate: {disc}%")
print (f"Discount value: £{discVal:.2f}")
print (f"Total before discount: £{base:.2f}")
print (f"Total after discount: £{dPrice:.2f}")
if voucher == "Y" or voucher == "y" and dPrice >= 25 :
print (f"Value of voucher: £{voucherValue:.2f}")
print (f"Final cost of order: £{fPrice:.2f}")
else :
print ("ERROR - Invalid amount!")
amount = float(input("Enter amount of books: "))
else :
print ("ERROR - Price too low!")
sPrice = float(input("Enter price of book: "))
else :
start = input("Do you want to make an order? ")
You need to include if at two place just to validate the input value.
Change while sPrice >0 : to if sPrice >0 : and line while amount >= 1 and amount <= 80 : to if amount >= 1 and amount <= 80 :

Where to place sys.exit() for termination of code

It's a beginner python program where we are given a menu and user gets to choose which item from 1-5 and 6 to exit. If they choose 6, it would terminate the code, don't ask any other questions and do not show the bill.
I thought placing it at the "elif choice == 6" would work but then it ends the whole code without considering the other previous choices
def get_inputs():
'''get input of each of the burger choices of the user and how much did they want'''
count = 0
quantity1 =quantity2=quantity3=quantity4=quantity5 = 0
flag = True
while flag:
check_choice = True
while check_choice:
try:
choices=int(input("Enter kind of burger you want(1-5 or 6 to exit): ").strip())
if choices <=0:
print("Enter a positive integer!")
else:
check_choice = False
except:
print("Enter valid numeric value")
check_quantity = True
while check_quantity and choices != 6:
try:
quantity = int(input("Enter quantity of burgers wanted: "))
if quantity <=0:
print("Enter a positive integer!")
else:
count +=1
check_quantity = False
except:
print("Enter valid numeric value")
if choices == 1:
quantity1 = quantity
elif choices == 2:
quantity2 = quantity
elif choices == 3:
quantity3 = quantity
elif choices == 4:
quantity4 = quantity
elif choices == 5:
quantity5 = quantity
elif choices == 6:
flag = False
check_staff = True
while check_staff and count !=0:
try:
tax = int(input("Are you a student? (1 for yea/0 for no)"))
check_staff = False
except:
print("Enter 1 or 0 only")
return quantity1,quantity2,quantity3,quantity4,quantity5,tax
def compute_bill(quantity1,quantity2,quantity3,quantity4,quantity5,tax):
'''calculate the total amount of the burgers and the total price of the purchase'''
total_amount = tax_amount = subtotal = 0.0
student_tax = 0
subtotal = (quantity1 * DA_PRICE) + (quantity2 * BC_PRICE) + (quantity3 * MS_PRICE) + (quantity4 * WB_PRICE) + (quantity5 * DCB_PRICE)
if(tax == 0):
tax = float(STAFF_TAX)
tax_amount = subtotal *(tax/100)
total_amount = subtotal + tax_amount
elif(tax == 1):
total_amount = subtotal+student_tax
return tax_amount, total_amount, subtotal
Expected: when starting the program and pressing 6, it will terminated without asking any other questions and also without showing the bill
Expected: code would get user's input and then when pressing 6, it will continue on to comput_bill function and compute/print the bill
Actual results: when pressing 6 at the beginning, in get_inputs, in the return statement, the local variable "tax" is referenced before assignment
You can just do the loop and when you get a 6 you exit the loop. If there has been no inputs, then skip the student check and the bill calculation.
This is much cleaner than trying to use flag variables to check whether you should print.
Using sys.exit. Is quite a brutal way to terminate your program. It's usually best to delegate the decision to terminate to the outermost functions in your application. It's also better to let the program terminate naturally by reaching the end of the program.
You might use sys.exit for things like incorrect command line arguments.
# example prices.
unitprices = {
1: 7.89, # DA_PRICE
2: 11.00, # BC_PRICE
3: 9.50,
4: 15.85,
5: 21.00
}
STAFF_TAX = 0.2
def calcbill(units, istaxable, unitprices=unitprices, taxrate=STAFF_TAX):
subtotal = 0
for u in units:
subtotal += unitprices[u]
if istaxable:
tax_amount = subtotal * (taxrate / 100)
else:
tax_amount = 0
return (subtotal + tax_amount, tax_amount)
entries = []
print("Enter kind of burger you want(1-5 or 6 to exit): ")
while True:
try:
choice = int(input("what is the next burger? "))
if choice == 6:
break
elif 0 < choice < 6:
entries.append(choice)
else:
print('invalid choice')
except:
print('not a number')
if entries:
while True:
s = input('Are you a student? ').lower()
if s in ('y', 'yes', 'true'):
isstudent = True
break
elif s in ('n', 'no', 'false'):
isstudent = False
break
else:
print('not a valid value')
total, tax = calcbill(entries, not isstudent)
print(f'the bill was ${total:.2f} which includes ${tax:.2f} tax')
As far as I understood from the expected output, you want to exit the code in the following scenarios:-
(1) At the beginning of the code, when there is no value in the kind of the burger, just exit the code, without prompting the user to input again.
(2) After saving some values in the burger count, if the user pressed 6, then also it should not ask the user for the price calculation logic.
If my understanding is right, then you should update your code in the following manner:-
if choices == 1:
quantity1 = quantity
elif choices == 2:
quantity2 = quantity
elif choices == 3:
quantity3 = quantity
elif choices == 4:
quantity4 = quantity
elif choices == 5:
quantity5 = quantity
elif choices == 6:
check_choices = False
flag = False
import sys
sys.exit()
And the output is as follows:-
(.test) [nikhilesh#pgadmin]$ python3 1.py
Enter kind of burger you want(1-5 or 6 to exit): 1
Enter quantity of burgers wanted: 2
Enter kind of burger you want(1-5 or 6 to exit): 6
(.test) [nikhilesh#pgadmin]$ python3 1.py
Enter kind of burger you want(1-5 or 6 to exit): 6
(.test) [nikhilesh#pgadmin]$ python3 1.py
Enter kind of burger you want(1-5 or 6 to exit): 1
Enter quantity of burgers wanted: 4
Enter kind of burger you want(1-5 or 6 to exit): 6
(.test) [nikhilesh#pgadmin]$

Roulette Program - Adding up the cash

Python 3.5
I have a project for a class to create a Roulette wheel minigame and I'm having issues. I set the initial cash to $100 and let the user play roulette. After they've given their wager and it's time to tally up the cash for the next round, I'm having issues setting the new cash value. Basically, I need to add the winnings/losings to the value of cash so that it's accurately updated for the next round. I know that declaring cash as a global variable is wrong, but we haven't learned the proper way to do it and haven't had time to check it out for myself. Anyways, the issue is near the bottom. Thank you for any help! -
import math
import random
def main():
global cash
print('Welcome to Roulette! We\'ll start you with $100')
cash = 100 #set to 100 for intitial
menu()
def menu():
print('Place your bet! ',cash,'bucks!', '''
=======================================
1. Bet on Red (pays 1:1)
2. Bet on Black (pays 1:1)
3. First 12 (pays 2:1)
4. Middle 12 (pays 2:1)
5. Last 12 (pays 2:1)
6. Choose any number (pays 35:1)
7. Cash out
Please enter your choice: ''')
menuChoice = int(input())
#Add validation!!!!!!!!!!!!!!!!!!!!!!!!!!!!
if cash > 0 and menuChoice != 7: #Determine if quit or broke
if menuChoice == 6:
number = int(input('Please choose a number from 0-36!')) #Get their specific number
while number < 0 or number > 36: #Validation
number = int(input('Please enter a number from 0-36'))
wager = int(input('How much would you like to bet? '))
#Add validation!!!!!!!!!!!!!!!!!!!!!!!!!!!!!
print('Press any key to spin the wheel! ')
input()
print(menuChoice, wager)
##
## ball = random.randint(0,36)
ball = 19 #set to 19 for testing. REMOVE AND RESET BALL!!!!!!!!!!!!!!!!!
if ball == 0:
color = ('green')
elif ball % 2 == 0:
color = ('black')
else:
color = ('red')
print('Your ball was',ball, 'and landed on the color',color)
#Determine if winner
if menuChoice == 1 and color == 'red':
winner = True
odds = 1
elif menuChoice == 2 and color == 'black':
winner = True
odds = 2
elif menuChoice == 3 and ball >= 1 and ball <= 12 :
winner = True
odds = 2
elif menuChoice == 4 and ball >= 13 and ball <= 24:
winner = True
odds = 2
elif menuChoice == 5 and ball >= 25 and ball <= 36:
winner = True
odds = 2
elif menuChoice == 6 and ball == number:
winner = True
odds = 35
else:
winner = False
odds = 0
#End determine if winner
if odds == 0:
pass
else:
amount = wager * odds #Get amount won/lost
print(amount)
if winner == True:
cash += amount #<~~~~~~~~~~~~~Problem Area
print('Congratulations! You won', wager,'dollars!')
print('Your total is now :',cash,'dollars.')
else:
cash -= wager
print('Sorry! You lost',wager,'dollars. Better luck next time!')
print('Your total is now :',cash,'dollars.')
input('Press a key to go back to the menu!')
print('====================================================================')
#New round
menu()
else:
print('Thank you for playing! ')
exit
main()
You could create your own python class, with the methods you already have. Than you can declare cash a class variable, with the parameter self. With self.cash you can than access the variable in every method. If that does not help please comment this answer with your issue.

Categories

Resources