Python 判断闰年、Python 平方根

Python 判断闰年

以下实例用于判断用户输入的年份是否为闰年:

# -*- coding: UTF-8 -*-

# Filename : test.py
# author by : www.w3cschool.cn

year = int(input("输入一个年份: "))
if (year % 4) == 0:
   if (year % 100) == 0:
       if (year % 400) == 0:
           print("{0} 是闰年".format(year))   # 整百年能被400整除的是闰年
       else:
           print("{0} 不是闰年".format(year))
   else:
       print("{0} 是闰年".format(year))       # 非整百年能被4整除的为闰年
else:
   print("{0} 不是闰年".format(year))

我们也可以使用内嵌 if 语句来实现:

执行以上代码输出结果为:

输入一个年份: 2000
2000 是闰年
输入一个年份: 2011
2011 不是闰年

Python 平方根

平方根,又叫二次方根,表示为〔√ ̄〕,如:数学语言为:√ ̄16=4。语言描述为:根号下16=4。

以下实例为通过用户输入一个数字,并计算这个数字的平方根:

# -*- coding: UTF-8 -*-

# Filename : test.py
# author by : www.w3cschool.cn

num = float(input('请输入一个数字: '))
num_sqrt = num ** 0.5
print(' %0.3f 的平方根为 %0.3f'%(num ,num_sqrt))

执行以上代码输出结果为:

$ python test.py 
请输入一个数字: 4
 4.000 的平方根为 2.000

在该实例中,我们通过用户输入一个数字,并使用指数运算符 ** 来计算改数的平方根。

该程序只适用于正数。负数和复数可以使用以下的方式:

# -*- coding: UTF-8 -*-

# Filename : test.py
# author by : www.w3cschool.cn

# 计算实数和复数平方根
# 导入复数数学模块

import cmath

num = int(raw_input("请输入一个数字: "))
num_sqrt = cmath.sqrt(num)
print('{0} 的平方根为 {1:0.3f}+{2:0.3f}j'.format(num ,num_sqrt.real,num_sqrt.imag))

执行以上代码输出结果为:

$ python test.py 
请输入一个数字: -8
-8 的平方根为 0.000+2.828j

该实例中,我们使用了 cmath (complex math) 模块的 sqrt() 方法。

你可能感兴趣的:(Python,java,前端,开发语言)