user3082366
user3082366

Reputation: 3

python how to make list and print it

hi I am very very new in python and write a function

def makeList(x,c):

  if(isinstance( x, int )) and (isinstance(x,chr)):
    mylist = []
    for i in range(c):
    mylist.append(x)
    print mylist
  else:
      print ' Sorry, but 'Hello' is not a valid length.'
      return

it simply define a function and print the list. I just can not run it and out put like this

>>> myList = makeList('a',5)
>>> myList
  ['a','a','a','a','a']

>>> makeList(3,12)
  [3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3]

>>> myList = makeList(7,"Hello")
  Sorry, but 'Hello' is not a valid length.
>>> myList 
  None 

I have a error when I run it can somebody tell me why? thank u veryvery much

Upvotes: 0

Views: 104

Answers (3)

Diegomanas
Diegomanas

Reputation: 162

Did you realised that your parameters are the other way around in the last call?

>>> makeList(3,12)
  [3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3]
>>> myList = makeList(7,"Hello")

That may be why doesn't work that time.

Also have in mind the suggestion done of change from chr to str

Upvotes: 0

Guy Gavriely
Guy Gavriely

Reputation: 11396

adding to @Christian answer, in python you'd use duck typing instead of checking the instance type, one version of makeList can be:

 >>> def makeList(x,c):
 ...     try:
 ...         return [x]*c
 ...     except TypeError:
 ...         print " Sorry, but 'Hello' is not a valid length."
 ... 
 >>> 
 >>> makeList(7,"Hello")
  Sorry, but 'Hello' is not a valid length.
 >>> makeList(3,12)
 [3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3]
 >>> makeList('a',5)
 ['a', 'a', 'a', 'a', 'a']

also see https://softwareengineering.stackexchange.com/questions/175655/python-forgiveness-vs-permission-and-duck-typing

Upvotes: 1

Christian Tapia
Christian Tapia

Reputation: 34156

There is no chr type in Python, use str instead. From Python Docs:

The items of a string are characters. There is no separate character type; a character is represented by a string of one item.

Also I think you want to check if c is an integer and x is a str:

if(isinstance(c, int)) and (isinstance(x, str)):

Also, you have to indent the line

mylist.append(x)

so it is in the body of the for loop. And in order to make your function makeList return a list, you have to add a return statement:

return mylist

Your code will look like:

def makeList(x, c):
    if(isinstance(c, int)) and (isinstance(x, str)):
        mylist = []
        for i in range(c):
            mylist.append(x)
        return mylist
    else:
        print " Sorry, but 'Hello' is not a valid length."
        return

Upvotes: 1

Related Questions