如何将输入读作数字?

如何将输入读作数字?

在下面的代码中为什么xy字符串而不是整数?

(注意:在Python 2.x中使用raw_input()。在Python 3.x中使用input()。在Python 3.x raw_input()中重命名为input()。)

play = Truewhile play:

    x = input("Enter a number: ")
    y = input("Enter a number: ")

    print(x + y)
    print(x - y)
    print(x * y)
    print(x / y)
    print(x % y)

    if input("Play again? ") == "no":
        play = False


12345678_0001
浏览 732回答 7
7回答

繁星点点滴滴

input()(Python 3)和raw_input()(Python 2)总是返回字符串。使用显式将结果转换为整数int()。x = int(input("Enter a number: "))y = int(input("Enter a number: "))

慕工程0101907

多个问题需要在单行上输入几个整数。最好的方法是将整个数字串输入一行,然后将它们拆分为整数。这是一个Python 3版本:a = []p = input()p = p.split()      for i in p:    a.append(int(i))

Cats萌萌

转换为整数:my_number = int(input("enter the number"))对于浮点数类似:my_decimalnumber = float(input("enter the number"))

心有法竹

def dbz():     try:         r = raw_input("Enter number:")         if r.isdigit():             i = int(raw_input("Enter divident:"))             d = int(r)/i            print "O/p is -:",d        else:             print "Not a number"     except Exception ,e:         print "Program halted incorrect data entered",type(e)dbz()Or num = input("Enter Number:")#"input" will accept only numbers
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

Python