[英]Is it possible to call a function that needs a parameter, without it? On python
I'm learning to code on Python 3.x using Exercism.我正在学习使用 Exercism 在 Python 3.x 上编码。 I have to code a conditional (on a secondary file) to return a string depending on a word sent from a main function:我必须编写一个条件(在辅助文件上)以根据从主函数发送的单词返回一个字符串:
User function:用户功能:
def two_fer(name):
if name:
string = "One for " + name + ", one for me."
else:
string = "One for you, one for me."
return string
Main function:主功能:
class TwoFerTest(unittest.TestCase):
def test_no_name_given(self):
self.assertEqual(two_fer(), 'One for you, one for me.')
def test_a_name_given(self):
self.assertEqual(two_fer("Alice"), "One for Alice, one for me.")
def test_another_name_given(self):
self.assertEqual(two_fer("Bob"), "One for Bob, one for me.")
The problem is that , for the first condition in the main function, it calls two_fer()
with no conditional, which results on a fail.问题是,对于主函数中的第一个条件,它调用two_fer()
没有条件,这导致失败。
Main function is supposed to not be modified, is it any way to solve the problem only by the user function?主函数应该不会被修改,有没有办法只通过用户函数来解决问题?
Thanks in advance.提前致谢。
You can change:你可以改变:
def two_fer(name):
to:到:
def two_fer(name=None):
which will make name None by default默认情况下,这将使 name None
If you give name
a default value of "you"
, you can call the function without an explicit argument and get rid of the if
statement altogether.如果你给name
一个默认值"you"
,你可以在没有显式参数的情况下调用该函数并完全摆脱if
语句。
def two_fer(name="you"):
return "One for " + name + ", one for me"
or better yet,或者更好,
def two_fer(name="you"):
return "One for {}, one for me".format(name)
You can use a default parameter ie None and check whether the function received any parameter or not.您可以使用默认参数即 None 并检查函数是否收到任何参数。
User Function:用户功能:
def two_fer(name = None):
if name != None:
string = "One for " + name + ", one for me."
else:
string = "One for you, one for me."
return string
The above code will execute the else part if the method two_fer is called without any parameters.如果在没有任何参数的情况下调用方法 two_fer ,则上述代码将执行 else 部分。
Use a default parameter like following使用如下所示的默认参数
def two_fer(name=None):
if name:
s = "One for " + name + ", one for me."
else:
s = "One for you, one for me."
return s
Also a tip, avoid assigning variable names as keywords for eg string in your case as it is a standard library and it is just a good practice to avoid it.还有一个提示,避免将变量名指定为例如字符串的关键字,因为它是一个标准库,避免它只是一个好习惯。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.