i can't input number even if i use int function

淺唱寂寞╮ 提交于 2020-01-30 11:22:06

问题


def sqrt():

    x = input('enter a number:' )
    x= int()           
    if x == int:
        a = x*x      
        print (a)
    else:
           print ('this is not a number')

this is my code, i wanted to input a number and multiply it by itself, but it didn't work out. when i run my program as;

sqrt()

enter a number:10 this is not a number

but the code that i have written should give 'True' to the 'if' statement. any helps?


回答1:


You are calling int without argument, so you get x=0; the other problem is, that a value of type int is never equal to the type int.

Use exceptions:

def sqrt():
    try:
        x = int(input('enter a number:' ))
    except ValueError:
        print('this is not a number')
    else:
        a = x*x      
        print(a)


来源:https://stackoverflow.com/questions/51572342/i-cant-input-number-even-if-i-use-int-function

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!