I ask the user to enter it's name and I print the pattern eg: 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()
I have written this program where am I wrong please help. A beginner here
CodePudding user response:
Others have given you code that does what you want it to do; I'll try to explain why your code doesn't do what you think it would do.
#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()
The above line s.split()
uses the default-behaviour of the built-in str.split()
method. Which does the following if we look at the help-file:
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.
That means that it will try to split your given string on each whitespace-character inside of it and return a list containing the results. "WORLD".split()
would therefore return: ['WORLD']
i=len(l)
This returns 1, because the result of s.split()
.
Now let's break down what happens inside of the for-loop.
# 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()
All of this results in only the print()
statement inside of the first for-loop being executed, and it will only be executed once because of how the range
-function works with the values it has been given.
CodePudding user response:
Don't complicate the code unnecessarily. A string you can think of as a list of characters on which to iterate, without resorting to splitting.
If you use Python's List Slicing, you can point to the positions of the characters you are interested in printing.
Your code becomes:
name = input("Enter your name: ")
for i in range(len(name)):
print(name[:i 1])
CodePudding user response:
We can do this without using 2 loops.
s = input("Enter your name")
for i in range(len(s) 1):
print(s[:i])
#Output:
W
WO
WOR
WORL
WORLD