Python if statement improvement

Asked 2 years ago, Updated 2 years ago, 15 views

if a < b:
    if c < 3:
        print("hi")

It's a matter of improving the code like above in a better way, so where is there room for improvement?

musketeers = ["Athos", "Porthos", "Aramis", "D'Artagnan"] 
i = 0
while i < len(musketeers):
    print(musketeers[i])
    i += 1

I need to simplify this code, and I'd appreciate it if you could help me with this!

python

2022-09-22 19:10

1 Answers

if A:
    if B:
        C

is an and operation (perform C when A is true and B is true).

Therefore, if you shorten the code above to two lines,

if A and B:
    C

Iterative statements are largely divided into when and for. When you refer to elements in a list one by one (when you read them), you often use a for statement.

listA = [1, 2, 3]
for i in listA:
    print(i)


2022-09-22 19:10

If you have any answers or tips


© 2024 OneMinuteCode. All rights reserved.