开发者

Python and Functions

开发者 https://www.devze.com 2023-04-05 20:07 出处:网络
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:

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.


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.


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.]


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.


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.


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.

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号