python if else用法例子

来自:    更新日期:早些时候
~

Python中的if-else语句是一种常见的条件语句,用于根据条件执行不同的代码块。if-else语句的基本语法如下:

if condition:

# code block to execute if condition is True

else:

# code block to execute if condition is False

其中,condition是一个布尔表达式,如果为True,则执行if语句块中的代码,否则执行else语句块中的代码。

下面是一些if-else语句的例子:

  • 判断一个数是否为偶数

num = 10

if num % 2 == 0:

print("The number is even.")

else:

print("The number is odd.")

这个例子中,我们使用了取模运算符(%)来判断一个数是否为偶数。如果num除以2的余数为0,则它是偶数,否则它是奇数。

  • 判断一个年份是否为闰年

year = 2020

if year % 4 == 0:

if year % 100 == 0:

if year % 400 == 0:

print("The year is a leap year.")

else:

print("The year is not a leap year.")

else:

print("The year is a leap year.")

else:

print("The year is not a leap year.")

这个例子中,我们使用了嵌套的if语句来判断一个年份是否为闰年。如果一个年份可以被4整除,但不能被100整除,或者可以被400整除,则它是闰年。




python if else用法例子视频

相关评论:

相关主题精彩

版权声明:本网站为非赢利性站点,内容来自于网络投稿和网络,若有相关事宜,请联系管理员

Copyright © 喜物网