一尘不染

如何在Python中将字符串转换为int?

python

我为小示例应用程序获得的输出如下:

Welcome to the Calculator!
Please choose what you'd like to do:
0: Addition
1: Subtraction
2: Multiplication
3: Division
4: Quit Application
0
Enter your first number: 1
Enter your second number: 1
Your result is:
11

这是因为additional()方法将input()作为字符串而不是数字。如何将它们用作数字?

这是我的整个脚本:

def addition(a, b):
    return a + b

def subtraction(a, b):
    return a - b

def multiplication(a, b):
    return a * b

def division(a, b):
    return a / b

keepProgramRunning = True

print "Welcome to the Calculator!"

while keepProgramRunning:    
    print "Please choose what you'd like to do:"

    print "0: Addition"
    print "1: Subtraction"
    print "2: Multiplication"
    print "3: Division"
    print "4: Quit Application"



    #Capture the menu choice.
    choice = raw_input()

    if choice == "0":
        numberA = raw_input("Enter your first number: ")
        numberB = raw_input("Enter your second number: ")
        print "Your result is:"
        print addition(numberA, numberB)
    elif choice == "1":
        numberA = raw_input("Enter your first number: ")
        numberB = raw_input("Enter your second number: ")
        print "Your result is:"
        print subtraction(numberA, numberB)
    elif choice == "2":
        numberA = raw_input("Enter your first number: ")
        numberB = raw_input("Enter your second number: ")
        print "Your result is:"
        print multiplication(numberA, numberB)
    elif choice == "3":
        numberA = raw_input("Enter your first number: ")
        numberB = raw_input("Enter your second number: ")
        print "Your result is:"
        print division(numberA, numberB)
    elif choice == "4":
        print "Bye!"
        keepProgramRunning = False
    else:
        print "Please choose a valid option."
        print "\n"

阅读 212

收藏
2020-12-20

共1个答案

一尘不染

由于您正在编写一个可能也接受浮点数(1.5, 0.03)的计算器,因此,更可靠的方法是使用以下简单的辅助函数:

def convertStr(s):
    """Convert string to either int or float."""
    try:
        ret = int(s)
    except ValueError:
        #Try float.
        ret = float(s)
    return ret

这样,如果int转换不起作用,则将返回浮点数。

编辑:division如果您不完全了解python
2.x如何处理整数除法,
则您的函数也可能会导致一些悲伤的表情。

简而言之,如果要10/2等于2.5不是 2,则需要执行from __future__ import division或强制将其中一个或两个参数转换为float,如下所示:

def division(a, b):
    return float(a) / float(b)
2020-12-20