Python Programming Language

A Simple Math Program in Python

By

First published on October 10, 2019. Last updated on February 6, 2021.


Python was written with mathematics in mind, so let’s examine a simple math program. Several important new concepts will be introduced.

First, it is important to document your code. This will help you remember why you wrote things a certain way, and it can help other people better understand your program. In Python, lines that begin with “#” are treated as comments. Python won’t do anything with code after the # on a single line.

# This is a comment.

Second, is the concept of the variable. Unlike states text, such as “Hello World”, variables can change. However, they don’t change by themselves. First, you have to assign them a variable. Then you can change them later. In the following program, “x” is variable.

# x is assigned a value
x = 1

Third, you can perform operations to change, combine or compare variables. In the program below, we use the “+” operator to combine the variable x with the constant 5.

# x is assigned a value
x = 3

# x and 5 are combined
y = x + 5.0

# Result is displayed
print('Y = ', y)

The above program assigns a value to x and then adds 5 to x. The result is displayed as y. When writing calculations in code, we often want the result to be a decimal. Writing the 5 as “5.0” will tell the program that we want a decimal calculation. Each language may handle this differently, but it is a good habit to get into the habit of adding the “.0” or else you will face many hours of grief in the future.

Activity

  • Write and run the above program. Save it as MyMathProgram.py
  • Try out initial values for x. Your final result should change for each different value of x.

Leveling Up

  • Add your won comments to the above program.
  • Create additional variables and calculations, and display multiple values in the same line of results.

COURSE


Content is copyright the author. Layout is copyright Mark Ciotola. See Corsbook.com for further notices.