条件逻辑允许程序根据某些条件做出决策。它允许您的代码根据条件是 true 还是 false 采取不同的操作。这些决定使用条件语句,例如 if、elif 和 else。
number = 5 if 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 = 20 if 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 check if int(number ** 0.5) ** 2 == number: print("perfect square") else: print("not a perfect square")
my_dict = {'name': 'John', 'age': 25} # Example dictionary if "name" in my_dict: print("Key 'name' exists") else: print("Key 'name' does not exist")
以上就是Python 中的条件逻辑:增强技能的示例的详细内容,更多请关注php中文网其它相关文章!
每个人都需要一台速度更快、更稳定的 PC。随着时间的推移,垃圾文件、旧注册表数据和不必要的后台进程会占用资源并降低性能。幸运的是,许多工具可以让 Windows 保持平稳运行。
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号