Python Forum
[SOLVED] Changing a string to an int
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
[SOLVED] Changing a string to an int
#1
I'm making a simple calculator, but when you input 1 + 1, the program returns "11". I don't get any errors, but is there a way to change the string that you type, into an int that can be added in an equation?
Self-taught HTML, CSS, Python, and Java programmer
Reply
#2
Does the user input the whole expression or just the numbers?

For the whole expression you can try this:
py-expression-eval
Reply
#3
(Jun-23-2018, 07:04 PM)gontajones Wrote: Does the user input the whole expression or just the numbers?

For the whole expression you can try this:
py-expression-eval

Just the numbers.

I solved it myself.

During the equation, i added int() around the strings.
Self-taught HTML, CSS, Python, and Java programmer
Reply
#4
Just an idea...

def myCalc():

    n1 = input()
    op = input()
    n2 = input()
    if n1.isdigit() and n2.isdigit() and op in '+-*/':
        n1, n2 = int(n1), int(n2)
        if op == '+':
            result = n1 + n2
        elif op == '-':
            result = n1 - n2
        elif op == '*':
            result = n1 * n2
        elif op == '/':
            result = n1 / n2
    print("Result: {}".format(result))


myCalc()
Reply


Possibly Related Threads…
Thread Author Replies Views Last Post
  question about changing the string value of a list element jacksfrustration 4 2,096 Feb-08-2025, 07:43 AM
Last Post: jacksfrustration
  [SOLVED] Sub string not found in string ? jehoshua 4 1,415 Dec-03-2024, 09:17 PM
Last Post: jehoshua
Question [SOLVED] How to replace characters in a string? Winfried 2 1,043 Sep-04-2024, 01:41 PM
Last Post: Winfried
  Virtual Env changing mysql connection string in python Fredesetes 0 986 Dec-20-2023, 04:06 PM
Last Post: Fredesetes
  [SOLVED] [BeautifulSoup] Why does it turn inserted string's brackets into </>? Winfried 0 2,711 Sep-03-2022, 11:21 PM
Last Post: Winfried
  [SOLVED] [BeautifulSoup] Turn select() into comma-separated string? Winfried 0 1,912 Aug-19-2022, 08:07 PM
Last Post: Winfried
  Adding string after every 3rd charater [SOLVED] AlphaInc 2 2,068 Jul-11-2022, 09:22 AM
Last Post: ibreeden
  Changing a string value to a numerical value using python code and a lamda function Led_Zeppelin 6 2,823 Jul-05-2022, 11:29 PM
Last Post: deanhystad
Question [SOLVED] Delete specific characters from string lines EnfantNicolas 4 3,246 Oct-21-2021, 11:28 AM
Last Post: EnfantNicolas
  Replace String in multiple text-files [SOLVED] AlphaInc 5 11,210 Aug-08-2021, 04:59 PM
Last Post: Axel_Erfurt

Forum Jump:

User Panel Messages

Announcements
Announcement #1 8/1/2020
Announcement #2 8/2/2020
Announcement #3 8/6/2020