想要从输出从0到pos的数字,并用-连接
def add_connection(pos):
"""
A function that inserts "-" between each number in
the range of 0 to the input integer (0 and input
integer both inclusive).
---
Parameters:
pos: a positive integer which represents the upper bound(inclusive)
---
Return the new string after insertions
>>> add_connection(1)
'0-1'
>>> add_connection(3)
'0-1-2-3'
"""
# YOUR CODE GOES HERE #
list=[]
for i in range(0,pos+1):
list.append[i]
list1=[str(x) for x in list]
str="-".join(list)
return str
修改如下:
def add_connection(pos):
list = []
s = " "
for i in range(0, pos + 1):
list.append(i)
list1 = [str(x) for x in list]
s = "-".join(list1)
return s
print(add_connection(5))
函数体中用列表解析式,一行代码即可:
def add_connection(pos):
"""
A function that inserts "-" between each number in
the range of 0 to the input integer (0 and input
integer both inclusive).
---
Parameters:
pos: a positive integer which represents the upper bound(inclusive)
---
Return the new string after insertions
>>> add_connection(1)
'0-1'
>>> add_connection(3)
'0-1-2-3'
"""
# YOUR CODE GOES HERE #
s='-'.join([str(x) for x in range(pos+1)])
return s
print(add_connection(6))
F:\2022\py01>t8
0-1-2-3-4-5-6
def add_connection(pos):
list = []
for i in range(0, pos + 1):
list.append(i)
list1 = [str(x) for x in list]
str1 = "-".join(list1)
return str1
有几个问题,字符转换跟连接不要写在for循环内,定义的变量不能与关键字冲突