Python Forum
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
Beginner:Python
#1
Hello,

I am new in Python programming and started reading Python documentation. Few queries I would like to ask:

def fib2(n):  # return Fibonacci series up to n
   """Return a list containing the Fibonacci series up to n."""
   result = []     #why required this?
   a, b = 0, 1
   while a < n:
       result.append(a)    # see below
       a, b = b, a+b
   return result
I'd like to know why it is required to initialize result=[]? However it was stated that it does not require to "declare" variable before assigning to it.

I tried to use it before assigning to it and it said:
"> UnboundLocalError: local variable 'c' referenced before assignment".

Another question I am trying to solve in beginner section of Codechef

Here is the snippet of code:

n,k = (input().split())
print(type(n),type(k))
#str type
n= int(n)
k=int(k)
#int type
print(type(n),type(k))

while(n):
    n=n-1
    num = (input().split())
    print(type(num))
#list type
    num = int(num)
    if(num/k==0):
        ctr=ctr+1
print(ctr)
Initial print statements prints class str class str and class 'int' class 'int'. However, the print inside the while statement prints class 'list'.
Could you please explain why it is of type list?
Any idea/help would be appreciated
Thanks.
Reply
#2
When they say you don't have to declare anything, that means you don't have to say 'result is a list containing integers' anywhere. And you don't, you just assign a list to it. And that is initialization, just like you initialize a and b to 0 and 1 on the next line. You need to assign an empty list to result so that you can use the append method on 6, as the error you got indicates. Without the empty list, Python doesn't know what you mean by append. It can't just guess that append means you want to have a list there. You might want to have some other class with an append method.

In the second case you have two different ways of assigning the value of split. In both cases, split returns a list of strings. When you do the simple assignment of num = input().split() (you don't need parentheses around the input/split), the list output of split is just assigned to num. When you do the more complicate tuple assignment of n,k = (input().split()) (note the comma on the left side of the assignment), Python pulls the individual strings out of the list, and assigns them to n and k.
Craig "Ichabod" O'Brien - xenomind.com
I wish you happiness.
Recommended Tutorials: BBCode, functions, classes, text adventures
Reply


Forum Jump:

User Panel Messages

Announcements
Announcement #1 8/1/2020
Announcement #2 8/2/2020
Announcement #3 8/6/2020