In python how to write a simple while loop?I am a C++ expert but i am starting to learn python.

Lets say i need to write a while loop asking the user if he wants to input a number and if the user says yes, the program will input the number and display it..

Read Me: Starting Python (Multi-page thread 1 2 3 4 5)
Read Me: Projects for the Beginner (Multi-page thread 1 2 3 4 5)
Read Me: Starting wxPython (GUI code) (Multi-page thread 1 2 3)

You mean none of these explained a while loop?

Not one code example at all ever showed a while loop?

Hi,
Just was experimenting a new language.Yes i goggled got through some tutorials and finally compiled the program successfully of my own.

Anyway thank you all for your replies.

There are at least two ways to write this. The first example puts the condition to not exit the while loop into the while statement:

n = 1
while n != 0:
    try:
        # works on Python2 and Python3 versions
        n = int(input("Enter a number (zero to exit): "))
        print("You entered integer %d" % n)
    except:
        print("Enter a number only!")

print("Done")

The second way is to make an endless loop and then exit via break in an if statement within the loop. I find that syntax easier to read:

while True:
    try:
        # works on Python2 and Python3 versions
        n = int(input("Enter a number (zero to exit): "))
        print("You entered integer %d" % n)
        if n == 0:
            break
    except:
        print("Enter a number only!")

print("Done")

The try/except traps the entry of a non-numeric value and gets back into the loop.

Have fun with Python!

it can also be like:
user=raw_input("would you like to enter number")
while user!='no':
if user=='yes':
a=raw_input("Enter numbers")
print a
user=raw_input('Would you like to enter more')

& can also be like:

while 1:
user=raw_input("do u like to enter numbers?reply in yes & no.\n\tMake sure of using same case as specified")
if user=='yes':
a=raw_input("\nEnter number")
print a
continue
elif user=='no':
break

hopes this wud hav solved ur problem

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.