debugging 在python中使用模式打印名称

lymgl2op  于 2022-11-24  发布在  Python
关注(0)|答案(3)|浏览(116)

我要求用户输入它的名称,然后打印模式,例如:世界

s=input("Enter your name")
l=s.split()
i=len(l)
for m in range(0,i):
    for s in range(0,m):
        print(s)
    print()

我已经写了这个程序我哪里错了请帮助。一个初学者在这里

cgvd09ve

cgvd09ve1#

其他人已经给了你代码,你希望它做什么;我将试着解释为什么您的代码没有做您认为它会做的事情。

#s=input("Enter your name")
# Let's pretend that the given word from the user was 'WORLD' as in your example.
s = "WORLD"
l=s.split()

上面的s.split()行使用内置str.split()方法的默认行为。如果我们查看帮助文件,它会执行以下操作:

split(self, /, sep=None, maxsplit=-1)
    Return a list of the words in the string, using sep as the delimiter string.

    sep
      The delimiter according which to split the string.
      None (the default value) means split according to any whitespace,
      and discard empty strings from the result.

这意味着它将尝试在给定字符串中的每个空格字符上拆分该字符串,并返回包含结果的列表。因此,"WORLD".split()将返回:['WORLD']

i=len(l)

这将返回1,因为s.split()的结果。
现在,让我们分解一下for循环内部发生的情况。

# This is essentially: for m in range(0, 1) which will only loop once, because range is non-inclusive
for m in range(0,i): 
    # This is range-command will not execute, because the first value of m will be 0
    # Because range is non-inclusive, running range(0, 0) will not return a value.
    # That means that nothing inside of the for-loop will execute.
    for s in range(0,m):
        print(s)
    print()

所有这一切都导致只执行第一个for循环中的print()语句,并且由于range函数如何使用给定的值,它只执行一次。

axzmvihb

axzmvihb2#

我们不需要使用2个循环就可以做到这一点。

s = input("Enter your name")

for i in range(len(s)+1):
    print(s[:i])

#Output:
W
WO
WOR
WORL
WORLD
ui7jx7zq

ui7jx7zq3#

不要不必要地使代码复杂化。可以将字符串看作是要迭代的字符的列表,而无需使用拆分。
如果使用Python的List Slicing,则可以指向要打印的字符的位置。
您的代码变为:

name = input("Enter your name: ")
for i in range(len(name)):
    print(name[:i+1])

相关问题