L

learnasyoulike

time


Python Interactive Mode

Table of contents:



Python interactive mode and the print statement



python simple syntax easy to learn beginner- friendly 137000 libraries! well- supported powerful popular web development desktop and mobile applications data science machine learning artificial intelligence object- oriented high- level

Python is an easy, yet very powerful high level programming language. It is an interpreter that translates high-level statements into machine codes. It is a very popular, general-purpose, object-oriented, high level programming language. Presently, python is used for application development involving data science, desktop and mobile applications, machine learning, artificial intelligence, web development and many more.

Python is very suitable for beginners. The statements are English-like, short, simple and easy to read.

Let us delve into the basics of python programming language in this series of webpages.



Table of contents:




Working with python involves two ways:
Script mode:
Interactive mode:

Script mode

In python script mode , we use some text editor to create a text file with .py extension, say, example.py. We write multiple python statements in this file. With valid python statements and the .py extension, the file becomes an actual python program/script.



In script mode, all the statements are executed in a single run, from top to bottom one by one.
The above program calculates the perimeter and area of a rectangle, given its length and breadth as input. You don't have to understand it now, the structure of the script is important here.

Python interactive mode

To work in interactive mode, we use an environment Integrated Development and Learning Environment or IDLE.

IDLE shell is an environment window for executing a single python statement, generally one at a time. It produces instant output.

A python IDLE window IDLE shell

It is automatically installed when Python is installed for Windows from here.

Alternatively, you can go to the windows command prompt and type python and press enter. Now you will be able to execute single python statements from here:

A python shell window Python shell (command line)


Before creating actual python programs, let us first practise entering single statements in IDLE shell, which will help writing short programs later in script mode.

Note: In this series, the terms 'statement', 'command' and 'instruction' have been used synonymously.

In python, print is a function used to display some data on the screen. It is a frequently used used in a variety of ways.

In the following is an imitated python IDLE shell which will be frequently used in this python series. Here we instruct python to display the text "Hello World!".

>>> >>> | Hello World! Press ENTER here user's input python's output

As soon as we type the statement print("Hello World!") and press ENTER, the python interpreter immediately executes it. The output is displayed in the next line. Input statements are shown in colours, outputs are in white.

To display a group of characters like "Hello World!", quotations are needed.

A sequence of characters inside quotations is called a string. In python, generally double and single quotes function similarly.

In the above, print is a statement through which we give an instruction to python to do something.
The primary purpose of print is to display something on the screen; but it can do more, as we will find gradually.

So, we executed our first statement in the IDLE shell.

When we display a number with print, quotations are not needed.

A number without quotations is a numeric value. "Hello World!", 123, 45.6 are values.

Literals and Data-types

In computer programming, a value is a number, or a character, or a sequence of chracters, digits, symbols, punctuations etc. Following are the examples of values:
11, -59, 0.4, -3.7, +268 "11", "hello", "abc@#$", "Python is easy and powerful!"

The above values have a technical term, literals.
Literals are raw data or fixed values; those constants do not change during the execution of a program. Every literal has a data-type.

123 is an integer literal. It is of integer data-type, and recognized by python as 'int'.

45.6 is a float literal. Decimal numbers are of float data-type, and recognized as 'float'.

"Hello World!" is a string literal. It is of string data-type, and recognized as 'str'. String literals must be enclosed within quotes.

The term data-type is a very important conception in programming. From now onwards, you will find it frequently.

We can find the data-type of any literal by using another function type(). The purpose of type() is to find the data-type of the given literal, variable, or expression. .



The output <class 'str'> indicates that the given character set "Hello World!" is of 'str' data-type(string).


<class 'int'> confirms that data-type of 123 is 'int', <class 'float'> denotes that of 56.7 is a 'float' type.

Arithmetic operators and calculations

With the use of print(), let us have some calculations through python. The print(4 + 5) produces an output of 9. The interpreter calculates the 4 + 5 part, and displays the result in the next line.



In the above, print() has been executed four times, each with different inputs, to produce different outputs.

4 + 5, 7 - 6, 8 * 90 and 100 / 25 are expressions. The +, -, * and / are arithmatical operators representing addition, subtraction, multiplication and division respectively.

If we omit the print(), IDLE shell works almost like a calculator:


Commenting in python

If a python statement has a # in the beginning, it is treated as a comment, and the line is not executed. A python comment goes like this:

# This is a comment in python

For multi-line comments, we can write the lines inside triple quotes, as in the following:

"""
This a multi-line comment
Those should be enclosed in triple quotes
End of multi-line comment
"""

The above string is not actually a python comment, rather it acts as a comment. Such triple-quoted multiline strings inside a use-defined function have some special meaning.

In computer programs comments are introduced to describe purpose of the succeeding statements. They increase the readability of a program, especially if it is a large one. Using a # is just one way of commenting; but there are multiple ways to comment a line. The next IDLE windows introduce some commenting examples (in gray).

Printing multiple values in same line

Python can display multiple literals with a single print() as in the following.

Three string literals are separated by commas in the input. For each comma in the input, one space is inserted in the output. Here, the commas are known as separators. To display multiple values, commas are mandatory.

We can print different types of values in a single line.


A septagon has 7 sides Two spaces already in the input literal Spaces inserted by python due to commas


The only even prime is 2 Spaces are already in the input Space inserted by python due to comma

In the above statement
print("The only even prime is", 2),
the space after the comma has no effect in the output. This means all of the following will have the exact same output.
print("The only even prime is", 2)
print("The only even prime is", 2)
print("The only even prime is",  2)



What if we want commas in the output itself? We may include commas inside quotes, like
print("python,", "java,", "c++"),
but that's not a programmer's way! Let us use a technique as in the following:



To force print commas in between, we added sep="," in the end of the function. This has inserted commas inbetween the output-strings.

We can even insert any set of characters like "..." in between, as per our requirement.


Changing the value of sep changes the output accordingly.
By proper use of sep, we can have useful outputs like:


In the world of computer programming, the \n denotes a newline character. It is known as escape sequence, and almost every programming language has its use.

With the help of sep="\n" we can print multiple strings in multiple lines, though a single print() has been used.


You have probably guessed how important print() is. But in IDLE window, we can display output also without the use of print(). (We have already omitted print() in above examples).

But, this is possible only in IDLE window. When writing python programs(script mode), we must use print(77.9), print(1234567890) etc.

When you make a mistake while feeding a statement or function, python displays an error message. Suppose you enter the following:

>>> prnt(9)

The print spelling is incorrect, so python displays an error message:

Traceback (most recent call last):
File "<pyshell#0>", line 1, in <module>
prnt(9)
NameError: name 'prnt' is not defined. Did you mean: 'print'?


Re-type the command corrctly and press enter. The error message won't appear, and output will be displayed, if any.

Let us have some discussion on python variables and expressions in the next page.

What are python objects

Python is an object-oriented programming language. Everything is an object in python.

A python object is a concrete piece of information that resides somewhere in the computer memory. It can be an integer, float, string, list, tuple, dictionary, set etc.

Every python object has three attributes, identity, type and value.

A python object Object Id 2696621240912 related function id() data-type 'str' related function type() value (immutable) "Hello World!"

Identity of an object is like the memory address of that object. Once an object is created, its identity cannot be changed. The id() function returns the identity of an object. The is and is not operators can compare the identities of two objects.

Type of an object is the data-type of the value the object has; it is unchangeable. An object may be of integer type('int'), float type('float') etc. The type() function returns the type of an object.

Value is the content of an object.


Mutable and immutable objects

When the value of an existing object can be changed, the object is mutable. If the value of an existing object cannot be changed, the object is immutable.

Object Mutable Immutable Can be changed 'list', 'dict', 'set' Cannot be changed 'int', 'float', 'str' 'tuple', 'frozenset'

Mutability and immutabiliy are core concepts of python, and they require a very good understanding. It is very important to know that lists, dictionaries and sets are mutable objects in python; while integers, floats, strings, tuples, frozen sets etc. are immutable objects.

What are python functions

A function, in any programming language, is a reusable block of codes which can be executed by calling its name.

A python function is an object that resides in memory, which has a valid name, type and identity.

When we call a function by its name, the multiple line of codes it contains are executed.

Note: The conception of function requires a separate article. Understanding what is a function in the introduction page might be difficult. But while explaining basic things of python, the terms function, argument, parameter etc. are inevitable. So, a short note might help as an introduction. After going through some consecutive pages, the conception of functions will become clear gradually.


Python built-in functions

For a function, there are two tasks involved.
1) Defining a function:
Here, we give the function a name, decide its parameters(input) and return value(output), and write the function. The body of the function contains python codes. Defining a function is done once.

2) Calling a function:
We put a function into work by calling it. This is done whenever required. To use a function, we must know about the function name, arguments and return value.

We are just coming to what are parameters, arguments and return value, when we explain examples.

Functions can be mainly of two types, built-in and user-defined.

Built-in functions are those which are provided by python. We do not have to write or define a function, we just use them by calling. The print() and type() used above are built-in python functions.

User-defined functions are those which we write ourselves as per our requirement. The details of writing a function of our own needs a separate article.

When we call a function, we pass a value to it(not always). We call this value an argument. When the function receives this value, we call value a parameter which is actually a placeholder. So, practically there is no difference between them. We can also call it the input to the function.

Then the function runs its own codes, and as per the received input, it returns an output to us(not always). We can now use this output for other operations.



A Function Call >>> len ( "python" ) >>> | 6 function name argument (input to function) return value (output from function) parenthesis must

Take the example of the built-in function len(). It counts the length of the object passed to it and returns the value. The function name is len, we pass exactly one argument(input) to it, and it returns(output) an 'int' type value. The argument we pass must be of type 'str' or 'list' or 'tuple' etc., and cannot be of type 'int', 'float', 'bool' etc. What type of argument we can pass to the len() function is clearly defined/documented.

Some functions may or may not take any argument. Also it is not necessary that every function will return an output value. The print() function without any arguments displays a blank line.

Note: If a function has nothing to return, it returns a None.


Following is the use of int() function. It accepts one argument, converts the value into 'int' type, and returns the converted value.

function name: int argument: 3.2 return value: 3

When we say, int(3.2) returns 3, we actually mean that int(3.2) is evaluated to 3. This is also applicable to expressions.


Following is the use of float() function which converts a value into 'float' type:

function name: float argument: "5" return value: 5.0

The len() function returns the length of an object. This function always returns an 'int' type value.

function name: len argument: "python" return value: 6

3.2 is a float literal. When it is converted to integer, we get 3. int(3.2) works like an expression actually, which always evaluates to 3 as seen in the following:

The print is omitted in the above.

Methods

Methods are very similar to functions. In both the cases a block of re-usable codes is executed by calling. But, in general, functions are independent block of codes while methods are tied to objects/classes and called with a dot notation.

Simply, a method is like a function, but it runs "on" an object.

len() is a simple, independent function in len("python"), and returns the length of the string "python", i.e., 6.

.upper() in "python".upper() is a method of 'str' type object, and returns the string "PYTHON".






--- x ---









Want to leave a message for me?