Multiple parameter in Python - python

I am stuck in using multiple parameter through function.
I have two files:
1.py
import function
x=2
y=5
print function.power(x,y)
function.py
import math
def power(*x)
return math.pow(x,x)
Whenever i try to pass multiple parameter to power function, it is giving following error:
Traceback (most recent call last):
File "C:\Examples\1.py", line 33, in
print function.power(x,y)
File "c:\Examples\function.py", line 11, in power
return math.pow(x,x)
TypeError: a float is required

I think you want:
def power(*x):
return math.pow(*x)
This is a form of argument unpacking. within the power function, x is a tuple which can then be unpacked when passed to another function.

that's because *x is actually making x a list.
You really want to make function.py be:
import math
def power(*x)
return math.pow(x[0],x[1])
Why do you really want to know how to do this though? It obviously can't be to pointlessly wrap the math.pow function.

Related

Why my parameter isn't callable for Python?

so i'm trying to learn about classes in python but for some reason i can't get Wiek function working.
i get the error:
Traceback (most recent call last):
File "D:/pythonProject/MEDIUM.py", line 36, in <module>
fafik.Wiek()
TypeError: 'int' object is not callable
class Pies(Ssaki):
def __init__(self, LiczbaKonczynPsa, ImiePsa, WiekPsa):
self.LiczbaKonczyn = LiczbaKonczynPsa
self.Wiek = WiekPsa
self.Imie = ImiePsa
def Przedstaw(self):
print('Ten pies wabi się: ', self.Imie)
def Konczyny(self):
print('Ten pies posiada ', self.LiczbaKonczyn, 'kończyny')
def Wiek(self):
print('Wiek psa wynosi 6')
fafik = Pies(4, 'BOBO', WiekPsa=3)
fafik.Przedstaw()
fafik.Konczyny()
fafik.Wiek()
I'm sorry for asking maybe so stupid question but i truly can't fin solution to my problem.
You're getting the error because you have both a class attribute named Wiek, which in your example is the int 3, and a method called Wiek(), which you try to call on the last line of your example. Since self.Wiek has already been defined as 3, calling fafik.Wiek() is the equivalent of calling fafik.3(), which is invalid.
def Wiek(self):
print('Wiek psa wynosi 6')
self.Wiek = WiekPsa
You have a parameter called Wiek, but also a method called Wiek
When you call fafik.Wiek() python tries to call your parameter Wiek which is an int, and tries to call it as a function which is not possible since it's a int
In any case, don't give a parameter and a function the same name; except for very precise case (getters)
Just rename either the variable Wiek, or the function to a new name and it will work
The problem you have here is that your class has two items having the same name.
An attribute, of type 'int'.
A method.
When you call your function here fafik.Wiek()it understands that you're trying to call the integer attribute as a method.
Just change the name of your function.

Using functions in a dictionary for a menu

I am trying to create a simple menu by utilizing a dictionary instead of a series of if, elif statements. My problem is the functions being called when I declare them as the definition within the dictionary. Also I'm running into an error when trying to call on the dictionary.
I know that I'm missing something with the declaration. It doesn't matter what I put in the definition, if it's executable code then it executes when declared instead of when I call on it.
As far as the problem with calling on the dictionary I'm totally lost, from everything I've read I believe I'm doing it correctly. I've included an overly simplified version of what I'm trying to do that replicates the problems I'm having.
def hello():
print("Hello")
def goodbye():
print("Goodbye")
options = { '1' : hello(),
'2' : goodbye()}
chosen = '1'
options[chosen]()
This is what I get when the above is executed.
Hello
Goodbye
Traceback (most recent call last):
File "main.py", line 12, in <module>
options[chosen]()
TypeError: 'NoneType' object is not callable
And I should just see this.
Hello
Simply remove the parentheses from the functions in the dictionary. Leaving them there causes the functions to be called when the dictionary is declared.
Furthermore you get an error because the values you put into the dictionary are the return values of the functions, i.e., None, and calling None() gets you nowhere ;-)
Just assign the function name as the values in the dictionary
def hello():
print("Hello")
def goodbye():
print("Goodbye")
options = {'1': hello,
'2': goodbye}
chosen = '1'
options[chosen]()

recursive function paradox in Python.. how can it be explained?

I made a very simple function that takes a list of numbers and returns a list of numbers rounded by some digits:
def rounded(lista, digits = 3):
neulist = []
for i in lista:
neulist.append(round(i, digits))
return neulist
However, I mistakenly put the function itself in the code instead of the built-in round() (as in the example below):
def rounded(lista, digits = 3):
neulist = []
for i in lista:
neulist.append(rounded(i, digits))
return neulist
and got this output:
Traceback (most recent call last):
File "<pyshell#286>", line 1, in <module>
rounded(a)
File "<pyshell#284>", line 4, in rounded
neulist.append(rounded(i, digits))
File "<pyshell#284>", line 3, in rounded
for i in lista:
TypeError: 'float' object is not iterable
The question is: how does the interpreter know that it had to apply the function rounded() while evaluating the function rounded() itself? How can it anyway now that rounded() is a function taking floats if it is attempting to interpret that very function? Is there a sort of two cycle procedure to evaluate & interpret functions? Or am I getting something wrong here?
The function is an object. It is created at definition, not when it is called, so if Python didn't know how to use it, it would've raised an error before any calling was done.
However, you called it with a list. During the iteration, the function is called recursively with the first item of the list - presumably, a float. With this float as argument, for i in lista: doesn't make sense anymore, and you have the error.
You've just stumbled upon recursion.
Recursive functions are very common in programming. Consider the following (naive) function for calculating the nth fibbonacci number:
def fib(x):
if x<=2:
return 1
else:
return fib(x-1)+fib(x-2)
The function knows that it calls itself, because the function definition is noted as soon as the interpreter reaches fib(x):. From that point on, fib is defined. For python in particular, since it's a dynamically typed language, there's no difference if you call the function with a integer, a string or a float - all it matters is that the function takes exactly one argument.
There are indeed two processes occurring here. The function is compiled as it's encountered in the source text, then a call is made to it afterward. The body of the function includes a call to rounded, but that's actually kept track of as the name of the function. Check this out:
def fun1(x):
if x == 0:
print x
else:
fun1(x-1)
fun2 = fun1
def fun1(x):
print x
fun2(3)
Here we're defining fun1() with an apparently recursive call to itself. However, after redefining fun1(), the call in the first definition of the function now refers to a different function entirely.

Python Date() Function

I have what may be a dopey question about Python's date function.
Let's say I want to pass the script a date, July 2nd 2013. This code works fine:
from datetime import date
july_2nd = date(2013,7,2)
print july_2nd
Output:
2013-07-02
So now what if I want to pass the date() function a value stored in a variable, which I can set with a function, rather than hard coding 7/2/13, so I try this and get an error:
from datetime import date
july_2nd = (2013,7,2)
print date(july_2nd)
Error message:
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: an integer is required
Can anyone explain what's going on here?
You want to pass in the tuple as separate arguments, using the *args splat syntax:
date(*july_2nd)
By prefixing july_2nd with an asterisk, you are telling Python to call date() with all values from that variable as separate parameters.
See the calls expression documentation for details; there is a **kwargs form as well to expand mapping into keyword arguments.

len(array) works from interpreter, fails when called within function

I have a simple function that works when I enter it in my Jython interpreter manually, but the call to len() fails when I try to run the code as a function.
def calculateChecksum(self, command):
sum = 0
for b in range(len(command)):
sum = sum + command[b-1]
mod = sum % 64
checkbyte = mod & (0xFF)
checksum = checkbyte | 0x80
where command is a jarray.array of bytes (Why am I not using the built-in array type? I ask you: Does it matter? jarray.array is working for everything else, and it clearly works on some occasions, see below)
>>> testarray
array([55, 57, 51], byte)
>>> len(testarray)
3
>>> stage.calculateChecksum(stage, testarray)
Traceback (innermost last):
File "<console>", line 1, in ?
File "....py", line 75, in calculateChecksum
AttributeError: __len__
So I think it's safe to say that this array implements len(), but I don't know why that doesn't always seem to be true. Any idea what's going on here?
Call the method like this:
stage.calculateChecksum(testarray)
Notice that you don't have to explicitly pass stage for the self parameter, that's passed implicitly when you invoke a method over an object (stage in this case.)
You defined def calculateChecksum(self, command): into a class, and when you call a class-method, you do not need to add the self variable. Python adds it for you.

Categories

Resources