How to run a function with no parameters defined? [closed] - python

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 1 year ago.
Improve this question
I am trying to create a code that does not require parameters to determine if one is qualified for a loan, but the function takes years and annual wage into account to determine if qualified. How can I get the function to take inputs without parameters?
edit: I cannot give it parameters becausse that is what was asked of me. To create this function without parameters.
def loan():
"""
-------------------------------------------------------
To qualify for a loan, the annual salary must be 30000 or more and
employee must have worked for a minimum of 5 years
Use: qualified = loan()
-------------------------------------------------------
Returns:
qualified - True if employee qualifies for a loan,
False otherwise (boolean)
-------------------------------------------------------
"""
MIN_SALARY =30000
MIN_YEARS = 5
if years < 5:
qualified = False
elif years >= MIN_YEARS:
if salary >= MIN_SALARY:
qualified = True
else:
qualified = False
else:
qualified = False
return qualified
#--------------Main Program-----------------#
years = int(input('Years employed: '))
salary = float(input('Annual salary: '))
qualified = loan(years = years, salary = salary)
print()
print('Qualified for a loan: {}'.format(qualified))

You could use keyword args for this...
def loan(**kwargs):
...
...but the more sensible and practical thing would be to specify the parameters you expect to be passed into the function.
def loan(years, salary):
...
Methods aren't magical and they have their own scope. If you don't add variables to that scope, then the only way you'd get information is from global scope, which is expressly discouraged and also wholly unnecessary in this case.

I was able to figure it out. What I did was add the inputs into the code itself.
def loan():
"""
-------------------------------------------------------
To qualify for a loan, the annual salary must be 30000 or more and
employee must have worked for a minimum of 5 years
Use: qualified = loan()
-------------------------------------------------------
Returns:
qualified - True if employee qualifies for a loan,
False otherwise (boolean)
-------------------------------------------------------
"""
years =(int(input('Years employed: ')))
salary = (float(input('Annual salary: ')))
#rest of the function

Related

New to Python looking for some assistance Assistance [closed]

Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 1 year ago.
Improve this question
For my class we have been instructed to execute the following:
"Create a program called ph.py that determines the acidity or basicity of a solution. It should ask the user to enter a numeric pH value. It should then call a function that accepts the value as a parameter and returns a string indicating that the solution is acidic (pH less than 7), basic (pH greater than 7), or neutral (pH is 7); it should return "invalid" if the value is greater than 14 or less than zero*. Finally, your script should then output the returned string for the user to see."
This is what I was able to come up with:
def water_ph() -> object:
ph: int = int(input("Enter the numeric value for your water: "))
if ph >= 14 or ph <= 0:
return f"{ph} invalid"
elif ph < 7:
return f"{ph} is acidic"
elif ph > 7:
return f"{ph} is basic"
elif ph == 7:
return f"{ph} is neutral"
ph = water_ph()
print(ph)
Does this look correct? it works I'm just worried I'm not answering the above question correctly.
call a function that accepts the value as a parameter
def water_ph()
I do not see any arguments in your function declaration.
returns a string
def water_ph() -> object:
Then why are you declaring the function to return an object ?
ask the user to enter a numeric pH value. It should then call a function
You are first calling the function and then asking the user for input iside this function.

Why isn't this extracting the price correctly? Every price comes out to 0? Also it said 'payment' was being referenced before it was defined? [closed]

Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 2 years ago.
Improve this question
# Sample line of text from file (Ford,F150,55000;)
filename = 'carPrice.txt'
def main():
all_prices= {}
try:
with open(filename) as fh:
for line in fh:
make, model, price = line.strip().split(',')
all_prices[(make,model)]=price.strip()
income = float(input("Enter your monthly income amount:"))
print("Your monthly income amount is",income,)
make = input("Enter Make of the car:")
print("You selected a",make,)
model = input("Enter Model of the car:")
print("You selected a",model,)
price_value=0
for x in price:
if x == (make,model):
price_value=price[x]
print("The price of that car is",price_value,)
payment = (price_value* 0.80)/60
print("The monthly payment is",payment,)
if (payment < 0.11*income):
print("The monthly payment of",payment,"= Acceptable Risk")
return "Acceptable"
else:
print("The monthly payment of",payment,"= Unacceptable Risk")
return "Unacceptable"
# Exception added to enable troubleshooting of errors on lines
except OSError as e:
print(e.errno)
if __name__ == '__main__':
main()
With respect, the code seems to be a bit all over the place, specifically in regards to price. If this is an exact copy of your code I think you may have lost track of what 'price' actually is.
For example here:
for x in price:
if x == (make,model):
price_value=price[x]
However, price here is a string value you pulled from the file e.g. £100. You're then iterating over that £, 1, 0, 0 and checking it against the make and model.
Finally you make the price_value an index of this string e.g.
price[x] # could be price["£"]
This would then cause an exception.
I'd go through your code again and look to make sure you're referencing price, price_value and all_prices where you actually want them

Another Python NameError: name is not defined [closed]

Closed. This question is not reproducible or was caused by typos. It is not currently accepting answers.
This question was caused by a typo or a problem that can no longer be reproduced. While similar questions may be on-topic here, this one was resolved in a way less likely to help future readers.
Closed 5 years ago.
Improve this question
I am having issues with a defined name error message in Python. I know there are quite a few responses to this question, but I cannot seem to find one that fits my situation. My code is as follows:
#Gets the input of the property value from the user and calculates the individual and total revenue
def main():
class_A_input = int(input('Please enter the number of Class A seats sold: '))
class_B_input = int(input('Please enter the number of Class B seats sold: '))
class_C_input = int(input('Please enter the number of Class C seats sold: '))
#Declares the cost for each class of ticket
class_A_cost = 20
class_B_cost = 15
class_C_cost = 10
#Passes the variable for each ticket class
class_A(class_A_input, class_A_cost)
class_B(class_B_input, class_B_cost)
class_C(class_C_input, class_C_cost)
#Calculates the total revenue
total_revenue = (class_A_input * class_A_cost) + ,\
(class_B_input * class_B_cost) + (class_C_input * class_C_cost)
print ('Total tickets revenue is $',format(total_revenue,',d'),sep='')
#Calculates the class A revenue
def class_A(A_input, A_cost):
class_A_revenue = A_input * A_cost
print ('The amount of Class A revenue is $',format(class_A_revenue,',d'),sep='')
#Repeat definitions for Class B and Class C
main()
I am running Python 3.6.0 and I am getting the following name error:
total_revenue = (class_A_input * class_A_cost) + ,\
(class_B_input * class_B_cost) + (class_C_input * class_C_cost)
NameError: name 'class_A_input' is not defined
I don't think I am declaring the variable before I use it. I have tried a variety of different solutions with no success. So what am I doing wrong?
This looks like an indentation issue. total_revenue is global and trying to use local variable from main() in its calculation.
p.s. You should learn about functions in order to help you reduce duplication in your code.

Python 2.7.9 - How to save a raw_input in a variable to use it later? [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 7 years ago.
Improve this question
This is a bit of code from my text based game:
location_now = ""
class what_do:
def whaat(self):
interactions = what_do()
print "*What will you do? Type help_ to see all the actions*"
what = raw_input("")
if what == "help_":
print ' '.join(help_)
interactions.whaat()
if what == "travel":
print "These are all the cities you can travel to:"
mapje.map()
travel = raw_input("To which city do you want to travel?(Takes 10 seconds)")
if travel == locations[0] or travel == locations[1] or travel == locations[2] or travel == locations[3] or travel == locations[4] or travel == locations[5] or travel == locations[6] or travel == locations[7] or travel == locations[8]:
print "You are now travelling to %s" % travel
time.sleep(10)
print "You are now in %s!" % travel
location_now = travel
else:
print "That is no location in Skyrim!"
interactions.whaat()
I want the input from travel = raw_input etc. to be stored and saved in the variable location_now (That I created before and outside the class). I have to use that input later in my code.
This class will be repeated because it is a sort of 'What would you like to do next?', so if the input from the second time, what = raw_input(""), is asked, it must replace the earlier input stored in location_now = ""
I believe you are worried that whatever is stored in your location_now variable would be overwritten if you use raw_input() again.
Luckily, that doesn't happen and if you have stored the result of a raw_input() in a variable, it remains intact.
Are you facing any problems that made you arrive to the conclusion?
I would move your location_now variable into the class "what_do" as a static variable. (Static class variables in Python)
Also as a helpful hint, this line
if travel == locations[0] or travel == locations[1] or travel == locations[2] or travel == locations[3] or travel == locations[4] or travel == locations[5] or travel == locations[6] or travel == locations[7] or travel == locations[8]:
can be reduced to
if travel in locations:
This will check if travel is in the list of locations. Just a little hint to simplify your code! Isn't Python beautiful?
In your whaat() function when you are trying to assign a new value to location_now you are actually creating a new local variable called location_now. You are not assigning a new value to the global location_now.
You need to declare location_now as global before your assignment so that you will actually assign a new value to the global variable.
global location_now
location_now = travel

Python hw, trouble with class and methods [closed]

It's difficult to tell what is being asked here. This question is ambiguous, vague, incomplete, overly broad, or rhetorical and cannot be reasonably answered in its current form. For help clarifying this question so that it can be reopened, visit the help center.
Closed 10 years ago.
I am having trouble with an hw problem in my CS class. The problem has to do with creating a class in python. Heres the prompt
Your class should be named Student, and you should define the following methods:
__init__: This method initializes a Student object.
Parameters: a name, a GPA, and a number of units taken
• Should initialize instance variables for name, GPA, and units based on
the information that was passed in. If the GPA or number of units is negative, sets it to 0. (Donʼt worry about non-numeric values in this method.)
update: This method updates the instance variables of the Student object if the Student takes a new class.
• Parameters: units for the new class, grade points earned (as a number) in the new class.
• Should modify the instance variable for units to add the units for the new class
• Should modify the GPA to incorporate the grade earned in the new class. (Note that this will be a weighted average using both the unit counts and both sets of GPAs.)
get_gpa: This method should return the studentʼs GPA.
get_name: This method should return the studentʼs name.
Heres what i have
class Student:
def__init__(self,name,GPA,units):
if units <0:
units=0
if GPA<0:
GPA=0
self.name=name
self.GPA=GPA
self.units=units
def update(newunits,GPE):
thats all i can come up with
Let’s go through some points which will hopefully help you:
Constructor (__init__)
If the GPA or number of units is negative, sets it to 0.
So you probably want to check each separately:
if units < 0:
units = 0
if GPA < 0:
GPA = 0
Update method
Methods in general take a reference to the current object as the first argument, named self per convention (just as in __init__). So your update method declaration should look like this:
def update(self, newunits, GPE):
...
Should modify the instance variable for units to add the units for the new class
Just as you did in the constructor, you can access instance variables using self.varname. So you probably want to do something like this:
self.units += newunits
Should modify the GPA to incorporate the grade earned in the new class. (Note that this will be a weighted average using both the unit counts and both sets of GPAs.)
Just as you update self.units you have to update self.GPA here. Unfortunately, I have no idea what a GPA is and how it is calculated, so I can only guess:
self.GPA = ((self.GPA * oldunits) + (GPE * newunits)) / self.units
Note that I introduced a new local variable oldunits here that simply stores the units temporarily from before it was updated (so oldunits = self.units - newunits after updating).
get_gpa and get_name
These are simple getters that just return a value from the object. Here you have an example for the units, i.e. you should figure it out for the actual wanted values yourself:
def get_units (self):
return self.units
Note that it’s rather unpythonic to have getters (get_x methods), as you would just expect people to access the properties directly (while handling them with care).
I'll help you to complete the question, but let me point out a little mistake first:
if units <0 and GPA <0:
units=0
GPA=0
This will set units and GPA to zero only if they are both negative. You'll want to set each to zero if it's negative, even if the other is not. Change it to:
if units < 0: units = 0
if GPA < 0: GPA = 0
Concerning your update method, the correct signature would be:
def update(self, newunits, GPE):
Python object methods should always start with self.
Now, I'm not sure about how to calculate the GPA (we use a different system were I live), but according to some quite google queries, your update method should be something like:
def update(self, newunits, GPE):
GPE_earned_before = self.GPA * self.units
total_GPE = GPE_earned_before + GPE
self.GPA = total_GPE / (self.units + newunits)
self.units += newunits
I used a lot of variables here, to make things clear, but this can be shortened to:
def update(self, newunits, GPE):
self.GPA = (self.GPA * self.units + GPE) / (self.units + newunits)
self.units += newunits

Categories