Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/349.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
在Python中将不带引号的字符串参数传递到函数中_Python_String_Function_Arguments - Fatal编程技术网

在Python中将不带引号的字符串参数传递到函数中

在Python中将不带引号的字符串参数传递到函数中,python,string,function,arguments,Python,String,Function,Arguments,我有一个Python函数,其中参数是一个字母和数字字符串 下面的第一个函数调用(函数定义后)起作用,第二个函数调用返回无效语法错误: def my_function(user): firstNumber=int(user[0]) secondNumber=int(user[2]) if user[1]!="d": quit() else: return firstNumber+secondNumber my_f

我有一个Python函数,其中参数是一个字母和数字字符串

下面的第一个函数调用(函数定义后)起作用,第二个函数调用返回无效语法错误:

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)

如果用户在参数中输入字符串而不加引号,我如何才能优雅地处理(例如,简单地退出程序),这样我就不会出错?

感谢大家这么快的评论


答案似乎是,如果字符串参数周围没有引号,它显然不再是字符串。此外,我将假设用户在使用函数时会传递正确的python语法。

如果没有双引号或单引号,它是一个变量而不是字符串。@6thSense:不够,变量以数字开头是无效的:具体怎么说?您试图实现什么?避免语法错误的方法是使用正确的语法。您有没有理由不想在这里使用正确的语法?如果您的意思是其他编写Python代码的人将使用该函数,那么他们必须有能力这样做。在本例中,我所说的胜任,是指他们应该知道上面的第二种形式是语法错误。你不能在你的函数中处理它,因为解释器永远不会走那么远。也许你应该提供一个例子来说明你希望实现的目标,因为从所有这些评论中你可以看到,目前还不清楚。