Thursday, January 7, 2021

Python - Control Flow and Logical Operators (Day 3)

This is a 100 Days challenge to learn a new language (Python). 100 Days of Code - The Complete Python Pro Bootcamp 

I will post some notes to motivate myself to finish this challenge.


Conditional Operators



Ex:
if condition:
    if condition:
        # Do something
    else:
        # Do something
elif condition:
    # Do something
else:
    # Do something


NOTE: Unlike other language, Python uses 'elif' instead of 'else if'


Logical Operators



* and
* or
* not

Ex:
input_num = 1
if input_num > 0 and input_num < 5:
    print("Using 'and' not '&&'")


NOTE: Unlike other language, Python uses 'and' instead of '&&'


Note



How to print a long message?   


Ex:
print('''
    abcdefg
    test
    hello
''')

Result:
abcdefg test hello



How to make a string to be lower case?   


Ex:
print("HELLO".lower())

Result:
hello



How to count the character from a string?   


Ex:
print("HELLO".count("H"))

Result:
1



Challenge



Determinate whether the input year is a Leap Year or not



Ex:
# on every year that is evenly divisible by 4
# **except** every year that is evenly divisible by 100
# **unless** the year is also evenly divisible by 400

year = int(input("Please Input a Year? "))

is_leap_year = False

if year % 4 == 0:
    if year % 100 == 0:
        if year % 400 != 0:
            is_leap_year = False
        else:
            is_leap_year = True
    else:
        is_leap_year = True


if is_leap_year == True:
    print("A leap year")
else:
    print("A common year")

Result:
Please Input a Year? 2020 A leap year


No comments:

Post a Comment