It is currently 27 Feb 2021, 12:03

• Featuring Members' Works (Image Attachments) •
1: member
2: member
3: member
4: member
5: member

GIMP/GL:  Tutorials | Tips | Questions | Interests | Script Requests
Recommendations:  Index | Top 10
Resources:  Python-Fu Plug-ins | Scheme-Fu Scripts | GIMP
Python:  🡆 Lessons | Questions | Exercises
The Arts:  GIMPed | GIMPed Photos | Other | Contests | Public Domain Images | Isolated Images | Blender
Inkscape
Social:  Say Hello | Anything Goes | Shares | FCSP

Ranges and For loops in Python

Simple lessons to get your started in Python language
tim
GL Blogger

Ranges and For loops in Python

Post#1 by tim » 09 Nov 2018, 16:12


Now that we know how to create lists in Python, let's move onto ranges in Python.

In python to create a range (an ordered sequential list of numbers), we can use the range function. For example, if we wanted a variable my_range to hold a list of numbers from 1 to 10, we can use
my_range = range(1,11)
range function accepts 2 parameters, start and end and it'll generate those numbers while excluding the last number.
You can optionally pass in a 3 number to use as the step parameter which is defaulted to 1 so for example if you wanted a list of numbers that goes backward from 11 to 1 you can use
my_range = range(11,0,-1)

You can create a loop that loops over each element of a list and execute some code (inside the loop indicated by indentation that is one level deeper after the for loop statement) by using:

Code: Select all

for item in range(1,11):
    print (item)
The indentation (of the print statement) of the code after the for loop statement indicates that that code belongs to the loop. You can have multiple lines of code to run in the loop. You'll just have to indent the lines the same way to indicate that they're the same block of code.

Notice the colon (:) at the end of the for statement indicating that the beginning of a block of code.

So the loop will loop over all items of range(1,11) (1-10) and set item variable to hold the value of current item in list and as it executes it'll print out item each time through the loop.

Try out what you've learned so far here.

Next lesson: If... Else... in Python Previous lesson: Lists in Python
aka Tin

         


GIMP/GL:  Tutorials | Tips | Questions | Interests | Script Requests
Recommendations:  Index | Top 10
Resources:  Python-Fu Plug-ins | Scheme-Fu Scripts | GIMP
Python:  🡆 Lessons | Questions | Exercises
The Arts:  GIMPed | GIMPed Photos | Other | Contests | Public Domain Images | Isolated Images | Blender
Inkscape
Social:  Say Hello | Anything Goes | Shares | FCSP

  • Similar Topics
    Replies
    Views
    Last post

Who is online

Users browsing this forum: No registered users and 1 guest