Wednesday, April 30, 2025

Introduction to Python

 Introduction to Python

The Python programming language is very similar to scripting languages of the early days, such as Perl, Unix shell scripts, awk, etc. But, it is much more than such languages to support larger programs. It is capabable of completing tasks with fewer lines of code (shorter programs) when compared to dominant programming languages such as C++/Java. Programs written in Python are very compact, less verbose and also readability at its best compared to C++/Java. 

Python Interpreter

Python command line with interpreter is a point of start for Python programming. If Python is not installed on your system, and if your computer has the Internet connection, then connect to Python.org to launch the interactive shell. You will find the command prompt as follows after launching the shell.

>>>
Start learning it as your calculator.
>>> 5+5
10
>>> 30-2*2
26
Do not hesitate to test and verify BODMAS rules. Now, try to use the command line to test small programs. Let us write code to add two numbers.
>>> a = 100
>>> b = 200
>>> c = a+b
>>> c
300
Now, write programs to multiply, divide, subtract and many more operations. But to carry out operations, you need operators. Do you know the operators in the Python programming language? If not, read the next topic and continue working with the Python command line interpreter.

Operators

The list of operators with their intended operations is listed below. All these are arithmetic operators with precedence levels from highest to lowest (recall BODMAS). Some of the operators are new; they are described after the table. Other operators of Python will be introduced in appropriate sections.
____________________________________________________________
Operation                                Operator            Example             Result
____________________________________________________________
Exponet                                        **                    2**4                    16
mod                                               %                    5%2                       1
Integer division                             //                     9//2                        4
(floor division)
Division                                        /                       9/2                       4.5
Multiplication                               *                      5*5                       25
Addition                                        +                     5+5                       10
Subtraction                                    -                      5-5                        0
____________________________________________________________

The modulus operator % computes the remainder of the division, whereas the integer division operator // computes the integer result by neglecting the fractional part. The exponent operator computes the power. Examples are provided in the table itself.  You know about the operators in Python now. But what about data? On what type of data do they operate on? 

Basic data types

There are three basic data types in Python: integer, floating point, string. Let us learn about each one. 

Integer (int): This is well known to all of us. Examples are,
        -98, 399, 0, 33, 933333, 333999, etc

Floating point numbers (float): They are real numbers with a fractional part included.
        -45.88, -0,45, 0.01, 56.90, 33433.0, 45555.3355644, etc

Strings (str): These are a sequence of characters enclosed within single or double quotes.
        'r', 'rr', "r", "Rrr",  "value", 'location', "133", "34.56", "abc123", etc.

The example "133" is a string of characters,  not an integer number 133. Operations on integer numbers and floating point numbers are as known to us from school. But string operations are new with strange mathematical operations. Let us learn them now.

Operations on strings

There are two prominent operations on strings. They are referred to as

Concatenation (+)
Replication (*)

Concatenation: Let us learn along with Shell.
>>> "one"+"two"
onetwo
>>> "three"+"4"
three4
>>> 'they'+ "are" + 'new"
theyarenew
>>> 'they'+' ' +are+' '+'new'
they are new

and so on. Concatenation is adding strings in sequence to create new strings. Both operands must be of string type for the string concatenation operation. The following in the Shell results in error

>>> "one"+100
Interpreter says an error in the instruction/statement.

Replication (*): Let us learn with Shell.
>>> 'one' * 3
oneoneone
>>> 'two ' * 3              # blank space included in the string "two "      
two two two

The replication operation on strings is a string repetition operation. You can't apply * operator on two different strings. The following statement is wrong and interpreter never executes the statement.

>>> 'one' * 'two'            # wrong usage of replication operator

String operations in Python is a big topic and will be discussed in detail later. Now, we know about data and operators to operate on data. As we know from math, we need variables to assign values to compute something. For example, to compute the area of a rectangle using the equation, 
                                    
                                                    A = length * width 
Three variables are necessary to do the computation (A, length, and width). Let us learn about variables in Python.

Variables

A value is assigned to the variable using the assignment operator (=) as shown below.

length = 2
width  = 4

Then the following statement computes the area of the rectangle.

A = length*width

But how to name the variables in Python PL? Any rules for naming variables? Yes. There are some rules for naming variables

Rules for naming variables: 
1. Use only alphabets (a-z, A-Z), numerals (0-9) and underscore (_) to name variables.
2. The variable name should not start with a numeral.
3. Variable names are case sensitive (a and A are distinct)

Some valid variable names are listed as follows.
length, LENGTH, Length, length_rect, length1, _length

Some invalid variable names are as follows.
3length        # should not start with a numeral
length$,      # special characters are not allowed

Variable naming conventions: There are some standard ways (not rules) to name variables. These conventions are necessary to improve the readability of programs and to follow some standard naming practices. As I observed, the following conventions are as follows in Python PL. 

1. Separate the words using an underscore if the name consists of more than one word
2. Use only lowercase to name the variables (uppercase is also used but for different identifiers)
3. Underscore is used as a beginning letter to name some special variables (internal use)
    
Ex: length_rect, length_rect_cm, 

Guidelines for naming variables:  The names of variables should be very close to their real participation in programs.  For example, to compute the area of the rectangle variables can be named in the following different ways.
1.  a, l, w
2. area, length, width
3. rect_area, rect_length, rect_width
4. rect_area_cm, rect_length_cm, rect_width_cm
and many more ways.

The 4th one is understandable (readable) to anyone using your program (or reading). This is about a rectangle, computing its area and the units are in cm.. 

Some introductory functions in Python

Functions are like block boxes. You need to understand its inputs and outputs. It does some job for you. You need to know what it does, not necessarily how it does the job.

Functions to convert data type from one to another (typecasters:int(), float(), str())

There are three basic data types in Python: int, float and str. Sometimes, it is necessary to convert from one type to another while writing code for some tasks. The type conversion from one to another with the help of code snippets is given below. 

int():  The int() function converts other data types (float/str) into an integer type as follows.

string_value = "187"
int_value = int(string_value)   # int_value = 187

The int function converts a string into an int only if it has numerals in the string form. If the string_value = "18A", the int() throws error.

float_value = 839.98
int_value = int(float_value)    # int_value = 839

The int function truncates the fractional part of the floating-point number.

float() function: This function converts data from other types (int, str) to the float type. The following code lines help you to understand the same.

int_value = 123
float_value = float(int_value)        # float_value = 123.0

string_value = "123.234"
float_value = float(string_value)        # float_value = 123.234

The string variable should have only numerals with a decimal point within quotes. Any other character in the string, the float() throws an error (for ex. string_value = "123.234f")

str() function: This function converts other types of data (for ex: int and float) to string data type. The following code snippet helps you to understand the same.

int_value = 123
float_value = 567.43
int_string = str(int_value)                # int_string = "123"
float_string = str(float_value)          # float_string = "567.43"

These typecasters are useful in many places during program development. One such situation is explained in the next section.

Functions for input and output of programs

Python has plenty of facilities for input and output of programs or applications. Here, only two functions are discussed: one for output (print()) and another for input (input()).

print() function: This function is useful to print messages on the terminal. Some examples with their output is as follows.

print("Hello world!")              # hello world!

length = 100
print("length = ", length)        # length = 100

print("Hello", end='_')             # separator argument end with underscore (_)
print("world!")                        # print on the terminal: Hello_world!

The print function automatically moves to the new line after its execution. It can be forced to stay on the current line using the separator parameter named end of the print function. It is illustrated in the code snippet shown above.

input() function: The input() function is useful to read a string from the keyboard. However, it is often used to read integer and float values also with the help of type casters. The following code snippets help you to learn reading a string, an integer and a float value from the keyboard.

# Reading a string:
string_value = input()            # waits for the user to enter the string
print(string_value)                 # verify the input function

# reading an integer
int_value = int(input())           # input() reads a string, type caster converts the string into int
x = int_value+10                     # verify that  int_value is integer now   
print(x)                                

# code to read a float value
string_value = input()                        # read a string from keyboard
float_value = float(string_value)        # convert string into float
print(float_value)                                # print its value 

# input function can also be used with user interface statement
int_value = int(input("enter and integer"))
float_value = float(input("enter a float value"))
string_value = input("enter a string")

Let us write some programs using the learnt operators, about variables names and functions.

Programs

Let us write a small program to read (input), compute and output (print). Read the student's details such as name, USN, and marks in a few subjects. Find the total marks and percentage. Print details of the student on the terminal.

# The comment line begins with #
# input: Read the details of the student
print("Enter the detials of the student ")
name = input("Enter the name of the student ")
USN = input("Enter the USN of the student ")
marks1 = int(input("Enter the marks of the first subject "))
marks2 = int(input("Enter the marks of the second subject "))
marks3 = int(input("Enter the marks of the third subject "))

# computation
total_marks = marks1+marks2+marks3
percentage = total_marks/3

#output: print results on the screen
print()
print("The output of the program is as follows")
print("The student Name: ", name)
print("USN: ", USN)
print("Total marks = ", total_marks)
print("Percentage = ", percentage)

Enter the program in a file and name the file appropriately (ex, StudentMarks.py). Run the file. If there are any Python syntactical errors, it stops at that point and displays a message (compiler errors). Otherwise, executes the program but stops if there are errors, which hampers the computation. 
For example, if the int keyword used for typecasting is typed as in, it results in a compiler error. If average_marks is typed as average_mar, no compiler error, but an interpreter error (while running the code). Make some errors in the source file and test. This program gives you the following result.

Enter the detials of the student 
Enter the name of the student = John
Enter the USN of the student =  MRT100
Enter the marks of the first subject = 65
Enter the marks of the second subject = 65
Enter the marks of the third subject = 89

The program output is as follows
The student Name:  John
USN:  MRT100
Total marks =  219
Percentage =  73.0