Ok.. so I just started python (just = 3 hours ago). I have basic input and output set. Hell I even understand slicing and stuff (OMG SUBSTRINGS SO MUCH EASIER ON PYTHON :O ) but Im finding it not so easy to understand how to use for loops (silly me. I know -.-)

So I was hoping if someone could explain to me how they work in python and what's what in the syntax.

Cheers.


EDIT: Also, how can I just declare a variable and use it later? for example, like in java:

int a;
//lines of codes... probably a few lines later
a = 4;
//or the user can input the number of his choice... Im not picky

Recommended Answers

All 4 Replies

A Python for-loop is pretty much like Java's for-each loop, where instead of going through the loop with an incrementing value each time, you go over a list of values, instead. Here's a simple example.

classes = ["English","Math","History","Physics"]
for s in classes:
    print s

If you prefer the more 'traditional' for-loops, you can use this template.

classes = ["English","Math","History","Physics"]
for i in range(0,4):
    print classes[i]

This code is analogous to the for(int i=0; i<5; i++) that's used in C++ and Java.

As for declaring variables, you don't need to declare them in Python. You can just pull them out of nowhere as you need them and start using them (though it's a healthy practice to initialize them at the beginning of the code block).

A Python for-loop is pretty much like Java's for-each loop, where instead of going through the loop with an incrementing value each time, you go over a list of values, instead. Here's a simple example.

classes = ["English","Math","History","Physics"]
for s in classes:
    print s

If you prefer the more 'traditional' for-loops, you can use this template.

classes = ["English","Math","History","Physics"]
for i in range(0,4):
    print classes[i]

This code is analogous to the for(int i=0; i<5; i++) that's used in C++ and Java.

As for declaring variables, you don't need to declare them in Python. You can just pull them out of nowhere as you need them and start using them (though it's a healthy practice to initialize them at the beginning of the code block).

uh huh. I get it a bit now... as for the variable. So if I wanted to initialize ALL the variables I wanted to use in the beginning of me writing the code (as in they are just there, without values for the moment), and all those variables were to be given values by the users when they are prompted, how would I initialize/pull them out? I just write the names and thats it? a better question would be, is it necessary to give a value to the variable when you type it for the first time?

The for loop is really an iterator, it iterates through sequences ...

# here the sequence is a string
name = "paul"
for c in name:
    print(c)

""" result >>>
p
a
u
l
"""

# range(start, stop, step) creates an iterator if integer values
# range starts from 0 (default) to less than stop in steps of 1 (default)
# so this should iterate from 0 to less than 3 in steps of 1
for k in range(3):
    print(k)

""" result >>>
0
1
2
"""

# let's not use any defaults
for k in range(10, 21, 5):
    print(k)

""" result >>>
10
15
20
"""

# or use negative steps
for k in range(99, 70, -10):
    print(k)

""" result >>>
99
89
79
"""

Also Python knows by inference that name is a string since you put paul in string quotes.

Before you use a variable's contents you have to assign a value to it, so Python knows the type. For instance ...

# by inference x and y are both floating point numbers
x = 1.45
y = 3.55
print(x + y)  # 5.0

# by inference x and y are both integers
x = 7
y = 5
print(x * y)  # 35

# by inference x is an integer and y is a string
x = 7
y = "hello "
print(y * x)  # hello hello hello hello hello hello hello

Here is an example where the variable total has never been initiated ...

# this will give you an error ...
# NameError: name 'total' is not defined
# since Python does not know at what value total starts with
# or what type it is
mylist = [1, 2, 3, 4, 5]
for item in mylist:
    total += item

To fix it give total a value and and by inference a type ...

total = 0
mylist = [1, 2, 3, 4, 5]
for item in mylist:
    total += item

print(total)  # 15

You will also quickly discover that Python can handle very large integer numbers. Here we calculate the factorial of a number n, which is 1*2*3*4*5*6*7* ... n

# calculate the factorial of 30
factorial = 1
limit = 30
for x in range(1, limit+1):
    factorial *= x

print(factorial)       # 265252859812191058636308480000000

The for loop is really an iterator, it iterates through sequences ...

# here the sequence is a string
name = "paul"
for c in name:
    print(c)

""" result >>>
p
a
u
l
"""

# range(start, stop, step) creates an iterator if integer values
# range starts from 0 (default) to less than stop in steps of 1 (default)
# so this should iterate from 0 to less than 3 in steps of 1
for k in range(3):
    print(k)

""" result >>>
0
1
2
"""

# let's not use any defaults
for k in range(10, 21, 5):
    print(k)

""" result >>>
10
15
20
"""

# or use negative steps
for k in range(99, 70, -10):
    print(k)

""" result >>>
99
89
79
"""

Also Python knows by inference that name is a string since you put paul in string quotes.

Before you use a variable's contents you have to assign a value to it, so Python knows the type. For instance ...

# by inference x and y are both floating point numbers
x = 1.45
y = 3.55
print(x + y)  # 5.0

# by inference x and y are both integers
x = 7
y = 5
print(x * y)  # 35

# by inference x is an integer and y is a string
x = 7
y = "hello "
print(y * x)  # hello hello hello hello hello hello hello

Here is an example where the variable total has never been initiated ...

# this will give you an error ...
# NameError: name 'total' is not defined
# since Python does not know at what value total starts with
# or what type it is
mylist = [1, 2, 3, 4, 5]
for item in mylist:
    total += item

To fix it give total a value and and by inference a type ...

total = 0
mylist = [1, 2, 3, 4, 5]
for item in mylist:
    total += item

print(total)  # 15

You will also quickly discover that Python can handle very large integer numbers. Here we calculate the factorial of a number n, which is 1*2*3*4*5*6*7* ... n

# calculate the factorial of 30
factorial = 1
limit = 30
for x in range(1, limit+1):
    factorial *= x

print(factorial)       # 265252859812191058636308480000000

wow! I love the fact that it can handle big numbers :D I made a few programs to calculate the Fibonacci sequence upto the nth term, factorial and stuff in java (using for loops... still have to do recursion) and the program worked fine until I entered a particular number which would screw it up :P why didn't I discover python before :O :)

EDIT: OMG! I used your program to calculate the factorial of 700 :O WHOA! LIKE SERIOUSLY WHOA!

EDIT 2: scratch that... i did it for 2010 as well... OH MY GOOD LORD! I LOVE PYTHON NOW :D

PS. Topic closed

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.