How to make function input become a string, if it's not? - python

So basically, let's say you define a function and then write something in () brackets after then function. If I write function(gay), it ends up as 'error name not defined' Python2.73
def lenRecur(aStr):
'''
aStr: a string
returns: int, the length of aStr
'''
print type(aStr)
return
def lenRecur2(aStr):
'''
aStr: a string
returns: int, the length of aStr
'''
s = str(aStr)
print type(s)
return
So when I type lenRecur(gay) or lenRecur2(gay), it ends up as an error whatever I do. So is there a way to avoid it? Without using "" quote marks.

No - unless your input is already a variable that holds a string (or another object).
However, you could use a try-except block (but it won't actually do anything if there's an error).
try:
lenRecur(foo)
lenRecur2(foo)
except NameError:
pass

The error occurs before the function even gets called. Python tries to evaluate the arguments before calling the function. So, Python encounters the bare name gay and wonders, "What the hell is that?"
When it fails to find its value in the local, enclosing, global or builtin scopes, it raises a NameError.
There is no way around this. You must clearly specify what you mean. If gay is a string, you must use quotes.

Related

python .lower doesnt work without the (), im curious why

So I came across this but don't fully understand why this is the case:
count = 0
Got_one = 0
while(count<1):
print('\n')
response = input("Did you get one?\n:").lower()#<--This part here
if response == 'yes':
Got_one += 1
#...ect
At one point of the script I had typed up .lower without the (). The code ran fine but the script failed to +1 when I inputted "yes", instead it printed out a value of 0, most likely due to the "Got_one" variable being set to 0 in the very beginning. However, as soon as I typed up the () the code worked as intended and +1 to the value after inputting "yes".
So, why is this the case? Is .lower on its own lowering everything after it or just something I don't understand about Python yet?
.lower() is a built-in method for the String object in Python. The reason you need the parenthesis is to execute the function on the string.
Without the parenthesis, you are simply accessing the String.lower attribute, which is a function pointer. Therefore, without the parenthesis, you are setting response = String.lower, which will not pass the if statement.
the difference is that calling it with no parenthesis is your just calling the method but not the value of that method and calling it with parenthesis your calling the value of that method
The reason for that is because .lower() is a class method, not a class attribute (which would be written as .lower).
Therefore, you have to use parenthesis to indicate that you are trying to call a method.
Since it does not take any arguments, you simply only put empty parenthesis behind it.
A class method is a function that belongs to a class object, in this case a str object.
A class attribute is a variable that belongs to this object.
To add to 1313e's answer, .lower() is actually a built-in method (functions for object classes) that you're performing on the string object (because everything in Python is an object), which is why you call 'this string'.lower() and not, say, lower('this string')
This is because you are merely making a reference to the lower class method (function) of the class object str. For reference:
foo = "ALL CAPS"
bar = foo.lower
bar
>>> <built-in method lower of str object at 0x1038e1570>
bar()
>>> 'all caps'

Passing a string argument, without quotes, into a function in Python

I have a Python function where the argument is a string of letters and numbers.
The first function call (after function definition) below works, the second returns an invalid syntax error:
def my_function(user):
firstNumber=int(user[0])
secondNumber=int(user[2])
if user[1]!="d":
quit()
else:
return firstNumber+secondNumber
my_function("5d40")
def my_function(user):
firstNumber=int(user[0])
secondNumber=int(user[2])
if user[1]!="d":
quit()
else:
return firstNumber+secondNumber
my_function(5d40)
How can I gracefully handle (eg. simply quit the program) if a user inputs a string into the argument without quotes, so that I don't get an error?
Thanks to everyone for commenting so quickly.
It seems that the answer is, that without quotes around a string argument, it is obviously no longer a string. Furthermore, I will assume that the user will pass correct python syntax when using the function.

Python: Substitute variable values before passing to another function

I want to determine whether the input string is a valid function name or not.
Is there any way to substitute the value of the variable before being passed to isfunction call ?
#!/usr/bin/python
def testFunc():
print "Hello world!";
return;
myString = "testFunc";
isfunction(testFunc); // This returns **True**
isfunction(myString); // This returns **False**
One way of doing that is using eval, which interprets string as code:
try:
eval(myString)
except NameError:
# not a function
Assuming you want to check to see if there exists a loaded function with You could try this:
try:
if hasattr(myString, '__call__'):
func = myString
elif myString in dir(__builtins__):
func = eval(myString)
else:
func = globals()[myString]
except KeyError:
#this is the fail condition
# you can use func()
The first if is actually unnecessary if you will always guarantee that myString is actually a string and not a function object, I just added it to be safe.
In any case, if you actually plan on executing these functions, I'd tread carefully. Executing arbitrary functions can be risky business.
EDIT:
I added another line to be a bit more sure we don't actually execute code unless we want to. Also changed it so that it is a bit neater

Python String Comparison function()

I am checking a piece of Python code I found online (http://www.exploit-db.com/exploits/18305/), and I'm stuck over a piece of code.
To be honest I don't know Python, but I have experience in other programming languages.
The method _computeCollisionChars generates a number of characters and then adds them to a dictionary if they are different. Below is the method signature along with the relevant part for the question. Note: The actual code can be found on the linked source.
def _computeCollisionChars(self, function, count, charrange):
baseStr = ""
baseHash = function(baseStr) # What is this?
for item in source:
tempStr = ""
if tempStr == baseStr:
continue
if function(tempStr) == baseHash: # What type of comparison is this?
# logic goes here...
return
My questions are:
What does the function parameter mean in the method signature?
Most importantly what does function(string) do? Why are there two
checks, and what sort of output does function(tempStr) generate
then?
Thanks a lot guys!
Apparently you can pass any callable object as function to _computeCollisionChars. Then baseHash is initialised as the result of calling function with an empty string as parameter. Inside the loop, the condition reads: if the result of function called with an empty string as parameter equals the baseHash do this and that. Which is kind of senseless, because tempStr is always '' and baseHash never changes (or you didn't post that part).
In the current snippet the second if is never reached, because invariably tempStr == baseStr == ''.
As the commentors pointed out, in the real code tempStr and baseStr do indeed change and function is expected to be a hashing-function (but any other function which takes a string as argument should work).
In Python functions are first class objects, so they can be passed as arguments to other functions just fine. So function(baseStr) is calling the function object passed to _computeCollisionChars.
Note that Python doesn't check that it is a function object passed as an argument - it just implicitly expects this (and the program would crash it is wasn't, raising a TypeError exception).
>>> def f1():
print "Hello world"
>>> def f2(function):
function()
>>> f2(f1)
Hello World
>>> f2("not a callable function")
TypeError: 'str' object is not callable

Function Return But No Value

I have a function defined which includes a return statement but no value is handed back. My code is as follows:
def seed(addy):
# urllib2 stuff is here
seed_result = re.search('<td>Results 1 - \d+ of (\d+)',seed_query) # searches for '<td>Results 1 - x of y', captures 'y'
seed_result = seed_result.group(1) # this is 'y' from above
# there's a call to a different function here which works properly
# other stuff going on here pertaining to addy but seed_result still has my string
# now I want to return the seed_result string...
return seed_result
# ... some code outside of the seed function, then I call seed...
seed(addy)
print "Result is %s" % seed_result
I have tried this with and without defining seed_result outside of the function to "initialize" it but this has no impact on the outcome which is that my print statement at the end yields "Result is " - there's no seed_result. I have also wrapped seed_result in parenthesis in the return statement though I believe how I have it is correct. The parens didn't make a difference.
A set up a very basic, yet similar, function in the Python shell and called it as I do here but that works. Not sure what I'm missing.
Thanks for the feedback and guidance.
You're not using the return value (e.g. assigning it to a variable). Try this:
result = seed(addy)
print "Result is %s" % result
Two ways of solving this:
First, the proper, obvious, and easy way is actually using the returned value:
seedresult = seed(addy)
Or you use a global variable (bad style - avoid at any cost):
seedresult = None
def seed(addy):
global seedresult
...
This is caused by None being assigned to seed_result during the execution of your function.
As Jon Skeet identified, you are doing nothing with the return value of your function. You should also address the issues below, though.
In particular, you are doing nothing with the parameter addy, and searching a global variable seed_query. I imagine the behaviour you are seeing is a result of that.

Categories