This course will become read-only in the near future. Tell us at community.p2pu.org if that is a problem.

Operators



Operators work with one or more objects and can perform tasks such as math, comparison, and inspection.

Math

There are standard operators for arithmetic:

Math Operators
Operator Description
+ Addition
- Subtraction
* Multiplication
/ Division
// Integer Division
% Modulus Division
** Exponent

Additionally, you can modify a named value and assign the output of an operator to the name in one line with inline assignment operators.

	>>> a_number = 1
>>> a_number += 1
>>> a_number
2
>>> a_number *= 8
>>> a_number
16
>>> a_number **= 2
>>> a_number
256
>>> a_number /= 2
>>> a_number
128
>>> a_number %= 3
>>> a_number
2
>>> 3.123 // a_number
1

Assignment

  1. Run Python commands to add, subtract, multiply and divide numbers from the Python interpreter command line.
  2. Create simple Python script program to perform numeric calculations and output results (e.g. calculating the area of a rectangle or circle).

Further Reading

Task Discussion


  • Fer said:

    on Oct. 21, 2013, 11:28 a.m.
  • v4lent1na said:

    Uhm I'm really bad at math - actually, I suck. Can someone please explain to me in simple and plain language how to create the program needed for the exercise? Assume that I'm a little kid and take a step-by-step instructions approach. Thanks a million!

    on Sept. 9, 2013, 8:25 a.m.

    algotruneman said:

    The key is to write the formula as math first (I do realize you need to know the formula).

    Area equals the height of rectangle times the width of rectangle.

    Math people usually say: Area = H x W which is close to the Python idea of using variables.

    Next change that to Python style code.

    areaRect = h * w

    Finally, use the inputs to get values for h and w and put the formula line after them and do a print of the answer.

    Hope that helps.

    on Sept. 9, 2013, 1:59 p.m. in reply to v4lent1na

    v4lent1na said:

    It actually helps a whole lot. I'll write it down and work around it to solve the exercise.

    Thanks! smiley

    on Sept. 9, 2013, 3:41 p.m. in reply to algotruneman

    v4lent1na said:

    Sorry if I bother you again: I'm gonna do this with raw_input, right?

    on Sept. 11, 2013, 5:27 a.m. in reply to algotruneman

    dvdgc said:

    In principle you could do so... though that's not asked directly.  The excercise could be understood as just doing the calculations.  But probably it's better if you ask the user, it would be more useful :)

    on Sept. 11, 2013, 4:36 p.m. in reply to v4lent1na

    algotruneman said:

    Yes, raw_input will work, but be sure to convert the input values to integer after the input.

    on Sept. 12, 2013, 6:25 p.m. in reply to v4lent1na
  • canuckfan34 said:

    Area of a Rectangle using a Function( yes, I know we haven't learned functions yet):

     

     

    def area_rectangle(length,width):
    area=length * width
    print "The area of this rectangle is:",area
    on June 26, 2013, 5:57 a.m.

    algotruneman said:

    Be sure you have the required indenting.

    def area_rectangle(length,width):

        area=length * width

        print "The area of this rectangle is:",area

    on June 26, 2013, 9:09 a.m. in reply to canuckfan34

    algotruneman said:

    Now, the nicest thing your  example did was make  me try to understand the function concept, especially the way variables get handled. I'd read about local vs. global variables, but was confused by the idea. However, trying to implement the function so I could get the results of the function to print both "inside" (as a variable local to the function) and "outside (as a global variable captured out from the function made me puzzle why my examples were not working...but now I get it!

    Thanks for spurring  me to figure it out, canuckfan34.

    Here's how I processed the information...with many trials and frustrating prints of the value of zero for the final print.

    The big key for me was seeing the difference of calling the function:
    area_rectangle(5,7)
    which shoves the two values into the function and gives variable area work inside as a local var.

    The second half of my slow realization came when I saw that the value inside not only needed a return from inside, but that the call of the function needed to be assigned to the global area variable.

    area = 0 # initializes the global variable
    def area_rectangle(length,width): # vars pulled into the function
        area = length * width
        print "The area of the rectangle is: ", area # local "inside" var
        return area
        # The next line sort of works, getting the values into the function.
        # area_rectangle(5,7) # but it doesn't work to capture the return  attempt

        # The big realization was that the inside return needed to be assigned
         # to the outside (global) variable, EVEN IF THEY WERE THE SAME VAR NAME
    area = area_rectangle(5,7) # this assignment captures the inside local
        # via the return to the outside, global area var
        # The inside area isn't the same as the outside one even though they
        # share the same human-readable name.

    print "The area (global) is: ", area
        # Over and over this stayed zero, until I saw the need to assign the
        # return value of the inside (local) to the outside (global)
        # during the function call.

    A more readable version is here: https://gist.github.com/algotruneman/5868694


    Thank you, canuckfan34. Your example helped me significantly advance my understanding of Python.

    on June 26, 2013, 11:42 a.m. in reply to canuckfan34
  • Iftekhar Mohammad said:

    on May 16, 2013, 4:56 a.m.
  • Dennis Daniels said:

    I did mine in Ipython3.

    The code is here.

    http://dpaste.com/1025661/

    I randomized the values to make it a little more interesting.

    on March 17, 2013, 10:03 a.m.
  • Wouter Tebbens said:

    #Use the theorem of pythagoras about rectangular triangles:
    a = raw_input ('size of side a: ')
    b = raw_input ('size of side b: ')
    print "c = ", round((float(a)**2+float(b)**2)**0.5,2)

    #calculate the surface of a circle
    d = raw_input('The diameter is: ')
    print "The circle's surface is: ", round(3.1415*float(d)**2/4,4)

    #calculate the surface of a circle
    import math
    d = raw_input('The diameter is: ')
    print "The circle's surface is: ", round(math.pi*float(d)**2/4,4)

    #calculate the surface of a rectangle
    length = raw_input('length: ')
    width = raw_input('width: ')
    print "The surface of the rectangle is: ", float(length)*float(width)

    on March 5, 2013, 3:11 p.m.
  • rinckemi said:

    FInding the circumference of a circle:

     

     

    print "Let's find the circumference of a circle!\n";
    r_prompt='First, what is the radius of your circle?\n';
    radius=raw_input(r_prompt);
    diameter=float(radius)*2;
    print 'So, if the radius of the circle is',radius,'that means the diameter of this circle is',diameter;
    circumference=3.14*float(diameter);
    print 'Which means that the circumference is',circumference
    on Feb. 5, 2013, 10:18 p.m.
  • drediamond said:

    How to calculate the area of a rectangle:

    j= 'What is the base of the rectangle?'

     k= raw_input (j)

    l='What is the side of your rectangle?'

    m=raw_input (l)

    print int(m)*int(k)

    on Nov. 18, 2012, 6:09 p.m.
  • 0quesevayantodos0 said:

    a = 'What is the radius of your circle? '
    b = raw_input(a)
    pi = 3.14159265359
    area = float(pi)*float(b)**2

    print 'The area of your circle is ', area
     
    on Sept. 11, 2012, 11 p.m.
  • Youngestprof said:

     

    #Below is my practice
    import math
     
     
            radius = raw_input('Radius: ')
            radius = float(radius)
     
     
    area = 2 * math.pi * radius
     
    print 'Area: ',area
    on Aug. 29, 2012, 2:10 a.m.
  • Youngestprof said:

    Anyone pls help. How do i compile and run my program without using the command line that just gives results line by line?

    on Aug. 28, 2012, 3:21 p.m.

    Tyler Cipriani said:

    You just need to save your script in a file with the extension .py then run the file using python

    on Aug. 28, 2012, 3:42 p.m. in reply to Youngestprof

    Ariel said:

    hi, you can write a .py file on a text editor, and then you can play a file only with double click. 2012/8/28 twonjee2002 <
    on Aug. 28, 2012, 3:55 p.m. in reply to Youngestprof

    drediamond said:

    I use text wrangler as a free editor

    on Nov. 18, 2012, 4:58 p.m. in reply to Youngestprof
  • saravanan said:

    #Calculate the Area of a circle
    import math
    print('To Calculate the Area of a Circle')
    radius=float(input('Enter the Radius of a circle:'))
    area=math.pi*radius**2
    print('The Area of a Circle is:',format(area,'.2f'))
     

    Output:

    To Calculate the Area of a Circle
    Enter the Radius of a circle:5
    The Area of a Circle is: 78.54

    on Aug. 14, 2012, 7:14 a.m.
  • Rob said:

    script for calculating volume of sphere can be found here:

    http://dpaste.com/771135/

    on July 15, 2012, 10:03 p.m.
  • smk said:

    Calculate the area of a circle (with pi as 3.14159265359)

     

     

    # Calculate the area of a circle
     
    pi = 3.14159265359
     
    radius = float(raw_input("Enter the radius of the circle: "))
     
    print "The area is: ", pi * radius ** 2
    on July 15, 2012, 12:04 p.m.
  • Inkbug said:

    It would be nice to have both Python 2 and 3 links.

    on July 12, 2012, 8:28 a.m.
  • Inkbug said:

    Simple exponent calculator (python 3):

    x = input( "Base: " )
    y = input( "Power: " )
    print( float( x ) ** float( y ) )

    on July 12, 2012, 8:20 a.m.
  • ionut.vlasin said:

    Ex1 and 2 from the  book

    http://pastebin.com/NaTB7iN0

    and computation of rectangle area:

    http://pastebin.com/s26BDsUF

    on July 9, 2012, 10:01 a.m.
  • Andres Kwan said:

    Calculate volume and surface of a cone.

    http://pastebin.com/guDMnuw6

    on May 11, 2012, 2:33 a.m.
  • motorjunky2000 said:

    Here is my simple program to calculate area and volume of a cylinder:

    http://dpaste.com/745854/

    on May 9, 2012, 10:36 p.m.
  • Carl Burkart said:

    Here is my program to calculate the circumference and the area of a circle given the radius.  I used 22/7 for pi because I wasn't sure how to express it in python.  Corrections welcome.

    http://dpaste.com/hold/745262/

    on May 8, 2012, 10:31 p.m.

    pannix said:

    You need to import the math module and then you can use math.pi. See http://pastebin.com/EFhE4Vsa

    on May 9, 2012, 11:55 a.m. in reply to Carl Burkart