[python] How can I convert a string to an int in Python?

The output I'm getting for my little example app is the following:

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

This is because the addition() method is taking the input() as strings and not numbers. How can I use them as numbers?

Here is my entire script:

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"

This question is related to python string int

The answer is


While calling your sub functions from your main functions you can convert the variables into int and then call. Please refer the below code:

import sys

print("Welcome to Calculator\n")
print("Please find the options:\n" + "1. Addition\n" + "2. Subtraction\n" + 
"3. Multiplication\n" + "4. Division\n" + "5. Exponential\n" + "6. Quit\n")

def calculator():
    choice = input("Enter choice\n")

    if int(choice) == 1:
        a = input("Enter first number\n")
        b = input("Enter second number\n")
        add(int(a), int(b))

    if int(choice) == 2:
        a = input("Enter first number\n")
        b = input("Enter second number\n")
        diff(int(a), int(b))

    if int(choice) == 3:
        a = input("Enter first number\n")
        b = input("Enter second number\n")
        mult(int(a), int(b))

    if int(choice) == 4:
        a = input("Enter first number\n")
        b = input("Enter second number\n")
        div(float(a), float(b))

    if int(choice) == 5:
        a = input("Enter the base number\n")
        b = input("Enter the exponential\n")
        exp(int(a), int(b))

    if int(choice) == 6:
        print("Bye")
        sys.exit(0)



def add(a, b):
    c = a+b
    print("Sum of {} and {} is {}".format(a, b, c))

def diff(a,b):
    c = a-b
    print("Difference between {} and {} is {}".format(a, b, c))

def mult(a, b):
    c = a*b
    print("The Product of {} and {} is {}".format(a, b, c))

def div(a, b):
    c = a/b
    print("The Quotient of {} and {} is {}".format(a, b, c))

def exp(a, b):
    c = a**b
    print("The result of {} to the power of {} is {}".format(a, b, c))

calculator()

Here what I did is I called each of the function while converting the parameters inputted to int. I hope this has been helpful.

In your case it could be changed like this:

 if choice == "0":
        numberA = raw_input("Enter your first number: ")
        numberB = raw_input("Enter your second number: ")
        print "Your result is:"
        print addition(int(numberA), int(numberB))

Perhaps the following, then your calculator can use arbitrary number base (e.g. hex, binary, base 7! etc): (untested)

def convert(str):
    try:
        base = 10  # default
        if ':' in str:
            sstr = str.split(':')
            base, str = int(sstr[0]), sstr[1]
        val = int(str, base)
    except ValueError:
        val = None

    return val

val = convert(raw_input("Enter value:"))
# 10     : Decimal
# 16:a   : Hex, 10
# 2:1010 : Binary, 10

Don't use str() method directly in html instead use with y=x|string()

<div class="row">
    {% for x in range(photo_upload_count) %}
        {% with y=x|string() %}

    <div col-md-4 >
        <div class="col-md-12">
            <div class="card card-primary "  style="border:1px solid #000">
                <div class="card-body">
                    {% if data['profile_photo']!= None: %}
                        <img class="profile-user-img img-responsive" src="{{ data['photo_'+y] }}" width="200px" alt="User profile picture">
                    {% else: %}
                        <img class="profile-user-img img-responsive" src="static/img/user.png" width="200px" alt="User profile picture">
                    {% endif %}
                </div>
                <div class="card-footer text-center">
                    <a href="{{value}}edit_photo/{{ 'photo_'+y }}" class="btn btn-primary">Edit</a>
                </div>
            </div>
        </div>
    </div>
    {% endwith %}
    {% endfor %}
</div>

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:"

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 = input("Enter your first number: ")
    numberB = input("Enter your second number: ")
    print "Your result is: " + str(addition(numberA, numberB)) + "\n"
elif choice == "1":
    numberA = input("Enter your first number: ")
    numberB = input("Enter your second number: ")
    print "Your result is: " + str(subtraction(numberA, numberB)) + "\n"
elif choice == "2":
    numberA = input("Enter your first number: ")
    numberB = input("Enter your second number: ")
    print "Your result is: " + str(multiplication(numberA, numberB)) + "\n"
elif choice == "3":
    numberA = input("Enter your first number: ")
    numberB = input("Enter your second number: ")
    print "Your result is: " + str(division(numberA, numberB)) + "\n"
elif choice == "4":
    print "Bye!"
    keepProgramRunning = False
else:
    print "Please choose a valid option."
    print "\n"

>>> a = "123"
>>> int(a)
123

Here's some freebie code:

def getTwoNumbers():
    numberA = raw_input("Enter your first number: ")
    numberB = raw_input("Enter your second number: ")
    return int(numberA), int(numberB)

easy!

    if option == str(1):
        numberA = int(raw_input("enter first number. "))
        numberB= int(raw_input("enter second number. "))
        print " "
        print addition(numberA, numberB)
     etc etc etc

Examples related to python

programming a servo thru a barometer Is there a way to view two blocks of code from the same file simultaneously in Sublime Text? python variable NameError Why my regexp for hyphenated words doesn't work? Comparing a variable with a string python not working when redirecting from bash script is it possible to add colors to python output? Get Public URL for File - Google Cloud Storage - App Engine (Python) Real time face detection OpenCV, Python xlrd.biffh.XLRDError: Excel xlsx file; not supported Could not load dynamic library 'cudart64_101.dll' on tensorflow CPU-only installation

Examples related to string

How to split a string in two and store it in a field String method cannot be found in a main class method Kotlin - How to correctly concatenate a String Replacing a character from a certain index Remove quotes from String in Python Detect whether a Python string is a number or a letter How does String substring work in Swift How does String.Index work in Swift swift 3.0 Data to String? How to parse JSON string in Typescript

Examples related to int

How can I convert a char to int in Java? How to take the nth digit of a number in python "OverflowError: Python int too large to convert to C long" on windows but not mac Pandas: Subtracting two date columns and the result being an integer Convert bytes to int? How to round a Double to the nearest Int in swift? Leading zeros for Int in Swift C convert floating point to int Convert Int to String in Swift Converting String to Int with Swift