GV

GeezerVison

The World Wide Web, restored to 800 pixels of glory.

Home|About|Gaming cabinet|Archives|How it works|Starter sites

On this site

  • Home
  • Why Practice Python?
  • Why Chilis?
  • Resources for learners
  • Exercises
  • Blog
  • About

This view

  • Original page
  • New address

GeezerVison is showing www.practicepython.org — 04 Divisors

Practice Python

  • follow us in feedly
  • Atom feed XML
Follow @practice_python

Beginner Python exercises

  • Home
  • Why Practice Python?
  • Why Chilis?
  • Resources for learners
  • Exercises
  • Blog
  • About

26 February 2014

Divisors

Exercise 4 (and Solution)

Create a program that asks the user for a number and then prints out a list of all the divisors of that number. (If you don’t know what a divisor is, it is a number that divides evenly into another number. For example, 13 is a divisor of 26 because 26 / 13 has no remainder.)

Discussion

The topics that you need for this exercise combine lists, conditionals, and user input. There is a new concept of creating lists.

There is an easy way to programmatically create lists of numbers in Python.

To create a list of numbers from 2 to 10, just use the following code:

  x = range(2, 11)

Then the variable x will contain the list [2, 3, 4, 5, 6, 7, 8, 9, 10]. Note that the second number in the range() function is not included in the original list.

Now that x is a list of numbers, the same for loop can be used with the list:

  for elem in x: 
    print elem

Will yield the result:

  2
  3
  4
  5
  6
  7
  8
  9
  10

Happy coding!

Enjoying Practice Python?

Buy me a coffee

Share the fun!

« Previous exercise Next exercise »

Explore Yubico
Explore Yubico
comments powered by Disqus
Copyright Michele Pratusevich, 2014-2022.
Advertising disclosure
You are visitor 01402809 — GeezerVison does not store the pages you look up.
Best viewed with Netscape Navigator 4.7 or Internet Explorer 6 at 800×600. No cookies required.