HomePortalFAQSearchMemberlistUsergroupsRegisterLog in

Share | 
 

 While Command

Go down 
AuthorMessage
Compu-Teck Inc.



Posts : 80
Join date : 2010-04-29
Age : 25

PostSubject: While Command   Thu Dec 16, 2010 1:56 am

Hello, everybody! It's CTI, back with another tutorial in Python! Today, we will be discussing the "while" command! Here is a sample code to look at!:
Code:

number = 23
running = True
while running:
guess =input('Enter an integer : ')
if guess == number:
print ("Congratulations, you guessed it.")
running = False # this causes the while loop to stop
elif guess < number:
print ("No, it is a little higher than that.")
else:
print ("No, it is a little lower than that.")
else:
print ("The while loop is over.")
# Do anything else you want to do here
print ("Done")

Let's see what makes this particular code tick, shall we?

Code:

number = 23
running = True
Ok, we've all seen the first line before... it's a variable. The second line is a condition called running. We will see the use in the next line of code.

Code:

while running:
This little bit of code tells us that the program is only to run if the condition of "running" returns as "True", as opposed to "False"

Code:

guess =input('Enter an integer : ')
if guess == number:
print ("Congratulations, you guessed it.")
running = False # this causes the while loop to stop
This next bit of code tells the program what is to hapen if the guess equals the number. In this case, the string "Congratulations, you guessed it." is to be displayed. Next, the loop is stopped by telling the program to return a value of false to the "while" loop. This is exlained by the comment (begins with the # symbol)

Code:

elif guess < number:
print ("No, it is a little higher than that.")
else:
print ("No, it is a little lower than that.")
else:
print ("The while loop is over.")
These next lines of code are pretty self explanatory... basically, it tells the program what is to happen when the guess is either greater or less than the number. After the program is ended, the program will display the string.

Code:

# Do anything else you want to do here
print ("Done")
These last two lines are also pretty simple. First, we are leaving a comment saying that the programmer can add any additional code after the program has been executed. Then, we are telling the program to display the string "Done" to tell the user that the program is over.

There, the "while" loop isn't so hard to understand, is it? Remember, though, a good programmer is only made through practice. Now, go have fun, my Python minions!! Twisted Evil Twisted Evil
Back to top Go down
View user profile
 
While Command
Back to top 
Page 1 of 1

Permissions in this forum:You cannot reply to topics in this forum
Compile Crazy :: Programming :: Python :: For Beginners-
Jump to: