1.2 Objects and Variables


Before delving into this chapter, it’s crucial to recall how to run a fundamental Python program, whether you’re using Thonny or Atom. If you need a quick refresher, you can refer to the previous chapter for a step-by-step guide.

In the world of Python, there’s a saying that ‘everything in Python is an object.’ As we progress, we’ll dive deeper into this concept and gain a more profound understanding of it. But, let’s begin by exploring the fundamentals of data types.

In the last chapter, we laid the foundation by creating a simple program with just one command. Now, let’s build upon that knowledge and take the next steps in our Python journey.

Our single line program was as follows

print(2+3)

The program’s output was ‘5, which is  the addition of the two numbers     2+3.’

Let’s create a new Python program named ‘variables.py’ and add a few more commands to it:

  1. Open your Python development environment, whether it’s Thonny or Atom.
  2. In the editor, create a new Python file and save it as ‘variables.py’ within your designated project folder.
  3. Add the following lines of code to your ‘variables.py‘ file:
print(2 + 3)
print('2 + 3')
  1. Save the file.
  2. Now, run the program by clicking the ‘Run’ or ‘Execute’ button in Thonny or using the terminal/command prompt if you’re in Atom.
  3. Observe the program’s output

This is how Python executes the individual commands.

Line NoInputOutput
1print (2+3)5
2print (‘2+3’)2+3

The quotes (‘    ‘) in the print command change how Python interprets what’s inside the ‘print’ command. 

At line no 1, the input is treated as numbers, and Python has proceeded to execute the addition’s mathematical operation.

At line no 2, the input is treated as characters, including the addition sign, and prints them out as mere words.

Within the inverted commas (quotes ‘  ‘), the characters’ input is technically called a ‘String.’

  • Python defines Characters (letters) data as ‘String.’ 
  • Numbers are divided into two data types,
    • ‘Integers’ — when no decimals are involved, 
    • ‘Float’ — when decimals are present. 

Syntaxes for data types: Let’s understand this concept by using an example. Modify the program by adding the two commands below and run it in Python. 

print(2+3)
print(‘2+3’)
print(‘2 plus 3’)
print(2 plus 3)

Upon running this file, we get the following message from Python.

The program output indicates a ‘Syntax Error’ while processing line 4. Syntax errors occur when the rules of a programming language are violated.

As previously discussed, in Python, strings are defined within quotes (single or double), while numbers are defined without quotes. In line 4, we did not use single quotes to enclose the characters (2 plus 3) which makes Python interpret it as numbers. However, the line also contains the word ‘plus,’ which doesn’t fit the expected syntax for a number.

This violation of the syntax rules results in an error. To resolve this error and allow the program to run smoothly, we can simply remove line 4. Doing so ensures that the program adheres to Python’s syntax rules without any issues.


 A. Rules for Mathematical operations in Python

In introductory algebra, we’re familiar with the BODMAS rule (Brackets Off Division Multiplication Addition Subtraction), which governs the order of operations in mathematical expressions. Python follows a similar rule with a slight modification, using PEMDAS (Parentheses, Exponents, Multiplication, Division, Addition, Subtraction).

In Python’s order of operations, when multiple operations share the same precedence, they are evaluated from left to right. This means that the operation that comes first from the left is solved first.

For example:

50 ÷ 5 • 5:

When we move from left to right, the division (50 ÷ 5) occurs first and is solved first, resulting in 10. Then, the multiplication (10 • 5) is performed, giving us an answer of 50.

With brackets:

Now, let’s consider the same set with brackets: 50 ÷ (5 • 5). In this case, the brackets operation comes first, and (5 • 5) equals 25. Then, the division (50 ÷ 25) is solved, resulting in an answer of 2.

Similar to its syntax for strings, Python has specific syntax rules to represent mathematical operations, ensuring that expressions are evaluated correctly following the PEMDAS rule

Brackets Off, Exponential, (Division or Multiplication), (Addition or Subtraction)

NoMathematical OperationMathematical SymbolPython Syntax
1ExponentialX YX * * Y
2DivisionX÷YX/Y
3MultiplicationX • YX * Y
4AdditionX+YX + Y
5SubstractionX-YX – Y

To explore these mathematical expressions, create a new file (‘Math.py’)

print(50/5 * 5)
print(50/(5*5))

The output we get is,

Exercise

Perform hand calculations for the equations and subsequently create a Python program to verify the solutions.

  1. 33 + 9 ÷ 3
  2. (10÷5) • (50÷10)
  3. 10÷5•50÷10
  4. 200*10+1000 – 2000÷2
  5. (((20÷5)+10)•((30-6)-10))2


B. Variables in Python

In introductory algebra, we often encounter problems where we need to solve mathematical expressions. These problems typically present questions like: ‘If the value of ‘A’ is 10, and ‘B’ is 5, and C = A • B, then what is C’s value?’

In these contexts, ‘A,’ ‘B,’ and ‘C’ are referred to as ‘parameters’ or ‘variables.’ These variables represent quantities that can vary within the context of the mathematical problem.

Now, the pivotal question is: How do these variables benefit us? Let’s illustrate this with an example. Consider the following equation:

Solve (22 ÷ 7) • (5)²

This is a generic problem that can be easily solved. However, we can rewrite the same problem in a variable format:

C = (22 ÷ 7) • (A)²

In this equation, ‘C’ and ‘A’ are our variables. If you look closely, you might notice a connection to basic geometry. This formula is reminiscent of the formula for the radius of a circle.

Area of Circle = (22÷7) • (Radius)2  

Variables provide a powerful way to generalize and represent mathematical relationships. They allow us to create equations and formulas that can be applied to a range of scenarios, making mathematics a versatile and practical tool for problem-solving in various fields

When we input a generalized formula into Python, we gain the ability to solve for different values, making our program interactive and adaptable. To do this, we need the capability to change the value of a variable, such as the radius in our example, interactively. The most effective way to achieve this is by prompting the user for input and storing that input in a variable. The command used for this purpose is ‘input.’

A=input("Enter radius")

In Python, ‘A’ is the variable name, and ‘input()‘ is the command used to prompt the user for input.

The message within the ‘input()’ command, enclosed in quotes (“Enter radius”), serves as an informational prompt displayed to the user, indicating the type of input expected.

The complete program for calculating the area of a circle can be expressed as follows

A=input(“Enter radius”)
C=(
22/7)(A**2)
print(C)

When we run this program, the output is as follows

However, when we run this program, we encounter an error: ‘Type Error: Unsupported operand types for ** or pow(): ‘str’ and ‘int.’

In this error message, ‘str’ stands for ‘string’ (representing the data type of ‘A’), and ‘int’ stands for ‘integer’ (the data type used in the mathematical operation).

The issue arises because the ‘input()’ command, by default, treats the user’s input as a string, and then, in the subsequent line, we attempt a mathematical operation (‘A ** 2’) on this string. This results in an error.

To resolve this issue, we must declare the data type we expect from the user’s input. We have two options: ‘integer’ (for non-decimal numbers) or ‘float’ (for decimal numbers). Given that our program involves a decimal term (22 ÷ 7), it’s wise to use floats.

Here’s how we declare the data type in the ‘input()’ command:

A=float(input(“Enter radius”))
C=(
22/7)*(A**2)
print(C)

Encasing an expression in a float bracket,    float( )      extracts a float value. 

In the output above , we entered the radius as    23‘,      and the value highlighted in the rectangle      1662.57..      is the circle’s area.


C. Clarity and readability of Python Program 

The ‘circle.py’ program accomplishes its intended task by allowing users to input the value of the ‘radius’ and obtain the ‘area’ as output. However, consider someone who only views the output window; that person might become confused about the meaning of the value ‘1662.57.’ Is it the circumference of a circle with a radius of 23? Is it the volume of a sphere with a radius of 23?

To avoid such confusion, our program should provide clarity in a way that anyone viewing only the output can understand the program’s purpose without having to open the source code.

The term ‘source code‘ refers to the original Python program we created, in this case, ‘circle.py.’ Source code has its own requirement – it should be ‘readable.’

Think about a situation where someone revisits your code five years down the line; the code should be so well-structured and documented that the person can easily comprehend its logic and flow. If the person needs to contact you for clarification, your code may be considered ‘unreadable.’

To make code readable, we can use techniques like adding empty lines and incorporating comments into our program. In Python, we use the ‘#’ symbol to include descriptive comments within the code. These comments provide explanations and context for each section, making it easier for both you and others to understand and maintain the code. Here is an example of it:

 
# Python program for finding area of circle with radius as an input
 
# Asking user to input radius and storing it as datatype float
_r1 = float(input(“Enter the value of radius :”))
_a1 = ((
22/7)*(_r1 ** 2))
 
# print area of circle with context
print(“For a circle of radius”, _r1, “the circular area is: “, _a1)

The output is

The comments prefaced by ‘#’ are not processed by Python for the output and serve to make the code ‘readable.’ In contrast, the print command’s context brings clarity in the output.


Variable Names in Python

n the context of our ‘circle.py’ program, we created two versions of the code.

The first version used variable names ‘A’ and ‘C’ to represent the radius and the area, respectively. However, in the revised program, we opted for more descriptive variable names, using ‘_r1’ for the radius and ‘_a1’ for the area.

When it comes to naming variables in Python, there are some key rules to remember:

  1. Variable names cannot begin with a number. They must start with a letter or an underscore.
  2. After the initial letter or underscore, variable names can contain letters, numbers, and underscores.
  3. Special symbols, aside from the underscore (‘_’), are not allowed to be part of variable names.

Following these rules ensures that your variable names are clear, informative, and in compliance with Python’s naming conventions. Descriptive variable names contribute to the clarity and readability of your code.”

Exercise

  1. Get as input the length and breadth of a rectangle, and calculate its area.
  2. Get as input the inner and outer radius of a circular ring and print the ring area as the output.
  3. Create a program that receives the circle area as its input and prints circumference as an output. (Square root is exponential to the power 0.5, (25)**0.5 = 5)
  4. Calculate the volume of a cube by using the length of the cube as the input.
  5. The age of Anju is twice that of Sanju. Input the age of Sanju and print the age of Anju as the output.

Prev Chapter    Course Homepage    Next Chapter

“Always code as if the guy who ends up maintaining your code will be a violent psychopath who knows where you live”

1 Comment

  1. […] Prev Chapter    Course Homepage    Next Chapter […]

Leave a reply

Your email address will not be published. Required fields are marked *