python中type用法,如何在python中使用if语句放入type()?

I have TypeError: a float is required when I try putting type() with if statement

example:

from math import *

x=input("Enter a Number: ")

if type (sqrt(x)) == int:

print (sqrt(x))

else:

print("There is no integer square root")

obviously I can't use x= float(x)

解决方案

there are 2 problems here :

1st

x=input("Enter a Number: ")

will be a string, not a number, using int(x) should fix this

2nd

if type (sqrt(x)) == int:

sqrt() always return a float, you can use float.is_integer(), like this : sqrt(x)).is_integer() to check if the square root is a integer.

final code :

from math import *

x=int(input("Enter a Number: "))

if sqrt(x).is_integer():

print (sqrt(x))

else:

print("There is no integer square root")

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值