Having issues with python functions - python

I am making a couple of functions for taking pizza information in one, then using that information to calculate the price in the other function. When I run this though, it's having problems locating attributes in one of the functions, even after its run.
def calc_pizza_charge(size_cost, meats_cost, veg_cost, num_cost):
get_pizza_info.size = range(1, 4)
num_cost = get_pizza_info.quantity
total = (size_cost + meats_cost + veg_cost) * get_pizza_info.quantity
if get_pizza_info.size == 1:
size_cost = 6.50
if get_pizza_info.size == 2:
size_cost = 9.50
if get_pizza_info.size == 3:
size_cost = 11.50
meats_cost = (get_pizza_info.meats - 1) * 3.50
veg_cost = (get_pizza_info.veg - 1) * 1.50
print("Your total is $", "{:,.2f}".format(total))
def get_pizza_info(size, meats, veg, quantity):
size = int(input("Enter size from 1-3: "))
meats = int(input("Enter number of meat toppings "))
veg = int(input("Enter number of non-meat toppings "))
quantity = int(input("Enter number of these pizzas "))
if size >= 4:
size = 3
if size <= 1:
size = 1
if meats <= 1:
meats = 1
if veg <= 1:
veg = 1

Since you are not comfortable with other answers, Here a working code with minimal modifications to your code
def calc_pizza_charge():
size, meats, veg, quantity = get_pizza_info()
if size == 1:
size_cost = 6.50
elif size == 2:
size_cost = 9.50
else:
size_cost = 11.50
meats_cost = (meats - 1) * 3.50
veg_cost = (veg - 1) * 1.50
total = (size_cost + meats_cost + veg_cost) * quantity
print("Your total is $", "{:,.2f}".format(total))
def get_pizza_info():
size = int(input("Enter size from 1-3: "))
meats = int(input("Enter number of meat toppings "))
veg = int(input("Enter number of non-meat toppings "))
quantity = int(input("Enter number of these pizzas "))
if size >= 4:
size = 3
elif size <= 1:
size = 1
if meats <= 1:
meats = 1
if veg <= 1:
veg = 1
return size, meats, veg, quantity
if __name__ == '__main__':
calc_pizza_charge()

To be honest, I was extremely confused when I saw your code. I think you should review how functions work. Anyway, a few pointers:
In get_pizza_info you essentially ask for the order details: store it in some sort of data structure (I used dictionary)
In get_pizza_charge, you need to use the order details to compute the price of the pizza.
I have included my rewriting of your code:
def calc_pizza_charge():
pizza_info = get_pizza_info()
num_cost = pizza_info["quantity"]
size_cost = get_size_cost(pizza_info["size"])
meats_cost = (pizza_info["meats"] - 1) * 3.50
veg_cost = (pizza_info["veg"] - 1) * 1.50
total = (size_cost + meats_cost + veg_cost) * pizza_info["quantity"]
print("Your total is $", "{:,.2f}".format(total))
def get_size_cost(size):
if size == 1:
return 6.5
elif size == 2:
return 9.5
elif size == 3:
return 11.50
def get_pizza_info():
size = int(input("Enter size from 1-3: "))
meats = int(input("Enter number of meat toppings "))
veg = int(input("Enter number of non-meat toppings "))
quantity = int(input("Enter number of these pizzas "))
pizza_info = {}
pizza_info["size"] = max(min(size, 3), 1)
pizza_info["meats"] = max(1, meats)
pizza_info["veg"] = max(1, veg)
pizza_info["quantity"] = max(0, quantity)
return pizza_info
calc_pizza_charge()

You have defined all the attribute variables in get_pizza_info function and are trying to access them in calc_pizza_charge function.
Variables declared in a function are local to that function and cannot be accessed by any entity outside that function.
For your problem I would suggest defining a new class that contains both of these functions.
class Pizza:
def calc_pizza_charge(self):
num_cost = self.quantity
if self.size == 1:
size_cost = 6.50
if self.size == 2:
size_cost = 9.50
if self.size == 3:
size_cost = 11.50
else:
size_cost = 10
meats_cost = (self.meats - 1) * 3.50
veg_cost = (self.veg - 1) * 1.50
total = (size_cost + meats_cost + veg_cost) * self.quantity
print("Your total is $", "{:,.2f}".format(total))
def get_pizza_info(self):
self.size = int(input("Enter size from 1-3: "))
self.meats = int(input("Enter number of meat toppings "))
self.veg = int(input("Enter number of non-meat toppings "))
self.quantity = int(input("Enter number of these pizzas "))
if self.size >= 4:
self.size = 3
if self.size <= 1:
self.size = 1
if self.meats <= 1:
self.meats = 1
if self.veg <= 1:
self.veg = 1
piz = Pizza()
piz.get_pizza_info()
piz.calc_pizza_charge()
This code runs fine just like you wanted it to work. There were many fundamental mistakes in your code. I would suggest you to learn basics of functions and classes in Python.

Related

Lottery win predictor

I am a beginner in Python and I think I need some help with my program. Any kind of help or advice would be appreciated:)
You can see the program below, when I run it it gets stuck on the part of comparing the random ticket with the winning ticket(win_combination).
from random import choice
#Winning ticket
win_combination = input("Enter the winning combination of 4 numbers(1-digit-numbers): ")
while len(win_combination) != 4:
if len(win_combination) > 4:
win_combination = input("Reenter a shorter combination(4 one-digit-numbers): ")
elif len(win_combination) < 4:
win_combination = input("Reenter a longer combination(4 one-digit-numbers): ")
print(f"Winning combination is {win_combination}.")
#Specifying range of numbers to choose from
range = range(0, 10)
#Making a fake comparison-ticket to start of the loop
random_ticket = [0, 0]
random_ticket_string = f"{random_ticket[0]}{random_ticket[1]}{random_ticket[2]}{random_ticket[3]}"
#Params for the loop
n_tries = 0
n_guesses = 1
while random_ticket_string != win_combination:
while n_tries > 4:
random_ticket.clear()
number = choice(range)
random_ticket.append(number)
n_tries += 1
n_guesses += 1
random_ticket_string = f"{random_ticket[0]}{random_ticket[1]}"
if random_ticket_string == win_combination:
chance_to_win = f"{(1 / n_guesses) * 100}%"
print("Estimated percent to win is " + chance_to_win + ", it took " + f"{n_guesses} to match the winning combination.")
else:
n_tries = 0

pylint reports => test.py:32:8: W0104: Statement seems to have no effect (pointless-statement)

This code I wrote for a school assignment. I checked the code with pylint, and pylint reports pointless-statement for all if elif else statements. I don't know how to improve my code, is there someone who could help me out? Thanks
USD = 0.8500
GBP = 1.1700
JPY = 0.0077
RATE = 0.015
FEE_MIN = 2.00
FEE_MAX = 15.00
choise = int(input("Which currency do you want to exchange for euros? "
"1) USD dollar,2) GB pound, 3) JP yen : "))
#USD
if (choise) == 1:
foreign = round(float(input("What amount of dollars do you want to convert"
" to euros? : ")))
euros = round((foreign * USD), 2)
COST = (round((foreign * USD), 2) * RATE)
if COST <= FEE_MIN:
COST = FEE_MIN
elif COST > FEE_MAX:
COST = FEE_MAX
else:
COST
payout = (float(euros) - float(COST))
print("The transactioncost are: {:.2f}.".format(COST))
print("You'll receive {:.2f} euros.".format(payout))
#GBP
if (choise) == 2:
foreign = round(float(input("What amount of pounds do you want to convert"
" to euros? : ")))
euros = round((foreign * GBP), 2)
COST = (round((foreign * GBP), 2) * RATE)
if COST <= FEE_MIN:
COST = FEE_MIN
elif COST > FEE_MAX:
COST = FEE_MAX
else:
COST
payout = (float(euros) - float(COST))
print("The transactioncost are: {:.2f}.".format(COST))
print("You'll receive {:.2f} euros.".format(payout))
#JPY
if (choise) == 3:
foreign = round(float(input("What amount of yen's do you want to convert"
" to euros? : ")))
euros = round((foreign * JPY), 2)
COST = (round((foreign * JPY), 2) * RATE)
if COST <= FEE_MIN:
COST = FEE_MIN
elif COST > FEE_MAX:
COST = FEE_MAX
else:
COST
payout = (float(euros) - float(COST))
print("The transactioncost are: {:.2f}.".format(COST))
print("You'll receive {:.2f} euros.".format(payout))
The problem is here:
else:
COST
Does nothing.

Python: Trying to approximate 'portion_saved' in the following code

#This part asks for the user input
annual_salary = float(input("Enter your annual salary:"))
#Declaring all the variables
total_cost = 1000000
High = 1.0
Low = 0.0
portion_saved = (High +Low)/2.0
semi_annual_raise = 0.07
r = 0.04 #annual investment return
portion_down_payment = 0.25
num_guesses = 0
epsilon = 100
total_saving = 0.0
months = 0
#Calculations next
while abs(total_cost - total_saving) >= epsilon:
num_guesses += 1
total_saving = 0.0
while total_saving < (total_cost*portion_down_payment):
monthly_salary = annual_salary/12
monthly_saving = monthly_salary*portion_saved
total_saving += (monthly_saving + total_saving*r/12)
months += 1
if months%6 == 0:
annual_salary += annual_salary*semi_annual_raise
if (total_saving < total_cost):
Low = portion_saved
else:
High = portion_saved
portion_saved = (Low+High)/2.0
print("Best savings rate:", portion_saved)
print("Number of steps:", num_guesses)
But the code enters an infinite loop. When checked using a print command, it turns out that the 'portion_saved' variable takes the value 1.0 on each iteration. But I can't figure out why is this happening. Can someone help?
your code always goes into the if statement, so you are always setting Low to be portion_saved:
1: Low = 0, portion_saved= 1/2
2: Low = 1/2, portion_saved= 1.5/2
3: Low = .75, portion_saved= 1.75/2
4: Low = .875, portion_saved= 1.875/2
5: and so on....
Well, I solved it. Had to make two corrections.
Multiplied the 'total_cost' by 'portions_down_payment' as I really had to calculate the rate to pay the downpayment.
I reset the value of annual sal for each iteration to the initial value.
The final code looks like this:
#This part asks for the user input
starting_salary = float(input("Enter your annual salary:"))
#Declaring all the variables
total_cost = 1000000
High = 1.0
Low = 0.0
portion_saved = (High +Low)/2.0
semi_annual_raise = 0.07
r = 0.04 #annual investment return
portion_down_payment = 0.25
num_guesses = 0
epsilon = 100
total_saving = 0.0
months = 36
print(portion_saved)
#Calculations next
while abs(total_cost*portion_down_payment - total_saving) >= epsilon:
num_guesses += 1
total_saving = 0.0
annual_salary = starting_salary
for i in range (months):
monthly_salary = annual_salary/12
monthly_saving = monthly_salary*portion_saved
total_saving += (monthly_saving + total_saving*r/12)
if i%6 == 0:
annual_salary += annual_salary*semi_annual_raise
if (total_saving > total_cost*portion_down_payment):
High = portion_saved
else:
Low = portion_saved
portion_saved = (Low+High)/2.0
print("Best savings rate:", portion_saved)
print("Number of steps:", num_guesses)

Return multiple values in a function

I am doing a University project to create a plan ordering ticket program, so far these are what I have done:
First, this is the function finding the seat type:
def choosingFare():
print("Please choose the type of fare. Fees are displayed below and are in addtion to the basic fare.")
print("Please note choosing Frugal fare means you will not be offered a seat choice, it will be assigned to the ticketholder at travel time.")
listofType = [""] * (3)
listofType[0] = "Business: +$275"
listofType[1] = "Economy: +$25"
listofType[2] = "Frugal: $0"
print("(0)Business +$275")
print("(1)Economy +$25")
print("(2)Frugal: $0")
type = int(input())
while type > 2:
print("Invalid choice, please try again")
type = int(input())
print("Your choosing type of fare is: " + listofType[type])
if type == 0:
price1 = 275
else:
if type == 1:
price1 = 25
else:
price1 = 0
return price1, listofType[type]
And this is a function finding the destination:
def destination():
print("Please choose a destination and trip length")
print("(money currency is in: Australian Dollars: AUD)")
print("Is this a Return trip(R) or One Way trip(O)?")
direction = input()
while direction != "R" and direction != "O":
print("Invalid, please choose again!")
direction = input()
print("Is this a Return trip(R) or One Way trip(O)?")
if direction == "O":
print("(0)Cairns oneway: $250")
print("(2)Sydney One Way: $420")
print("(4)Perth One Way: $510")
else:
print("(1)Cairns Return: $400")
print("(3)Sydney Return: $575")
print("(5)Perth Return: $700")
typeofTrip = [""] * (6)
typeofTrip[0] = "Cairns One Way: $250"
typeofTrip[1] = "Cairns Return: $400"
typeofTrip[2] = "Sydney One Way: $420"
typeofTrip[3] = "Sydney Return: $575"
typeofTrip[4] = "Perth One Way: $510"
typeofTrip[5] = "Perth Return: $700"
trip = int(input())
while trip > 5:
print("Invalid, please choose again")
trip = int(input())
if trip == 0:
price = 250
else:
if trip == 1:
price = 400
else:
if trip == 2:
price = 420
else:
if trip == 3:
price = 574
else:
if trip == 4:
price = 510
else:
price = 700
print("Your choice of destination and trip length is: " + typeofTrip[trip])
return price, typeofTrip[trip]
And this is the function calculating the total price:
def sumprice():
price = destination()
price1 = choosingFare()
price2 = choosingseat()
sumprice = price1 + price2 + price
print("How old is the person travelling?(Travellers under 16 years old will receive a 50% discount for the child fare.)")
age = float(input())
if age < 16 and age > 0:
sumprice = sumprice / 2
else:
sumprice = sumprice
return sumprice
The error I have:
line 163, in <module> main()
line 145, in main sumprice = sumprice()
line 124, in sumprice
sumprice = price1 + price2 + price
TypeError: can only concatenate tuple (not "int") to tuple
Can someone help me? I am really stuck.
I can't return all the
These functions return 2 values each: destination(), choosingFare(), choosingseat().
Returning multiple values at once returns a tuple of those values:
For example:
return price, typeofTrip[trip] # returns (price, typeofTrip[trip])
So while calculating the sum of all prices, you need to access price, price1, price2 from the tuples:
sumprice = price1[0] + price2[0] + price3[0]
Alternatively: You can edit the code to return list/ dictionary or some other data structure as per your convenience.
First let me explain what happends when you write. return price, typeofTrip[trip].
The above line will return a tuple of two values.
Now for sumprice I think what you want is sum of all prices. So you just want to sum first element of returned values.
This should work for your case.
sumprice = price1[0] + price2[0] + price3[0]

How to better implement a history of user action?

I decided to make a calculator as a project.
Implementing basic addition, subtraction, division, and multiplication was fairly easy.
I wanted to add more functionality so I decided to implement a list of results the user view. However, I had a difficult time keeping track of the results numerically. I wrote a maze of if statements that are functional but seem to be overwrought with code. I am sure there is a better way to handle this.
Any advice?
def add(x, y):
return x + y
def sub(x, y):
return x - y
def mul(x, y):
return x * y
def div(x, y):
value = None
while True:
try:
value = x / y
break
except ZeroDivisionError:
print('Value is not dividable by 0, try again')
break
return value
def num_input(prompt='Enter a number: '):
while True:
try:
print(prompt, end='')
x = int(input())
break
except ValueError:
print('You must input a number. Try again.')
return x
def get_two_val():
x, y = num_input(), num_input()
return x, y
print("Welcome to Simple Calc")
# declaration of variables
num_of_calc_counter = 0
index_of_calc = 1
calculations = []
while True:
print("Choose from the following options:")
print(" 1. Add")
print(" 2. Subtract")
print(" 3. Multiply")
print(" 4. Divide")
print(" 5. Sales Tax Calculator")
print(" 6. Recent Calculations")
print(" 0. Quit")
usrChoice = num_input('Enter your choice: ')
'''
Menu workflow
options 1-4 take in two numbers and perform the specified calculation and
then add the result to a master list that the user can reference later.
lastly, the workflow increments the num_of_calc variable by 1 for recent
calc logic
option 5 is a simple tax calculator that needs work or option to enter
or find tax rate
option 6 returns a list of all the calculations perform by the user
'''
if usrChoice is 1:
numbers = get_two_val()
result = add(*numbers)
print(numbers[0], "plus", numbers[1], "equals", result)
calculations.extend([result])
num_of_calc_counter += 1
elif usrChoice is 2:
numbers = get_two_val()
result = sub(*numbers)
print(numbers[0], "minus", numbers[1], "equals", result)
calculations.extend([result])
num_of_calc_counter += 1
elif usrChoice is 3:
numbers = get_two_val()
result = mul(*numbers)
print(numbers[0], "times", numbers[1], "equals", result)
calculations.extend([result])
num_of_calc_counter += 1
elif usrChoice is 4:
numbers = get_two_val()
result = div(*numbers)
print(numbers[0], "divided by", numbers[1], "equals", result)
calculations.extend([result])
num_of_calc_counter += 1
elif usrChoice is 5:
tax_rate = .0875
price = float(input("What is the price?: "))
total_tax = tax_rate * price
final_amount = total_tax + price
print('Tax rate: ', tax_rate, '%')
print('Sales tax: $', total_tax)
print('_____________________________')
print('Final amount: $', final_amount)
#
elif usrChoice is 6:
if len(calculations) is 0:
print('There are no calculations')
elif num_of_calc_counter == 0:
index_of_calc = 1
for i in calculations:
print(index_of_calc, i)
index_of_calc += 1
num_of_calc_counter += 1
elif index_of_calc == num_of_calc_counter:
index_of_calc = 1
for i in calculations:
print(index_of_calc, i)
index_of_calc += 1
num_of_calc_counter += 1
elif num_of_calc_counter > index_of_calc:
index_of_calc = 1
for i in calculations:
print(index_of_calc, i)
index_of_calc += 1
num_of_calc_counter -= 1
elif num_of_calc_counter < index_of_calc:
index_of_calc = 1
for i in calculations:
print(index_of_calc, i)
index_of_calc += 1
num_of_calc_counter += 1
elif usrChoice is 0:
break
I don't know if you could find this simpler:
def num_input(prompt='Enter a number: '):
finished = False
while not finished:
string_input = input(prompt)
try:
input_translated = int(string_input)
except ValueError:
print('You must input a number. Try again.')
else:
finished = True
return input_translated
def division_operation(x, y):
if y == 0:
print('Value is not dividable by 0, try again')
return None
else:
return x / y
math_operations_values = [
(lambda x, y: x + y, 'plus'),
(lambda x, y: x - y, 'minus'),
(lambda x, y: x * y, 'times'),
(division_operation, 'divided by')
]
def get_two_val():
return (num_input(), num_input())
def operate_on_numbers(operation_index):
def operate():
numbers = get_two_val()
operator, operation_string = math_operations_values[operation_index]
result = operator(*numbers)
if result is not None:
print(numbers[0], operation_string, numbers[1], "equals", result)
calculations.append(result)
return operate
def tax_computation():
tax_rate = .0875
price = float(input("What is the price?: "))
total_tax = tax_rate * price
final_amount = total_tax + price
print('Tax rate: ', tax_rate * 100, '%')
print('Sales tax: $', total_tax)
print('_____________________________')
print('Final amount: $', final_amount)
def show_computations():
if calculations:
for (index, values) in enumerate(calculations, start=1):
print(f'{index}: {values}')
else:
print('There are no calculations')
calculations = []
finished = False
choices_actions = [
operate_on_numbers(0),
operate_on_numbers(1),
operate_on_numbers(2),
operate_on_numbers(3),
tax_computation,
show_computations
]
while not finished:
print("""
Choose from the following options:
1. Add
2. Subtract
3. Multiply
4. Divide
5. Sales Tax Calculator
6. Recent Calculations
0. Quit""")
user_choice = num_input('Enter your choice: ')
'''
Menu workflow
options 1-4 take in two numbers and perform the specified calculation and
then add the result to a master list that the user can reference later.
lastly, the workflow increments the num_of_calc variable by 1 for recent
calc logic
option 5 is a simple tax calculator that needs work or option to enter
or find tax rate
option 6 returns a list of all the calculations perform by the user
'''
if user_choice == 0:
finished = True
else:
try:
operation_to_do = choices_actions[user_choice - 1]
except IndexError:
print('Please enter one of choice shown.')
else:
operation_to_do()

Categories