I am learning how to program in python 3 and today i was praticing until i start to struggle with this.
I was trying to make a function to get to know the total square meters of wood that i'll use in one project, but i keep get the none result and i don't know why, even reading almost every post about it that i found here.
Anyway, here's the code:
from math import pi
def acirc(r):
pi*r**2
def madeiratotal(r1,r2,r3,r4,r5):
a = acirc(r1)
b = acirc(r2)
c = acirc(r3)
d = acirc(r4)
e = acirc(r5)
print (a+b+c+d+e)
madeiratotal(0.15,0.09,0.175,0.1,0.115)
I already try defining the "acirc" function inside the "madeiratotal" function, try to print all numbers separated and them suming then... I just don't know what else to do please help
You need to return value from acirc function otherwise return type is None
def acirc(r):
return pi*r**2
Related
I have a function which returns a dictionary that always has the same keys (send over network and "stringified" with json). And basically my function looks like this:
def getTemps(self) -> dict:
"""
get room and cpu temperature in °C as well as humidity in %
"""
# send temperature request to server
msg = {'type':'req', 'reqType':'temps'}
self.send(msg)
res = self.recieve() # get response
return res
and the dictionary you get from this function always looks something like that:
{'Room':float, 'CPU':float, 'hum':float}
so I was wondering if there was a way to specify the return type of the function so you know what keys the dictionary has:
def getTemps(self) -> Dict['Room':float, 'CPU':float, 'hum':float]
but that didn't work as it only showed Dict[slice, slice, slice] when hovering over the function (I am using vscode).
I don't think this is something that is very useful, but something that makes your code look better and also be easier to use for someone else. So if someone knows if this is possible and how, I would be very grateful to get a response!
consider this:
class Message:
def __init__(self,room,cpu,hum):
self.Room = room
self.CPU = cpu
self.hum = hum
and return Message(room,cpu,hum) or define a method to convert this to dict in the class if necessary.
This may be the only method.
Update: This is neither the only nor the best method, see comments.
I want to build a function for following code:
PlayDirection_encoder = LabelEncoder()
train["PlayDirection"] = direction_encoder.fit_transform(train["PlayDirection"])
train.PlayDirection.unique()
That's my current function:
def object(category):
%s = Label_Encoder() % (category + "_encoder")
train[category] = %s.fit_transform(train[category]) %(category + "_encoder")
len(train.category.unique())
object("PlayDirection")
UsageError: Line magic function `%s` not found.
I am running my code on Kaggle's server.
Do you know how to solve this problem?
calling function an object is really really bad idea. It's a reserved word in Python, so it might break everything in your code.
what do you want to achieve? your problem is not clear
I am trying to use "odein" in another function to assess some parameters. But the code gave a sign "restart: shell". I cannot understand what is happenning here.
def fun(x,ia,ib):
#### function that returns dy/dt
def model(y, t, a, b):
dydt = np.exp(a-b/R/T)
return dydt
#### initial condition
y0 = 0.0
#### temperature points
t = x/d
#### solve ODEs
a= ia
b = ib
y1 = odeint(modeldydt,y0,t,args=(a,b))
return y1
x=array([279,300,310,320,330,340,350])
y=array([0.0,0.1,0.2,0.3,0.6,0.7,0.8])
calc_model = Model(fun)
pars = TGA_model.make_params(ia=10, ib=1e4)
result = calc_model.fit(y, x=x)
And what I got is
=============================== RESTART: Shell ===============================
I would like to know if it is possible to net the functions together in python. If it is possible, you are very kind to tell me the mistake I have made. If it is not possible, you are still welcome to send me your suggestion. If nothing works in python, I should try some matlab code instead.
Thanks in advance!
(background first: I am NEW to programming and currently in my very first "intro to programming class" in my college. This is our second assignment dealing with Functions. So far functions have been a pain in the ass for me because they don't really make any sense. ex: you can use miles_gas(gas) but then don't use "miles_gas" anywhere else, but the program still runs??, anyways)
Okay, I've looked EVERYWHERE online for this and can't find an answer. Everything is using "Exceptions" and "try" and all that advanced stuff. I'm NEW so I have no idea what exceptions are, or try, nor do I care to use them considering my teacher hasn't assigned anything like that yet.
My project is to make a program that gives you the assessment value, and the property tax upon entering your property price. Here is the code I came up with (following the video from my class, as well as in the book)
ASSESSMENT_VALUE = .60
TAX = 0.64
def main():
price = float(input('Enter the property value: '))
show_value(value)
show_tax(tax)
def show_value():
value = price * ASSESSMENT_VALUE
print('Your properties assessment value is $', \
format(value, ',.2f'), \
sep='')
def show_tax(value,TAX):
tax = value * TAX
print('Your property tax will be $', \
format(tax, ',.2f'), \
sep='')
main()
Upon running it, I get it to ask "blah blah enter price:" so I enter price then I get a huge red error saying
Traceback (most recent call last):
File "C:/Users/Gret/Desktop/chapter3/exercise6.py", line 41, in <module>
main()
File "C:/Users/Gret/Desktop/chapter3/exercise6.py", line 24, in main
show_value(value)
NameError: name 'value' is not defined
But I DID define 'value'... so why is it giving me an error??
Python is lexically scoped. A variable defined in a function isn't visible outside the function. You need to return values from functions and assign them to variables in the scopes where you want to use the values. In your case, value is local to show_value.
When you define a function, it needs parameters to take in. You pass those parameters in the brackets of the function, and when you define your function, you name those parameters for the function. I'll show you an example momentarily.
Basically what's happened is you've passed the function a parameter when you call it, but in your definition you don't have one there, so it doesn't know what to do with it.
Change this line:
def show_value():
To this line:
def show_value(price):
And show_value to show_value(price)
For example:
In this type of error:
def addition(a,b):
c = a + b
return c
addition() # you're calling the function,
# but not telling it the values of a and b
With your error:
def addition():
c = a + b
return c
addition(1,2) # you're giving it values, but it
# has no idea to give those to a and b
The thing about functions, is that those variable only exist in the function, and also the name of the parameters doesn't matter, only the order. I understand that's frustrating, but if you carry on programming with a more open mind about it, I guarantee you'll appreciate it. If you want to keep those values, you just need to return them at the end. You can return multiple variables by writing return c, a, b and writing the call like this sum, number1, number2 = addition(1,2)
Another problem is that I could call my addition function like this:
b = 1
a = 2
addition(b,a)
and now inside the function, a = 1 and b = 2, because it's not about the variable names, it's about the order I passed them to the function in.
You also don't need to pass TAX into show_tax because TAX is already a global variable. It was defined outside a function so it can be used anywhere. Additionally, you don't want to pass tax to show_tax, you want to pass value to it. But because show_value hasn't returned value, you've lost it. So return value in show value to a variable like so value = show_value(price).
I have some code getting data and then selecting it in order. For this I use simple maps that I may later access with ease (I thought..).
I use the following code within a loop to insert maps to another map named "companies":
def x = [:]
x.put(it.category[i], it.amount[i])
companies.put(it.company, x)
And I can surely write the result out: [Microsoft:[Food:1], Apple:[Food:1]]
But then, when I am about to get the food value of each company it always is null. This is the code I use to get the values:
def val = companies.get(it.company).get(key.toString())
def val = companies[it.company][key] // doesn't make a difference
Val is always null. Can someone help and / or explain why I have this error. What am I doing wrong? I mean, I can clearly see the 1 when I print it out..
My guess is that it.category[i] and key are completely different types...
One thing you could try is:
x.put(it.category[i].toString(), it.amount[i])
and then
def val = companies[it.company][key.toString()] // doesn't make a difference
The solution was simple to make the category as a string:
x.put(it.category[i].toString(), it.amount[i])
And after that little fix it all works as expected.