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?

aydow
  • 3,673
  • 2
  • 23
  • 40
Daniel
  • 1,599
  • 1
  • 16
  • 19
  • Python does not have an increment operator. – juanpa.arrivillaga Aug 07 '18 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. – juanpa.arrivillaga Aug 07 '18 at 23:43
  • 1
    Up coming in 3.8 – geckos Aug 08 '18 at 02:55

1 Answers1

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 --

aydow
  • 3,673
  • 2
  • 23
  • 40
  • to stick closer to OP's code: `while number < 10: number +=1` – Julien Aug 07 '18 at 23:24
  • @Julien, true, but the `while` loop doesn't take advantage of any auto-increment functionality which is also what was asked – aydow Aug 07 '18 at 23:32
  • 1
    but the behavior could be completely different with a for loop depending on what is happening in the loop... – Julien Aug 07 '18 at 23:35
  • 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* – juanpa.arrivillaga Aug 07 '18 at 23:41