繁体   English   中英

用 python 中的模式打印名称

[英]to print name with a pattern in python

我要求用户输入它的名字并打印模式,例如:W WO WOR WORL WORLD

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()

我写了这个程序哪里错了请帮忙。 这里是初学者

其他人已经为您提供了可以执行您希望它执行的操作的代码; 我将尝试解释为什么您的代码没有按照您的预期执行。

#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函数如何处理给定的值,它只会执行一次。

不要不必要地使代码复杂化。 一个字符串,您可以将其视为要迭代的字符列表,而无需求助于拆分。

如果你使用 Python 的List Slicing ,你可以指向你感兴趣的字符的位置来打印。

您的代码变为:

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

我们可以在不使用 2 个循环的情况下做到这一点。

s = input("Enter your name")

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

#Output:
W
WO
WOR
WORL
WORLD

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM