Python 中的条件逻辑:增强技能的示例
条件逻辑允许程序根据某些条件做出决策。它允许您的代码根据条件是 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")
- 检查一个人是否有资格投票(年龄 >= 18)
age = 20 if age >= 18: print("eligible to vote") else: print("not eligible to vote")
- 判断一个数是否能被5整除
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")
- 检查一个数字是否是 3 和 7 的倍数
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")
- 检查数字是否大于或等于 100
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 中的条件逻辑:增强技能的示例的详细内容,更多请关注硕下网其它相关文章!