Forums: » Register « |  Free Tools |  User CP |  Games |  Calendar |  Members |  FAQs |  Sitemap |  Support |
 User Name: Password: Remember me

New Free Tools on Dev Shed!
We're Excited to announce that Dev Shed now has 70 free tools on the site. To learn more, click here!

 Add This Thread To: Del.icio.us   Digg   Google   Spurl   Blink   Furl   Simpy   Y! MyWeb
 « Previous Thread | Next Thread » Thread Tools Search this Thread Rate Thread Display Modes
 Dev Shed Forums Sponsor:
#1
March 23rd, 2005, 07:27 AM
 pord_80
Contributing User

Join Date: Mar 2005
Posts: 51
Time spent in forums: 1 Day 4 h 30 m 3 sec
Reputation Power: 9
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 11:15 AM. Reason: Wanted to state Python programming...

#2
March 23rd, 2005, 12:55 PM
 Yegg`
Contributing User

Join Date: Dec 2004
Location: Meriden, Connecticut
Posts: 1,797
Time spent in forums: 3 Weeks 6 Days 21 h 54 m 27 sec
Reputation Power: 154
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
March 23rd, 2005, 02:35 PM
 sfb
Contributing User

Join Date: Nov 2003
Posts: 624
Time spent in forums: 3 Days 6 h 10 m 21 sec
Reputation Power: 34
Quote:
 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
March 23rd, 2005, 05:58 PM
 netytan
Hello World :)

Join Date: Mar 2003
Location: Hull, UK
Posts: 2,537
Time spent in forums: 1 Week 2 Days 18 h 17 m 47 sec
Reputation Power: 68
Quote:
 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.
__________________
programming language development: www.netytan.com Hula

#5
March 23rd, 2005, 06:34 PM
 Yegg`
Contributing User

Join Date: Dec 2004
Location: Meriden, Connecticut
Posts: 1,797
Time spent in forums: 3 Weeks 6 Days 21 h 54 m 27 sec
Reputation Power: 154
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
March 23rd, 2005, 06:46 PM
 netytan
Hello World :)

Join Date: Mar 2003
Location: Hull, UK
Posts: 2,537
Time spent in forums: 1 Week 2 Days 18 h 17 m 47 sec
Reputation Power: 68
Quote:
 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
March 23rd, 2005, 07:49 PM
 Yegg`
Contributing User

Join Date: Dec 2004
Location: Meriden, Connecticut
Posts: 1,797
Time spent in forums: 3 Weeks 6 Days 21 h 54 m 27 sec
Reputation Power: 154
Lol. Ok.
PS. I wonder if anyone will do my homework, 8>

#8
March 24th, 2005, 11:37 AM
 pord_80
Contributing User

Join Date: Mar 2005
Posts: 51
Time spent in forums: 1 Day 4 h 30 m 3 sec
Reputation Power: 9
It is not.........

Quote:
 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
March 24th, 2005, 11:46 AM
 pord_80
Contributing User

Join Date: Mar 2005
Posts: 51
Time spent in forums: 1 Day 4 h 30 m 3 sec
Reputation Power: 9
Thanks for the help..

Quote:
 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
March 24th, 2005, 12:12 PM
 Schol-R-LEA
Commie Mutant Traitor

Join Date: Jun 2004
Location: Norcross, GA (again)
Posts: 1,798
Time spent in forums: 1 Month 2 Weeks 3 Days 1 h 39 m 19 sec
Reputation Power: 1569
Quote:
 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 .
__________________
Rev First Speaker Schol-R-LEA;2 JAM LCF ELF KoR KCO BiWM TGIF
#define KINSEY (rand() % 7) λ Scheme is the Red Pill
Scheme in ShortUnderstanding the C/C++ Preprocessor
Taming PythonA Highly Opinionated Review of Programming Languages for the Novice, v1.1

FOR SALE: One ShapeSystem 2300 CMD, extensively modified for human use. Includes s/w for anthro, transgender, sex-appeal enhance, & Gillian Anderson and Jason D. Poit clone forms. Some wear. \$4500 obo. tverres@et.ins.gov

Last edited by Schol-R-LEA : March 25th, 2005 at 03:44 AM.

#11
March 24th, 2005, 08:55 PM
 Schol-R-LEA
Commie Mutant Traitor

Join Date: Jun 2004
Location: Norcross, GA (again)
Posts: 1,798
Time spent in forums: 1 Month 2 Weeks 3 Days 1 h 39 m 19 sec
Reputation Power: 1569
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 08:18 PM.

#12
March 25th, 2005, 02:08 AM
 netytan
Hello World :)

Join Date: Mar 2003
Location: Hull, UK
Posts: 2,537
Time spent in forums: 1 Week 2 Days 18 h 17 m 47 sec
Reputation Power: 68
[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
March 25th, 2005, 03:42 AM
 Schol-R-LEA
Commie Mutant Traitor

Join Date: Jun 2004
Location: Norcross, GA (again)
Posts: 1,798
Time spent in forums: 1 Month 2 Weeks 3 Days 1 h 39 m 19 sec
Reputation Power: 1569
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 03:46 AM.

#14
March 25th, 2005, 12:47 PM
 Dietrich
Contributing User

Join Date: Feb 2005
Posts: 574
Time spent in forums: 5 Days 4 h 6 m 36 sec
Reputation Power: 63

This works a little better in the cute box example:
Code:
```def star():
print '*',```

Uses a comma to stay on the line.

#15
March 25th, 2005, 01:55 PM
 pord_80
Contributing User

Join Date: Mar 2005
Posts: 51
Time spent in forums: 1 Day 4 h 30 m 3 sec
Reputation Power: 9
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

 Viewing: Dev Shed Forums > Programming Languages > Python Programming > Help, For and while Loop

Developer Shed Advertisers and Affiliates

 Thread Tools Search this Thread Search this Thread: Advanced Search Display Modes Rate This Thread Linear Mode Rate This Thread: 5 : Excellent 4 : Good 3 : Average 2 : Bad 1 : Terrible

 Posting Rules You may not post new threads You may not post replies You may not post attachments You may not edit your posts vB code is On Smilies are On [IMG] code is On HTML code is Off
 View Your Warnings | New Posts | Latest News | Latest Threads | Shoutbox Forum Jump Please select one User Control Panel Private Messages Subscriptions Who's Online Search Forums Forums Home -------------------- Programming Languages    PHP Development        PHP FAQs and Stickies    Perl Programming        Perl FAQs and Stickies    C Programming        C Programming FAQs and Stickies    Java Help        Java FAQs    Python Programming        Python Programming FAQs    Ruby Programming        Ruby Programming FAQs    Game Development        Game Development FAQs Programming Languages - More    ASP Programming        ASP Programming FAQs    .Net Development        .Net Development FAQs    Visual Basic Programming        Visual Basic Programming FAQs    Software Design        Software Design FAQs    ColdFusion Development        ColdFusion Development FAQs    Delphi Programming        Delphi Programming FAQs    Regex Programming        Regex Programming FAQs    XML Programming        XML Programming FAQs    Other Programming Languages        Other Programming Languages FAQs Web Design    HTML Programming        HTML Programming FAQs    JavaScript Development        JavaScript Development FAQs    CSS Help        CSS Help FAQs    Flash Help        Flash Help FAQs    Photoshop Help        Photoshop Help FAQs    Web Design Help        Web Design Help FAQs    Website Critiques        Website Critiques FAQs    Search Engine Optimization        Search Engine Optimization FAQs Mobile Programming    Mobile Programming        Mobile Programming FAQs    iPhone SDK Development        iPhone SDK Development FAQs    Android Development        Android Development FAQs    BlackBerry Development        BlackBerry Development FAQs Web Site Management    Business Help        Business Help FAQs    Development Software        Development Software FAQs    Scripts        Scripts FAQs Databases    Database Management        Database Management FAQs    DB2 Development        DB2 Development FAQs    MySQL Help        MySQL Help FAQs    PostgreSQL Help        PostgreSQL Help FAQs    Firebird SQL Development        Firebird SQL Development FAQs    MS SQL Development        MS SQL Development FAQs    Oracle Development        Oracle Development FAQs    LDAP Programming        LDAP Programming FAQs System Administration    Mail Server Help        Mail Server Help FAQs    Apache Development        Apache Development FAQs    Security and Cryptography        Security and Cryptography FAQs    Antivirus Protection        Antivirus Protection FAQs    DNS        DNS FAQs    IIS        IIS FAQs    Networking Help        Networking Help FAQs    FTP Help        FTP Help FAQs Operating Systems    BSD Help        BSD Help FAQs    Linux Help        Linux Help FAQs    UNIX Help        UNIX Help FAQs    Windows Help        Windows Help FAQs    Mac Help        Mac Help FAQs Web Hosting    Web Hosting        Web Hosting FAQs    Free Web Hosting        Free Web Hosting FAQs    Web Hosting Requests        Web Hosting Requests FAQs    Web Hosting Offers        Web Hosting Offers FAQs Computer Hardware    Computer Hardware    CPUs        CPUs FAQs    Cooling        Cooling FAQs    Embedded Programming        Embedded Programming FAQs    Motherboards        Motherboards FAQs    Multimedia Hardware        Multimedia Hardware FAQs Other    Dev Shed Lounge        Dev Shed Lounge FAQs    Development Articles        Development Articles FAQs    Beginner Programming        Beginner Programming FAQs    Hire A Programmer        Hire A Programmer FAQs    Project Help Wanted        Project Help Wanted FAQs Latest News Updated Hourly    Technology News    Business News    Science News Forum Information    Forum Rules/Guidelines        Forum Rules/Guidelines FAQs    Forum Announcements        Forum Announcements FAQs    Dev Shed Gaming Center        Go to the Dev Shed Battle Arena        Go to the Dev Shed Arcade Games        Go to the Legend of the Green Dragon    Suggestions & Feedback        Suggestions & Feedback FAQs

 Forums: » Register « |  Free Tools |  User CP |  Games |  Calendar |  Members |  FAQs |  Sitemap |  Support |

Powered by: vBulletin Version 3.0.5
Copyright ©2000 - 2013, Jelsoft Enterprises Ltd.

© 2003-2013 by Developer Shed. All rights reserved. DS Cluster - Follow our Sitemap