Using functions with variables in Python - python

I had an assessment for my programming class about calculating insurance using functions. This is the code I was trying to get work but unfortunately I failed:
import time
def main():
print('Welcome to "Insurance Calculator" ')
type_I, type_II, type_III = inputs()
calculationAndDisplay()
validation()
time.sleep(3)
def inputs():
try:
type_I = int(input("How many Type I policies were sold? "))
type_II = int(input("How many Type II policies were sold? "))
type_III = int(input("How many Type III policies were sold? "))
return type_I, type_II, type_III
except ValueError:
print("Inputs must be an integer, please start again")
inputs()
def calculationAndDisplay():
type_I *= (500/1.1)
type_II *= (650/1.1)
type_III *= (800/1.1)
print("The amount of annual earned for type_I is: $", type_I)
print("The amount of annual earned for type_I is: $", type_II)
print("The amount of annual earned for type_I is: $", type_III)
def validation():
cont = input("Do you wish to repeat for another year? [Y/N]: ")
if cont == 'Y' or cont == 'y':
main()
elif cont == 'N' or cont == 'n':
print('Thank You! ------ See You Again!')
else:
print("I'm sorry, I couldn't understand your command.")
validation()
main()
I eventually got it to work by cramming all of the input, calculation, and display into one function. I just want to know how I could have made it work the way intended..
Edit: The program is meant to get the user to input the number of policy's sold and display a before tax total. When I enter a few number inputs it gives me the following error
Welcome to "Insurance Calculator"
How many Type I policies were sold? 3
How many Type II policies were sold? 3
How many Type III policies were sold? 3
Traceback (most recent call last):
File "C:\Users\crazy\Desktop\assessment 2.py", line 38, in <module>
main()
File "C:\Users\crazy\Desktop\assessment 2.py", line 5, in main
type_I, type_II, type_III = inputs()
TypeError: 'NoneType' object is not iterable
Edit: I moved the return line to the suggested line and now it is giving me an unbound variable error:
Welcome to "Insurance Calculator"
How many Type I policies were sold? 5
How many Type II policies were sold? 5
How many Type III policies were sold? 5
Traceback (most recent call last):
File "C:\Users\crazy\Desktop\assessment 2.py", line 39, in <module>
main()
File "C:\Users\crazy\Desktop\assessment 2.py", line 6, in main
calculationAndDisplay()
File "C:\Users\crazy\Desktop\assessment 2.py", line 22, in
calculationAndDisplay
type_I *= (500/1.1)
UnboundLocalError: local variable 'type_I' referenced before
assignment

The problem is, that you save the values in variables which only exist inside the main method but not in the global scope:
type_I, type_II, type_III = inputs()
calculationAndDisplay()
Doing this, the calculationAndDisplay() method do not know the values. You can solve this, by adding parameters to this functions, like this:
def calculationAndDisplay(type_I, type_II, type_III):
#your code
Edit: You code is working without any problem when you perform all calculations in the same method, as now all variables are created inside the same scope. If you use methods, you either have to use function arguments/parameters (the better solution) or use global variables (bad solution, as it undermines the concept of the functions).
In the case, that you later on want to use the modified values of type_I etc. after calling calculationAndDisplay() again, you have to return the modified values in this function, so that you and up with this code:
def calculationAndDisplay(type_I, type_II, type_III):
#your code
return type_I, type_II, type_III

That error which you have mentioned is due to the indentation of the return statement in inputs(). That return statement should be inside inputs function(Because in your case inputs() is not returning type_I,type_II,type_II). Also arguments should be passed to calculationAndDisplay(type_I,type_II,type_III).

Related

Call a nested function through a global function?

I am new to Python and am trying to make a simple game with several chapters. I want you to be able to do different things depending on the chapter, but always be able to e.g. check your inventory. This is why I have tried using nested functions.
Is it possible to create a global function which acts differently depending on what chapter I am in, while still having certain options available in all chapters or should I perhaps restructure my code significantly?
I get the following error code:
> Traceback (most recent call last): File "test.py", line 21, in
> <module>
> chapter1() File "test.py", line 19, in chapter1
> standstill() File "test.py", line 4, in standstill
> localoptions() NameError: name 'localoptions' is not defined
I understand that the global function doesn't identify a nested function. Is there any way to specify this nested function to the global function?
def standstill():
print("What now?")
print("Press A to check inventory")
localoptions()
choice = input()
if choice == "A":
print("You have some stuff.")
else:
localanswers()
def chapter1():
def localoptions():
print("Press B to pick a flower.")
def localanswers():
if choice == "B":
print("What a nice flower!")
standstill()
chapter1()
I used classes as Mateen Ulhaq suggested and solved it. Thank you! This is an example of a scalable system for the game.
(I am new to Python and this might not be the best way, but this is how I solved it now.)
class chapter1:
option_b = "Pick a flower."
def standstill():
print("What do you do now?")
print("A: Check inventory.")
if chapter1active == True:
print("B: " + chapter1.option_b)
#Chapter 1
chapter1active = True
standstill()
chapter1active = False

How can I solve a KeyError in my code, I'm a begginer

I'm resolving a basic problem consisting of make a list of products, the user choose the product and the amount of the product and the total price is printed. I get a keyerror in the line 22.
def main():
print("Choose a product: ")
print("")
print("Products: ")
print("")
print("Samsung Galaxy S10+.............1")
print("Samsung Galaxy S10..............2")
print("OnePlus 7 Pro...................3")
print("OnePlus 7.......................4")
print("OnePlus 6t......................5")
print("Huawei P30 Pro..................6")
print("Huawei Mate 20 Pro..............7")
print("Google Pixel 3XL................8")
print("Gooogle Pixel 3A XL.............9")
print("Oppo Reno 10x Zooom............10")
print("")
relation = {1:1000, 2:900, 3:700, 4:600, 5:470, 6:850, 7:970, 8:950, 9:300, 10:550}
code = input("Enter the product code: ")
print("")
print("The price is $", relation[code])
quantify = input("Enter amount: ")
print("")
totalPrice = float(relation[code] * quantify)
print("The total price is: $", totalPrice)
The error displayed is
Traceback (most recent call last):
File "main.py", line 30, in <module>
main()
File "main.py", line 22, in main
print("The price is $", relation[code])
KeyError: '5'
In this case I choose the product code "5".
When you use input it returns a string, not an integer. You can see this because the error message shows '5', not 5. The keys to your dictionary are integers, though, so the key you are providing in the statement (code) is not found.
You could instead use
print("The price is $", relation[int(code)])
A better format, at least in Python 3.6 and later, would be
print(f"The price is ${relation[int(code)]}")
for line 26, the problem is similar. Just convert to integers (or float, if there's a decimal point)
totalPrice = float(relation[int(code)] * int(quantify))
or
totalPrice = relation[int(code)] * float(quantify)
input in python receives data as a string, you need to typecast it
it is something along:
print("The price is $", relation[int(code)])
I think you should also follow the Python idiom EAFP (Easier to ask for forgiveness than permission) here when asking for user input as he could write literally everything but integers you expect:
while True:
code = input("Enter the product code: ")
try:
price = relation[int(code)]
except (ValueError, KeyError):
print("Error: Incorrect code value, try again!")
else:
break
def main():
print("Choose a product: ")
print("")
print("Products: ")
print("")
print("Samsung Galaxy S10+.............1")
print("Samsung Galaxy S10..............2")
print("OnePlus 7 Pro...................3")
print("OnePlus 7.......................4")
print("OnePlus 6t......................5")
print("Huawei P30 Pro..................6")
print("Huawei Mate 20 Pro..............7")
print("Google Pixel 3XL................8")
print("Gooogle Pixel 3A XL.............9")
print("Oppo Reno 10x Zooom............10")
print("")
relation = {1:1000, 2:900, 3:700, 4:600, 5:470, 6:850, 7:970, 8:950, 9:300, 10:550}
code = input("Enter the product code: ")
print("")
print("The price is $", relation[code])
quantify = input("Enter amount: ")
print("")
totalPrice = float(relation[int(code)] * quantify)
print("The total price is: $", totalPrice)
you need to take the input as integer because the input() take the default as a string so you can type it like quantify = int(input("Enter amount: "))
or another method is to use int() in the place where the calculations are like
totalPrice = float(relation[int(code)] * int(quantify))

How do I successfully include a definition in a if function

How do I put a definition function into a if statement so when it's running the program will activate the definition by itself.
person=int(input("select the number of any option which you would like to execute:"))
if (person)==(1):
print ("please write the value for each class ")
main()
def main ():
juvenile=(input(" number of juveniles: "))
adult= (input(" number of adults:"))
senile=(input("number of seniles:"))
When i run it it always gives me an error.
Traceback (most recent call last):
File "C:\Users\fenis\Desktop\TEST PAGE 4 GCSE CS CW.py", line 6, in <module>
main()
NameError: name 'main' is not defined
>>>
You can't call main() at a point where main() hasn't been defined. Move your definition of main() to above the place where you try and call it.
def main():
juvenile = input("number of juveniles:")
adult = input("number of adults:")
senile = input("number of seniles:")
person = int(input("select the number of any option which you would like to execute:"))
if person==1:
print ("please write the value for each class ")
main()

Error saying a variable is not defined?

#Intro
import time
import random
def restart():
bowlSize = random.randint(1,100)
bowlStrawberries = 0
def lel():
while bowlSize > bowlStrawberries:
if (addCheck + bowlStrawberries) > bowlSize:
print('You´re filling the bowl..')
time.sleep(2)
print('...and...')
time.sleep(2)
print('Your mom slaps you!')
restart()
def addStrawberries():
print('The bowl has ' + str(bowlStrawberries) + ' strawberries in it')
print('How many strawberries do you want to add?')
addCheck = input()
lel()
print('STRAWBERRY (:')
time.sleep(2)
print('Okey so you have a bowl kinda')
time.sleep(2)
print('And you have a bag with 100 strawberries')
time.sleep(2)
print('So ur mom forces you to fill the bowl')
time.sleep(2)
print('But she will slap you if a strawberry drops on the floor')
time.sleep(2)
print('So you have to fill it up in as few tries as possible without overfilling it')
time.sleep(2)
restart()
addStrawberries()
I´m new to Programming, it´s my fifth day today and I can´t understand why I get errors. You propably had similar questions but I am new and I don´t know what to search. I basically want it to restart when I pick a higher value than the bowls space.
Exact errors:
Traceback (most recent call last):
File "C:/Users/***/Documents/strenter code herew.py", line 44, in <module>
addStrawberries()
File "C:/Users/***/Documents/strw.py", line 27, in addStrawberries
lel()
File "C:/Users/***/Documents/strw.py", line 14, in lel
if (addCheck + bowlStrawberries) > bowlSize:
NameError: name 'addCheck' is not defined
addCheck is a local variable in addStrawberries, meaning it can't be seen outside of the function. I recommend passing it as an argument to lel, i.e. call lel(addCheck) and define lel as def lel(addCheck). Alternatively you could make addCheck a global variable by inserting the statement global addCheck in addStrawberries before assigning it, but global variables tend to be icky.

Printing a subtotal when a value is defined inside an if-elif-else statement? Name error issue [Python 2.7]

I'm currently working on a project which acts as an airline reservation booking system. As of right now I'm having an issue with calculating and displaying a subtotal which was calculated inside of an if elif else loop statement, if that makes sense.
For example, I currently need to calculate the subtotal of the seats and luggage. Below is my code:
user_people = int(raw_input("Welcome to Ramirez Airlines! How many people will be flying?"))
user_seating = str(raw_input("Perfect! Now what type of seating would your party prefer?"))
user_luggage = int(raw_input("Thanks. Now for your luggage, how many bags would you like to check in?"))
user_frequent = str(raw_input("Got it. Is anyone in your party a frequent flyer with us?"))
user_continue = str(raw_input("Your reservation was submitted successfully. Would you like to do another?"))
luggage_total = user_luggage * 50
import time
print time.strftime("Date and time confirmation: %Y-%m-%d %H:%M:%S")
if user_seating == 'economy':
seats_total = user_people * 916
print seats_total
elif user_seating == 'business':
seats_total = user_people * 2650
print seats_total
else:
print user_people * 5180
print luggage_total
print luggage_total + seats_total
As I said above I'm trying to add the total price for the number of plane tickets reserved based on which class the user chose (economy, business and first class) and the total amount of the required luggage needed to be checked in (x amount & $50).
This is the error I am receiving when executing the above code:
Traceback (most recent call last):
File "C:/Users/Cory/Desktop/Project 1.py", line 26, in <module>
print luggage_total + seats_total
NameError: name 'seats_total' is not defined
How do I go about defining seats_total outside of the if-elif-else statements?
Thank you so much!
Well, your variable seats_total will be defined only for user_seating == 'economy' or user_seating == 'business'. For the third case, no such variable is defined. To define "seats_total outside of the if-elif-else statements" just set it to zero for example, or some default value.

Categories

Resources