1

In Java, it is possible to write code like this:

int number = 1;
while((number++)<10){
     System.out.println(number);
}

I tried doing the same in Python, but got a syntax error. Is there any similar feature in Python where the value of a variable can be modified within a conditional expression?

3
  • Python does not have an increment operator. Commented Aug 7, 2018 at 23:40
  • It is probably more helpful if you tell us what you are trying to accomplish. Python has various built-in and extensible methods for using iterators, which is generally the way to go. Actually, in Python 3.8, an assignment expression will be added to the language, which could be used in this situation to get something similar to the Java code you have. The thing is, you likely don't want to be writing python like you would Java. Commented Aug 7, 2018 at 23:43
  • 1
    Up coming in 3.8 Commented Aug 8, 2018 at 2:55

1 Answer 1

2

Python doesn't allow you to modify variables in control structures like in Java and C as it doesn't have increment or decrement operators.

You could try

for number in range(1, 10):
    print(number)

Or using a while loop (as Julien suggested)

number = 1
while number < 10:
    print(number)
    number += 1

Also, check out this answer which explains the exclusion of ++ and --

Sign up to request clarification or add additional context in comments.

4 Comments

to stick closer to OP's code: while number < 10: number +=1
@Julien, true, but the while loop doesn't take advantage of any auto-increment functionality which is also what was asked
but the behavior could be completely different with a for loop depending on what is happening in the loop...
You can modify variables in control structures (depending on what you mean). Anything that is a valid expression can be used. Python simply lacks an increment operator

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.