Passing a string argument, without quotes, into a function in Python - 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.

Related

How do I stop Python's Sys module's "stdout" and "stderr" write method from returning the numbers of characters written

whenever I use the write method from the stdout or stderr object in Python's built-in "sys" module in Python with the Python interpreter, the method also prints an integer representing the number of characters there are in the string after the string that I provided as an argument for the text parameter for the stdout or stderr method, which is really frustating as I only want the text, not also the string length.
For example:
>>> sys.stdout.write('string')
string6
I only wanted to print "'string'", not the string length (6) as well.
I have tried to solve this problem by using sys.stdout.write('string')[:-1] which I think would also remove the number of characters that is placed after the string
I then found out that the number of characters in the string that I provided as an argument is appearing because I was using the interpreter, and the interpreter prints values that are returned by functions but not printed.
So what I want to do is to call sys.stdout.write('test') but stop it from returning the number of characters in the string that I provided as the text argument. How would I do this?
You cannot stop a ready-made function from doing what it does when you call it. What you can do is stop the Python interpreter from printing the returned value by doing something with it, e. g. assigning it to a variable.
sys.stdout.write also prints the integer after the string that was provided as an argument for the text parameter in the method call because the write method of the stdout object also returns the length of the text parameter's argument, and the Python REPL/Interpreter also prints out returned values, which is the answer for your problem.
So, to stop it from printing out the length of the text string, just assign the sys.stdout.write method call to a variable, as it will call the function and then you can del the variable after it executes, as you will not want the returned number of characters in the string that was provided for the text parameter.
Another solution to this problem is by calling the sdtout object's write method in a function and then calling that function like:
def show_text(txt):
from sys import stdout
stdout.write(txt)
return
show_text('Hello!)

My function for some reason auto-converts a string into a tuple?

I'm very confused here. I'm trying to pass an optional string parameter to my function, but once the parameter is added, it converts the string to a tuple? How can I stop it from doing that or convert back?
I have this:
def fen2grid(note, *optional)
print(optional)
# here it does other stuff
With this when I call it:
fen2grid(example, '.')
now... the print is supposed to print a period. Just .
This is just a test before I use it in the function and it seems to be a good thing that I'm testing it.What it prints is
('.',)
I need the period because I need to work with that (it can be any other symbol too)
Any help would be appreciated!
*args reads an arbitrary number of arguments and encloses them as a tuple. To access them you can simply do print(args[0]) or [print(x) for x in args]
Edit: Keep in mind that neither args or kwargs are keywords, you can replace them for any other placeholder preceded by * or **
I'm trying to pass an optional string parameter to my function
*optional isn't quite how you do that. At least not for default/keyword argument like you are trying to use. That is a tuple.
Try
def fen2grid(note, optional=None)
print(optional)
For more details, see about Defining Functions.

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

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

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.

Calling External Command On Python Without Quotes

Following the advice given in;
Calling an external command in Python
I have been experimenting using the call() function to call an external command, however the command I need to call is being called correctly but it does not like the parameters being passed to it.
This is because the Call function is passing the parameters with ' 's around them.
E.g
test = call(['/opt/program/something/lookup', 'search "bob"'])
The search part must be passed to the command lookup without any characters surrounding it, I have tried a few different permutations of the call function with varying levels of quotes, spaces, lack of commas etc. The second statement - bob, must be within quotes.
Is there a clean way to do this?
Example of return value of test atm;
Error: 'search "bob"' is not a valid command.
This should work - if not then please update the question with specific error text:
test = call(['/opt/program/something/lookup', 'search', '"bob"'])

Categories