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
  Virtual Env changing mysql connection string in python Fredesetes 0 381 Dec-20-2023, 04:06 PM
Last Post: Fredesetes
  [SOLVED] [BeautifulSoup] Why does it turn inserted string's brackets into </>? Winfried 0 1,530 Sep-03-2022, 11:21 PM
Last Post: Winfried
  [SOLVED] [BeautifulSoup] Turn select() into comma-separated string? Winfried 0 1,124 Aug-19-2022, 08:07 PM
Last Post: Winfried
  Adding string after every 3rd charater [SOLVED] AlphaInc 2 1,260 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 1,626 Jul-05-2022, 11:29 PM
Last Post: deanhystad
Question [SOLVED] Delete specific characters from string lines EnfantNicolas 4 2,228 Oct-21-2021, 11:28 AM
Last Post: EnfantNicolas
  Replace String in multiple text-files [SOLVED] AlphaInc 5 8,161 Aug-08-2021, 04:59 PM
Last Post: Axel_Erfurt
  Replace String with increasing numer [SOLVED] AlphaInc 13 5,053 Aug-07-2021, 08:16 AM
Last Post: perfringo
Thumbs Up Parsing a YAML file without changing the string content..?, Flask - solved. SpongeB0B 2 2,281 Aug-05-2021, 08:02 AM
Last Post: SpongeB0B
  reading lines from a string [Solved] ebolisa 14 6,409 Mar-28-2021, 08:16 PM
Last Post: perfringo

Forum Jump:

User Panel Messages

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