Python 中的条件逻辑:增强技能的示例
条件逻辑允许程序根据某些条件做出决策。它允许您的代码根据条件是 true 还是 false 采取不同的操作。这些决定使用条件语句,例如 if、elif 和 else。
number = 5if number > 0: print("positive")elif number < 0: print("negative")else: print("zero")
year = 2024 if (year % 4 == 0 and year % 100 != 0) or (year % 400 == 0): print("leap year")else: print("not a leap year")
number = 10 if number % 2 == 0: print("even")else: print("odd")
age = 20if age >= 18: print("eligible to vote")else: print("not eligible to vote")
number = 25 if number % 5 == 0: print("divisible by 5")else: print("not divisible by 5")
input_string = "" if not input_string: print("empty string")else: print("non-empty string")
number = 21 if number % 3 == 0 and number % 7 == 0: print("multiple of both 3 and 7")else: print("not a multiple of both 3 and 7")
number = 15 if 10 < number < 20: print("between 10 and 20")else: print("not between 10 and 20")
letter = 'a' if letter in 'aeiouaeiou': print("vowel")else: print("consonant")
number = 150 if number >= 100: print("greater than or equal to 100")else: print("less than 100")
input_string = "hello, world!" if input_string.startswith("h"): print("starts with h")else: print("does not start with h")
number = 16 # example number to checkif int(number ** 0.5) ** 2 == number: print("perfect square")else: print("not a perfect square")
my_dict = {'name': 'John', 'age': 25} # Example dictionaryif "name" in my_dict: print("Key 'name' exists")else: print("Key 'name' does not exist")