Reputation: 33
I am looking to make a text pattern using Python, but I am a little stuck on how to use main() function And send "string" argument to another function "d_func". Plus if the text is long then 9 I want to slice it.
def d_func(a):
length = len(a)
for i in range (0, length,2):
for j in range(length-i//2):
print(' ', end="")
for j in range(0, i+1):
print(word[j], end="")
print()
for i in range (length - 3,-1,-2):
for j in range(length-i//2):
print(' ', end="")
for j in range(0, i+1):
print(word[j], end="")
print()
def main():
text = input("Enter text: ")
if len(text) > 9 :
text[:9] ## slice the text if it bigger then 9 letters
d_func(text)
main()
why i get " 'length' is not defined" error?
Upvotes: 0
Views: 137
Reputation: 32594
why i get " 'length' is not defined" error?
because your indent are not correct. The for loops are out of the function d_func so length is not defined.
Plus if the text is long then 9 I want to slice it.
your line
text[:9]
just extract the first 9 characters of text and loose it immediately, probably you want
text = text[:9]
If you want to get up to last 9 letters use text[-9:] rather than text[:9]
Note you can also call d_func directly with text[:9] without doing the test on the length.
Also in your code word must be a
After corrections :
def d_func(a):
length = len(a)
for i in range (0, length,2):
for j in range(length-i//2):
print(' ', end="")
for j in range(0, i+1):
print(a[j], end="")
print()
for i in range (length - 3,-1,-2):
for j in range(length-i//2):
print(' ', end="")
for j in range(0, i+1):
print(a[j], end="")
print()
def main():
text = input("Enter text: ")
d_func(text[:9])
main()
Execution :
pi@raspberrypi:/tmp $ python3 a.py
Enter text: the long text
t
the
the l
the lon
the long
the lon
the l
the
t
pi@raspberrypi:/tmp $
Note you can simplify a lot your code:
So
def d_func(a):
length = len(a)
for i in range (0, length,2):
print(' '*(length-i//2), a[0:i+1], sep='')
for i in range (length - 3,-1,-2):
print(' '*(length-i//2), a[0:i+1], sep='')
def main():
text = input("Enter text: ")
d_func(text[:9])
main()
Upvotes: 1
Reputation: 9504
You can send to d_func
a sliced string as a parameter:
text = input("Enter text: ")
d_func(text[:9])
...
Upvotes: 0