Python if..elif..else.. blocks

by Atakan

Now we will see a phrase that will be used very often. In any case, there is no language for the program without this keyword 🙂
A generic expression used to execute flow when a logic expression is true or false.

Usage case 1

if expression:
	logic true
else:
	logic false

Here, we need to pay attention to the space under the if and else, 1 indent from the beginning of the line. a lot of advanced ide will do this automatically for us, it is good to say that anyway.

Usage case 2

if expression:
	logic true
elif expression:
	logic true
elif expression:
	logic true
else:
	logic false

Usage case 3

if expression:
	if expression:
		logic true
	else:
		logic false
else:
	logic false

Let’s write an example scenario from the real world..
For example, let’s say you want the user to choose a password for a registration form on a certain principle.

  • have min 6 characters
  • have min 1 number
  • have min 1 string characters
  • have min 1 uppercase letter
input_password = input("Password: ")

password_length = input_password.__len__()
has_digit_number = any(map(str.isdigit, input_password))
has_upper_character = any(map(str.isupper, input_password))


if password_length >= 6:
    if has_digit_number:
        if has_upper_character:
            print("Password format acceptable")
        else:
            print("password must contains min 1 uppercharacter")
    else:
        print("password must contains min 1 number")
else:
    print("password must be min 6 character")

It could also be used multiple expressions in a single if block

if password_length >= 6 and has_digit_number and has_upper_character:
    print("Password format acceptable")
else:
    print("Password format unacceptable")

You may also like

This website uses cookies to improve your experience. We'll assume you're ok with this, but you can opt-out if you wish. OK Read More