0

I'll admit it, I am very new to python and need some help. I am trying to convert a very simple calculator from c++ to python. Here is the code so far:

x = 0
y = 0
sign = '+'

 def getnum(prompt, number):
    number = input(prompt)
def getsign(prompt, sign):
    sign = raw_input(prompt)
    print sign
def calc(string, number1, number2, sign):
    print string
    print " "
    if sign == '+' or 'plus':
        a = x + y
    elif sign == 'x' or '*' or 'times':
        a = x * y
    elif sign == '/' or 'divided by':
        a = x / y
    elif sign == '-' or 'minus':
        a = x - y
    print string, a
getnum("Enter first number: ", x)
getnum("Enter second number: ", y)
getsign("Enter sign: ", sign)
calc("The answer is: ", x, y, sign)
print x
print y
print sign

The problem with the functions. At the end, I get this:
The answer is: 0
0
0
+

I can't seem to get the two numbers at the end to change.

5
  • "I am very new to python"... Have you done any of the Python tutorials? Commented Sep 20, 2011 at 0:22
  • Your calc function has no return. x and y don't appear on the left side of = statements (except for their initial values). Unless x or y appear on the left side of =, their value cannot possibly change. Can you list some of the tutorials you've done? Perhaps we can suggest better tutorials that cover the = statement better than the ones you've tried. Commented Sep 20, 2011 at 0:26
  • I must be really confusing how a function works. What my plan is is to use the function getnum() to change the values of x and y. My understanding of a function is when I run getnum("Enter a number", x) that the variable prompt will be replaced with "Enter a number" and that the variable number will be replaced with the variable x. Is my thinking wrong or did I mess up my code or something. When it comes to tutorials, I pretty much google my question, and this is the first one I cannot find an answer to anywhere. Commented Sep 20, 2011 at 0:41
  • This does not cause a problem in your program, but in general it is a bad idea to name a variable string because it is a standard python module you can import. Commented Sep 20, 2011 at 1:06
  • 1
    @Ward: getnum("Enter first number: ", x) can not change the value of x. Period. Please identify what tutorials you've been using. They are misleading you about how function arguments work. For some reason. You need to be given better tutorials to learn from. Commented Sep 20, 2011 at 2:18

5 Answers 5

1

I give you few suggestions at the places where you have to change your code, these will certainly make your program work given you know how functions work in python (in genral any language)

def getnum(prompt, number):
    number = input(prompt)

The variable 'number' is local to that function. So every time you call the function "getnum" you assign a value to the number but what else do you do with that.

**Hint 1: A mechanism where as soon as you get the number, try throwin this number to a variable which can use it. Try using return.

**Hint 2: When you use input, by default the value entered will be converted into a string. So think of a method where the value will be changed from string to int. "casting"?

def getsign(prompt, sign):
    sign = raw_input(prompt)
    print sign

print sign

Directly prints the sign to the console, just think of a situation where your program can use the sign. I will give the same hint.

**Hint: Try using return.

Sign up to request clarification or add additional context in comments.

Comments

1

Python does not have "call by name". C does. Python does not.

A function evaluation like this:

getnum("Enter first number: ", x)

Will never assign a new value to x in Python. In C, a new value can be assigned. In Python a new value cannot be assigned this way.

[A value can be mutated, but that's not relevant to this question.]

Comments

1

There are a number of issues.

Let's look at them in the interactive Python interpreter, which is an invaluable tool when you're experimenting with Python.

Firstly, getnum() doesn't do what you think it does...

>>> def getnum(prompt, number):
...     number = input(prompt)
...
>>> x = 0
>>> getnum("Enter first number: ", x)
Enter first number: 6
>>> print x
0

Here you should return the value and capture it in a variable.

>>> def getnum(prompt):
...     return input(prompt)
...
>>> x = 0
>>> x = getnum("Enter first number: ")
Enter first number: 6
>>> print x
6

getsign() has a similar issue.

Moving onto calc(). Here or isn't doing what you expect:

>>> sign = '*'
>>> if sign == '+' or 'plus':
...     print 'plus'
...
plus

This needs to look more like:

>>> sign = '*'
>>> if sign == '+' or sign == 'plus':
...     print 'plus'
... else:
...     print 'not plus'
...
not plus

Or better still:

>>> if sign in ('+', 'plus'):
...     print 'plus'
... else:
...     print 'not plus'
...
not plus
>>> sign = '+'
>>> if sign in ('+', 'plus'):
...     print 'plus'
... else:
...     print 'not plus'
...
plus

The other conditions in this function have the same issue.

1 Comment

Okay. Maybe he was farther than my initial judgement.
0

I'm inclined to treat this like a "homework" problem and tell you what you're doing wrong rather than show you the exact solution. When you take your inputs using input(prompt), you are getting a string. If you want to treat it as a number, you need to tell Python that explicitly.

2 Comments

That's a good start, but it's not enough to solve the problem.
That's the idea. He's almost there.
0

I asume this is for the school, so this maybe can help you.

   #!/usr/bin/env python

   import re

   #put the logic in an object like enviroment
   class CalculatorProto(object):
        def __init__(self, numberone, numbertwo):
        """
        initialize the data
        """
            self.firsn = numberone
            self.twon = numbertwo

       def Verifynumber(self):
       """
       verify is you pass abs numbers
       """
           numbers = re.compile("^[0-9]+$")
           if numbers.search(self.firsn) and numbers.search(self.twon):
              self.firsn = int(self.firsn)
              self.twon = int(self.twon)
              return True
           else:
              return False

       def sum(self):
       """
       manage sum
       """
           rsum = self.firsn + self.twon

           return rsum


       def rest(self):
       """
       manage rest
       """
           if self.firsn > self.twon:
              rrest = self.firsn - self.twon
              return rrest
           else:
              rrest = self.twon - self.firsn
              return rrest

       def div(self):
       """
       manage div
       """
           if int(self.firsn) > int(self.twon):
              if self.twon != 0:
                 rdiv = self.firsn / self.twon
                 return rdiv
              return "Is not good idea div a number by 0"
          else:
              if self.firsn != 0:
                 rdiv = self.twon / self.firsn
                 return rdiv
              return "Is not good idea div a number by 0"

      def mul(self):
          rmul = self.firsn * self.twon
          return rmul

   if __name__ == "__main__":
      #here you cant write you small interface
      print "Enter two numbers, and a operation please"
      o = raw_input("One: ")
      t = raw_input("Two: ")
      operation = raw_input("Operation: ")
      while operation not in ("sum", "div", "rest", "mul"):
           print "WTF?? Enter a valid operation"
           print "sum\ndiv\nrest\nor mul"
           operation = raw_input("Operation: ")

      cal = CalculatorProto(o, t)

      if cal.Verifynumber():
         exec("print cal.%s()" % operation)
      else:
         print "Please insert absolute numbers"

You cant modify this, for a more complex manage.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.