Justin
Justin

Reputation: 365

Simple "if" statements in Python

I'm having difficulty making this simple if statement work. I'm trying to get a string to print for a set amount of times using an 'if' statement

x = 0
if x < 9:
    print "this works"
    x = x + 1
else:
    print "this doesn't work"

The result of the code above is that it prints "this works" only once. I want 1 to be added to x until x reaches 9 and the statement is not longer true.

Can anyone help me here?

Upvotes: 0

Views: 4692

Answers (3)

CrazyCasta
CrazyCasta

Reputation: 28302

I think what you're asking for is a while statement. Try this:

x = 0
while x < 9:
    print "this works"
    x = x + 1

print "this doesn't work"

An if statement does not loop. You can think of it in the sense of English:

  • "If something is true then do something else do something different" - no implied do something multiple times in this statement.
  • "While something is true do stuff." - here "while" suggests that something may happen multiple times.

Other ways of doing this:

If all you're looking to do is loop through something with the values x 0-9 then a for loop would work well:

for x in range(9):
    print "this works"
print "this doesn't work"

In this case range(9) can be replaces by range(start_value, stop_value+1) for more genericism. This is more typical way of doing this, I suggested while merely because it sounded most like what you were thinking if would do.

Another way:

x = 0
while True:
    if x < 9:
        print "this works"
        x = x + 1
    else:
        print "this doesn't work"
        break

Based on Adam's solution. Not generally used for something where you can easily work out the end condition, but can be useful where the end condition isn't terribly obvious in advance. Can't think of any specific examples of where this use case is appropriate at the moment. It's a replacement to doing dummy_var = True, while dummy_var: and then set dummy_var = False when you want to dump out.

Upvotes: 5

Vincent Rodomista
Vincent Rodomista

Reputation: 780

You need to also include a loop if you want something to repeat. The two simplest ways to do this are with a for or while loop.

for i in range(0,9):
 print "this works"

Or

x = 0
while(x < 9):
 print "this works"
 x = x + 1

Upvotes: 1

Sharath Manchala
Sharath Manchala

Reputation: 101

Control Statement like 'if' can be used for decision making and the statements under the condition runs only once. Instead you could make use of while loop for this purpose.

Upvotes: 1

Related Questions