打印姓名时顺序不一样会报错
本帖最后由 Joyce8888 于 2021-3-27 11:19 编辑【萌新】请大神救助:
以下代码有时可用有时报错。
比如想打印“你好马春花!”
春花马正常
马春花报错
Please tell me your name:
(Enter 'q' at any time to quit.)
First name:chun
Middle name:hua
Last name:ma
Hello,Chun Hua Ma!
Please tell me your name:
(Enter 'q' at any time to quit.)
First name:ma
Middle name:chun
Last name:hua
Traceback (most recent call last):
File "H:/数据练习/python/06001打印你好.py", line 23, in <module>
formatted_name = formatted_name(first_name=f_name, middle_name=m_name, last_name=l_name)
TypeError: 'str' object is not callable
#以下代码:
def formatted_name(first_name, last_name,middle_name=None):
full_name=f"{first_name} {middle_name} {last_name}"
return full_name.title()
while 1:
print("\nPlease tell me your name:\
\n(Enter 'q' at any time to quit.)")
f_name = str(input("First name:")).lower()
if f_name == 'q':
break
m_name = str(input("Middle name:")).lower()
if m_name =='q':
break
l_name = str(input("Last name:")).lower()
if l_name =='q':
break
formatted_name = formatted_name(first_name=f_name, middle_name=m_name, last_name=l_name)
print(f'Hello,{formatted_name}!')
原因在倒数第二行:循环一次后formatted_name被赋值为一个字符串,也就是函数名formatted_name被字符串formatted_name覆盖了,第二次调用就会报错,改个变量名就好了。
def formatted_name(first_name, last_name,middle_name=None):
full_name=f"{first_name} {middle_name} {last_name}"
return full_name.title()
while 1:
print("\nPlease tell me your name:\
\n(Enter 'q' at any time to quit.)")
f_name = str(input("First name:")).lower()
if f_name == 'q':
break
m_name = str(input("Middle name:")).lower()
if m_name =='q':
break
l_name = str(input("Last name:")).lower()
if l_name =='q':
break
formatted_name2 = formatted_name(first_name=f_name, middle_name=m_name, last_name=l_name)
print(f'Hello,{formatted_name2}!') hrp 发表于 2021-3-27 12:04
原因在倒数第二行:循环一次后formatted_name被赋值为一个字符串,也就是函数名formatted_name被字符串form ...
哇塞,感谢大神!
页:
[1]