### Thread: Help, For and while Loop

Page 1 of 2 12 Last
• Jump to page:
1. No Profile Picture
Contributing User
Devshed Newbie (0 - 499 posts)

Join Date
Mar 2005
Posts
51
Rep Power
10

#### Help, For and while Loop

Hello,

I am pord, I am kind of new to python programming.......

Can anybody out there kindly teach or help me how to write program that prompts the user to input an integer between 1 to 100 and outputs a list of it's factors using a For loop

The second problem is to write a program that prompts the user to enter an integer greater than 50 and it must also be odd numbers.........using While loop.

I will appreciate it very much to hear from you cool programmers soon.
Last edited by pord_80; March 23rd, 2005 at 10:15 AM. Reason: Wanted to state Python programming...
2. Code:
factor = []
printed = []
while True:
n = input('Number: ')
if n in range(1, 100):
for number in range(1, 100):
a = n / number
b = a * number
if b == n:
factor.append(number)
for item in factor:
if item in printed:
pass
else:
print item
printed.append(item)
else:
pass
I had to put a little thought into this one. This is the program for your first request. Maybe I'll work on the second.
3. No Profile Picture
sfb
Contributing User
Devshed Novice (500 - 999 posts)

Join Date
Nov 2003
Posts
624
Rep Power
34
Can anybody out there kindly teach or help me how to write program that prompts the user to input an integer between 1 to 100 and outputs a list of it's factors using a For loop
I don't quite understand how one could teach such a program...
the purpose of the question seems to be to get you to understand breaking a problem into steps and then converting those steps to Python by doing it.

Here's one possible answer:
Code:
#Step 1: Prompt the user for a number
number = input("Enter a number: ")

# Step 2: Test if the number is between 1 and 100
if 1 <= number <= 100:
print "Factors of ", number, ": "

# Step 3: Check for factors by
# finding all the numbers 0 - N and
# testing if N divides evenly by each one..

for x in range(number):
if number % x == 0:
print x,

Code:
while True:
number = input("Enter an odd number greater than 50: ")
if number > 50 and number % 2 != 0:
break
4. Originally Posted by pord_80
Hello,

I am pord, I am kind of new to python programming.......

Can anybody out there kindly teach or help me how to write program that prompts the user to input an integer between 1 to 100 and outputs a list of it's factors using a For loop

The second problem is to write a program that prompts the user to enter an integer greater than 50 and it must also be odd numbers.........using While loop.

I will appreciate it very much to hear from you cool programmers soon.
Hey pord, is this class-work? I mention this because you will generally get a slightly different responce if it is – people won't write the program for you, but they will guide you though what needs to be done .

Take care,

Mark.
5. I already knew that it was class work from the start just because of the kind of program he needed built and by many others asking similar questions. I was pretty bored at the time so I figured I'd make the first program for him.
6. Originally Posted by †Yegg†
I already knew that it was class work from the start just because of the kind of program he needed built and by many others asking similar questions. I was pretty bored at the time so I figured I'd make the first program for him.
LOL we all guessed Yegg I was just pointing out the situation: it's not forum policy to do homework for you however if someone does decide to do it I'm sure as hell not making a big deal .
7. Lol. Ok.
PS. I wonder if anyone will do my homework, 8>
8. No Profile Picture
Contributing User
Devshed Newbie (0 - 499 posts)

Join Date
Mar 2005
Posts
51
Rep Power
10

#### It is not.........

Originally Posted by †Yegg†
Lol. Ok.
PS. I wonder if anyone will do my homework, 8>

Well you might say it's class work ,but it is not.......
I had other class work which I had to work with.....
But these 2 questions was to test my knowledge of the program.
We have just about the same forum at school>>>> But nobody could do it.
That is why I asked here.
Pord.
9. No Profile Picture
Contributing User
Devshed Newbie (0 - 499 posts)

Join Date
Mar 2005
Posts
51
Rep Power
10

#### Thanks for the help..

Originally Posted by pord_80
Well you might say it's class work ,but it is not.......
I had other class work which I had to work with.....
But these 2 questions was to test my knowledge of the program.
We have just about the same forum at school>>>> But nobody could do it.
That is why I asked here.
Pord.

Thank you for you time and knowledge ....

Thank you for not judging>>>>>>>
I thought the purpose for these forum was to help other up and coming programmmers......
10. Originally Posted by pord_80
Thank you for you time and knowledge ....

Thank you for not judging>>>>>>>
I thought the purpose for these forum was to help other up and coming programmmers......
Oh, it is. However, writing a classwork program for you isn't helping you. The whole purpose of classwork tasks is in the experience of performing the task, and having someone else do it doesn't give you that experience. Hence, while we'll help you by explaining how it can be done, we generally won't do the work for you.

Actually, some of us might if you pay us to, I guess (deperation can drive people to many things they wouldn't do otherwise), but that's called Cheating with a capital C and is likely to get you expelled if you're caught. And trust me on this, the schools have some very effective ways of detecting cheating these days.

Enough of that. What you need, really, are explanations rather than code - the whole "teach a man to fish" thing, grok? Anyway, the basic idea of a loop is a block of code that gets repeated until a certain state is reached. A while: loop is a general loop consisting of a conditional expression - something that is either true or false - and a loop body, which is the part that gets repeated. Here's a simple example that will keep printing a message endlessly until you break out of the program:
Code:
while True:
print("Help, I'm stuck in a loop!")
Just like with if: statements, the loop body is the indented code that is immediately after the conditional line; in Python, the body of a loop (or conditional, or function) continues until the first line that is at the same indent level as the first line.

To look at the second problem (as I interpret it), we can write it this way
Code:
# this part is before the while loop
n = input ("Please enter an odd number less than 50: ")

while (n > 50) or (n % 2 == 0):   # this is the conditional for the while loop
# this part is in the loop body
print n, (" isn't an odd number under 50.")
n = input ("Please try again: ")

# this is after the loop body
print n, " is an odd number less than 50."
print "Thank you."
(The % is the modulo or remainder operator.)

The for: loop is a more specialized type of loop: it takes a collection such as a list and goes through each of the items in the collection in turn, repeating once for each item. This is referred to a definite loop, because it has a fixed number of repetitions set at the start of the loop, as opposed to an indefinite loop like a while:, which continues until some condition is met. Here is a simple for: loop which prints the elements of a three-element list (EDIT: Thank you, Netytan, for pointing out the mistake here):
Code:
for n in ["Hello", ",", "World!"]:
print n,
You can nest different types of conditionals and loops, like so:
Code:
# this part is before the while loop
test = "Y"

while test == "Y":
n = input("Enter a number: ")

if n < 50:
print "Counting from", n, "to 50"
# range()is a special built-in function which creates
# a list of numbers starting with the first number
# and ending with one less than the second number.
for x in range(n, 50):
print x,

# this is after the end of the for: loop
print 50

else:
print n, "is over 50"

#this is after the end of the if statement

# raw_input() reads in text without interpreting it
test = raw_input("If you want to do that again, type 'Y' ")

# this is after the end of the while loop
print "Thank you"
Did you have any questions about the code that's been posted? Do you think you understand how while: and for: loops work now, or do you want a further explanation?

#### Comments on this post

• sfb agrees
• netytan agrees : Nice and clear :).
Last edited by Schol-R-LEA; March 25th, 2005 at 02:44 AM.
11. Just to add a bit here: in the while: loop program, you could simplify the while clause by replacing it with

Code:
while (n > 50) or IsEven(n):
However, to do this you would have to define the function IsEven(). If your professor hasn't gotten around to explaining functions yet, I'll do so now.

A function (also known as a procedure or subroutine) is basically a name for a block of code. To write a function, you use a def: expression. For example, if you want a function that prints an asterisk, you could write

Code:
def star():
print '*',  # EDIT: restored the trailing comma
then, to use it, you would simply enter
Code:
star()
The advantage of this is that if you have to do the same thing in more than one place, you can define a function, and then call it wherever you need to do that thing. This is especially useful for complex operations. It also allows you to break a large program into smaller parts, making it easier to finish and understand. Furthermore, it allows you to have separate files just of useful functions, which can be used in more than one program; this is what is called a function library. Finally, as in the case if IsEven(), it can simply be used to make the code easier to read.

Now, you'll notice that the function name has a pair of parentheses after it. This is because a function can be written to use a special kind of variable called a parameter, or argument (these terms are usually used interchangably, but there's actually a subtle difference between an argument and a parameter, which I'll explain in a moment). These allow you to tell give a value to the function, which it can then use as part of itself. for example, if you wanted a function which printed an number of stars which you told it to, you could write:
Code:
def stars(n):
for x in range(0, n):
star()
To call it so that it prints out a line of 5 stars, you would write
Code:
stars(5)
Now, as I said, parameters and arguments aren't quite the same thing; technically, the parameter is the variable that is defined in the function definition, while the argument is the actual value it is called with. Thus, in this example, the parameter is n, while the argument is 5.

Functions can take more than one parameter; for example, this function prints a box of asterisks x characters wide and y characters high:
Code:
def box(x, y):
stars(x)
print
for i in range(1, y - 1):
star()
for j in range(1, x - 1):
print " ",
star()
print
stars(x)
the number of parameters a function has is called its arity, though the term doesn't get used very often.

There is one last thing to know about functions, and that is that they can give back a value as well. For example, a function which takes two numbers and returns the greatest common denominator between them:

Code:
def gcd(x, y):
if y == 0:
return x
else:
return gcd(y, x % y)
Notice that this function does something very funny: it calls itself. This is a way of looping called recursion, as opposed to loops like while: or for:, which are a type called iteration. This works because each time the function is called, it creates a new version of the parameters, so they never need to overwrite the old version (actually, the interpreter may sometimes overwrite them, as a way of optimizing the call, if it knows the function won't need them again; this is what is called tail recursion elimination, and it effectively turns a recursive function into an iterative one automagically. The gcd() function is an example of a tail recursive function). Anything that can be done with iteration can be done with recursion, and vis versa. While iterative loops are usually faster and often take up less memory, recursion is often the easier way to solve a problem.

Thus, to write the IsEven() function, we'd simply write something like

Code:
def IsEven(x):
return (x % 2) == 0
Last edited by Schol-R-LEA; March 25th, 2005 at 07:18 PM.
12. [QUOTE=Schol-R-LEA]Here is a simple for: loop which prints out a list of numbers from 10 to 20:
Code:
for n in ["Hello", ",", "World!"]:
print n,
...
[QUOTE]

Odd way to print to the numbers 10 to 20 but I can see where you we're going . Here's the example.

Code:
>>> for each in range(10, 21):
...     print each
...
10
11
12
13
14
15
16
17
18
19
20
>>>
Easily done eh, take care guys.

Mark.
13. smacks self on forehead D'oh! I forgot to change the wording when I changed the examples around. I'll go fix it right now. Thanks for pointing it out.
Last edited by Schol-R-LEA; March 25th, 2005 at 02:46 AM.

14. This works a little better in the cute box example:
Code:
def star():
print '*',
Uses a comma to stay on the line.
15. No Profile Picture
Contributing User
Devshed Newbie (0 - 499 posts)

Join Date
Mar 2005
Posts
51
Rep Power
10

#### Hello

Well I am begining to get the hand of how these programs work>>>>>
Thanks for the bringing it to my level.
I am so happy I even wrote a program myself......
Please let me know if I did it good or bad>>>>>
But I know it works alright after running it......

So all I want is to know if I did it good, or did I take the easy way out?. Nothing more.

print " This program prints and outputs the sqaures",
print " of numbers 1 to 20 in a column\n"

for i in range (1,21):
print i**2
Page 1 of 2 12 Last
• Jump to page: