JOHN
JOHN

Reputation: 33

Python send string as argument to function

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

Answers (2)

bruno
bruno

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:

  • to write the first i+1 letters of the text it is useless to use a loop, just do print(a[0:i+1])
  • to indent with length-i//2 spaces you can use ' '*(length-i//2)

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

Gabio
Gabio

Reputation: 9504

You can send to d_func a sliced string as a parameter:

text = input("Enter text: ")
d_func(text[:9])
...

Upvotes: 0

Related Questions