Skip to content

Instantly share code, notes, and snippets.

@prodeveloper
Last active February 28, 2017 04:56
Show Gist options
  • Save prodeveloper/59c239c7885ef01c2788afd2d64ceb54 to your computer and use it in GitHub Desktop.
Save prodeveloper/59c239c7885ef01c2788afd2d64ceb54 to your computer and use it in GitHub Desktop.
An introduction to working with loops and lists in python

##Step 1

In programming, recurrence happens a lot. In fact it can be said that the entire essence of programming is to automate recurring steps.

Suppose for example we needed to have python print out a list of all numbers between 1-10 how would we do it?

Lets first create the folder for the lesson. From the terminal type in

mkdir 5lesson
cd 5lesson

Then create your python script

touch count_10.py

Open the script to the main IDE window. Type out

print(0)
print(1)
print(2)
print(3)
print(4)
print(5)
print(6)
print(8)
print(9)
print(10)

When you run this script you should see a listing of all numbers from 1 to 10

A range function can also do the same for you. See http://pythoncentral.io/pythons-range-function-explained/

Create a new file called range_10.py. Inside the file you can now put in range functions

values = range(11)

for i in values:
        print(i)

Note that range method is zero indexed.

Python uses indetation to structure code. See http://www.python-course.eu/python3_blocks.php for a bit more information.

###Assignment:

Can you get the method to print out a number as defined by the user? ie write a script called range_n.py that when run asks for a number and then prints out all the values between 0 and that number.

##Step 2

We can now list out all the numbers but what about say names?

If we wanted list of all students we could start by first creating a file called students_long_form.py

print("Botul Yusuf")
print("Peris Wanjiru")
print("Leila Hassan")
print("Marline Khavele")
print("Joyce Waithaka")

This would then print out all the names. This is of course tedious. Instead we can save it all in a python list.

A list enables us to store a collection of items. See http://introtopython.org/lists_tuples.html

Now create a new file called students_short_form.py

students = ["Botul Yusuf","Peris Wanjiru","Leila Hassan","Marline Khavele","Joyce Waithaka"]
for student in students:
    print(student)

You will note that you get the same results but with a much more compact syntax.

###Assignment:

Create a python list with all your teachers. Running the script should print out their names similar to short form above for students.

##Assignment

Write a script that computes the sum of numbers from 1 to the number given in the input. Eg if given 3 it should return 6 1+2+3 = 6 if given 4 should return 10 1+2+3+4. Use loops to carry out the computation

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment