Home > Mobile >  Convert comprehensive list to an if, else statement
Convert comprehensive list to an if, else statement

Time:08-30

I'm relatively new to Python. What I try to do is convert this comprehensive list to a normal if, else statement.

def draw(self):
    self.value = choice(green_chars)
    self.y = self.y   self.speed if self.y < 1080 else -40 * randrange(1, 5)
    screen.blit(self.value, (self.x, self.y))

So far I've tried this:

    self.value = choice(green_chars)
    if self.y < 1080:
        self.y = self.y   self.speed 
    else:
        -40 * randrange(1, 5)

    screen.blit(self.value, (self.x, self.y))

But it doesn't work.

CodePudding user response:

You probably forgot to assign the value:

self.value = choice(green_chars)
if self.y < 1080:
    self.y = self.y   self.speed 
else:
    self.y = -40 * randrange(1, 5) # Here

screen.blit(self.value, (self.x, self.y))

CodePudding user response:

The conditional expression in Python is similar as other languages

variable = expr1 if truth-expr else expr2

Here variable will be assigned to expr1 expression if truth-expr expression is true, otherwise expr2.

In normal form,

if truth-expr:
    variable = expr1
else:
    variable = expr2
  • Related