Lesson 04: Interactive programming with Python

In this lesson, we will explain the interactive mode of Python; How to enter or exit, write code or get tips on something in this language. After reading the previous lesson and the first two parts of this lesson, you will become familiar with script execution and Python interactive mode; Accordingly, in the third part of this lesson, we will explain the options used in calling the Python interpreter, which are somehow related to both of these topics. This lesson is full of topics that will be examined in turn (!) In the future (like the concept of an object ). Of course, a short explanation is provided to understand the topics, but it is better to focus on the main topics of the lesson and not get too involved; Just remember!

 Level: Basic

 

Interactive mode

We remember from the previous lesson that Python code can be executed in two ways: 1- Creating a script and introducing it to the Python interpreter that was examined in the same lesson 2- Interactive with the Python interpreter which is the subject of this lesson.

Python is an Interactive Mode programming language; This feature is based on the command line, features for processing and code execution (orders, statements [1] and defined) provides the Python language. Coding in this case is like when you create a script; But every time you press the Enter key on the keyboard, the Python interpreter executes it automatically.

Of course, the interactive mode has limitations that you will see, but from some angles it is very convenient and practical; For example, you may want to test one of the features of the Python language, or you may want to see the output of a short code snippet, in which case creating a script and then executing it can seem like a daunting task! Another advantage is that it is very useful in remembering, recognizing and gaining knowledge of Python language items (keywords, functions, classes, modules, etc.), even some of this Python mode as a calculator Benefit!

To enter the Python interactive mode, the interpreter call command (general mode python) – alone and without arguments – is used in the operating system command line interface.

Enter Python 2x Interactive Mode – Windows

> cd C:\\Python27

> python

Python 2.7.9 (default, Dec 10 2014, 12:28:03) [MSC v.1500 64 bit (AMD64)] on win32
Type "help", "copyright", "credits" or "license" for more information.
>>>

Enter Python 3x-Gnolinux Interactive Mode:

user> python3

Python 3.4.2 (default, Jan 25 2015, 20:02:16)

[GCC 4.9.2 20141101 (Red Hat 4.9.2-1)] on linux

Type "help", "copyright", "credits" or "license" for more information.
>>>

Is displayed after a message arrives; In this message, while providing basic information about Python Interpreter and operating system, it is recommended that you use special commands to find out more about the Python programming language:

  • ()license: Displays several pages related to the development date and Python licenses, which of course can also be viewed through the Python History and License page . Use the Enter key to navigate and the q key to scroll through the keyboard.
  • creditsDisplays a list of organizations and companies involved in Python language development.
  • copyright: Displays the copyright list of the Python language from the beginning to the present.
  • helpThis command has many uses, which will be discussed below. This command can be used to guide various objects and components in the Python language.

In Python interactive mode, each row is >>>specified by an icon by default , and since it is possible to enter multi-line commands (such as functions); The lines related to the body of a command ...are indicated by a symbol .

After entering each line and pressing the Enter key, the interpreter processes that line and, if necessary, displays the result or report of the relevant exception. In fact, after pressing the Enter key, it will no longer be possible to return and modify the entered line, and that line must be re-entered. Obviously, the occurrence of errors in multi-line commands means the need to re-enter the entire command

>>> print("(50-5×6)÷4 =", (50-5*6)/4)

(50-5×6)÷4 = 5.0

>>> def func():
...     print("(50-5×6)÷4 =", (50-5*6)/4)
...

>>> func()

(50-5×6)÷4 = 5.0

consideration

Python defuses a keyword to define a function , followed by the name and then the function parameters (if needed) in parentheses. After the colon, :and in the next lines, with uniform uniform indentation, the body functions of the function are written. By calling the function (entering the function name) the body of the function is executed. If parameters are also considered in the definition of the function, their corresponding value must be specified when calling (in parentheses in front of the function name) – in the above code, the function has funcno parameters, so no value is sent when calling. [Only for basic knowledge – Python function will be examined in a separate lesson]

Attention

To end multi-line commands, you must leave the last line blank and press Enter.

Use the Ctrl-L key combination to clear the screen. To exit, you can also enter quit () or use the Ctrl – D key combination in Gnolinux and the Ctrl – Z key with an Enter key then in Windows .

One of the advantages of the interactive mode is that in most cases you do not need to use print to view the result:

>>> a = 2
>>> a
2

>>> (50-5*6)/4
5.0

And if you are doing math, you can use a special variable called _(Underscore); This variable always refers to the last value [2] calculated:

>>> 5 * 6

30

>>> _

30

>>> 50 - _

20

>>> _ / 4

5.0

Another example – In mathematical application, some functions are available by module mathfrom the Python standard library [ Python documents ]:

>>> import math

>>> math.sqrt(36)
6.0

>>> math.pow(3, 2)
9.0

>>> math.radians(90)

1.5707963267948966

>>> math.sin(_)
1.0

The import command is used to import a module into the script (or another module). It will be discussed in full in a separate lesson, but to continue this lesson, know that to call the functions in an imported module, the “module name + dot + function name” pattern is used – in the import command, the module extension It cannot be written.

Another example – sysone of the most important modules of Python; This module provides access to some variables used by the interpreter (at runtime) as well as the functions associated with the interpreter [ Python Documents ]

>>> import sys

>>> sys.version
'3.4.2 (default, Jan 25 2015, 20:02:16) \n[GCC 4.9.2 20141101 (Red Hat 4.9.2-1)]'

>>> sys.version_info
sys.version_info(major=3, minor=4, micro=2, releaselevel='final', serial=0)

>>> sys.platform
'linux'

>>> sys.getdefaultencoding()
'utf-8'

The command ()sys.exitalso stops the execution (here: Exit Python Interactive Mode). It is used to control errors and can also send a related message to the output (usually reporting an event that caused the program to end abruptly):

>>> import sys

>>> sys.exit("Error: Goodbye! :| ")
Error: Goodbye! :|

user>

Get tips

One of the suggested commands in the initial interactive message helpwas to enter the following text:

>>> help

Type help() for interactive help, or help(object) for help about object.

Guidance can be used in two ways, which are discussed below.

Attention

In both methods, use the Enter key (line by line) and Space (page by page) to browse long descriptions, and use the q key on the keyboard to exit the description; The end of the description is also (END)indicated by the phrase .

 

Method 1: Go to the interactive guide mode

The command ()helpis used for this purpose – by entering this command while displaying the welcome message, the line ( <<<) symbol will also <helpchange:

>>> help()

Welcome to Python 3.4's help utility!

If this is your first time using Python, you should definitely check out
the tutorial on the Internet at http://docs.python.org/3/tutorial/.

Enter the name of any module, keyword, or topic to get help on writing
Python programs and using Python modules.  To quit this help utility and
return to the interpreter, just type "quit".

To get a list of available modules, keywords, symbols, or topics, type
"modules", "keywords", "symbols", or "topics".  Each module also comes
with a one-line summary of what it does; to list the modules whose name
or summary contain a given string such as "spam", type "modules spam".

help>

Now just enter the name of the item you want to get information about; In this regard, as stated in the initial message, you can also use the following commands:

  • modules: Displays a list of names of all available modules
  • keywords: ‌ Show all Python keywords
  • symbols: ‌ Show all meaningful symbols in Python
  • topics: View a list of topics related to Python
# Python 3.x

help> keywords

Here is a list of the Python keywords.  Enter any keyword to get more help.

False               def                 if                  raise
None                del                 import              return
True                elif                in                  try
and                 else                is                  while
as                  except              lambda              with
assert              finally             nonlocal            yield
break               for                 not
class               from                or
continue            global              pass

help> def

Function definitions
********************

A function definition defines a user-defined function object (see
section *The standard type hierarchy*):

[...]

A function definition is an executable statement.  Its execution binds
the function name in the current local namespace to a function object
(a wrapper around the executable code for the function).  This
function object contains a reference to the current global namespace
:

Enter quit(or qto exit the interactive guide .

Method 2: Call the help function

This method uses a template (help(objectto get information about an object directly without entering an interactive guide – just put the name of the object in parentheses (instead of the word object):

>>> help(print)

Help on built-in function print in module builtins:

print(...)
    print(value, ..., sep=' ', end='\n', file=sys.stdout, flush=False)

    Prints the values to a stream, or to sys.stdout by default.
    Optional keyword arguments:
    file:  a file-like object (stream); defaults to the current sys.stdout.
    sep:   string inserted between values, default a space.
    end:   string appended after the last value, default a newline.
    flush: whether to forcibly flush the stream.
(END)

>>>

tip

print In 3x, Python is defined as a function, and functions in Python are an object type

This method is used with another attern. Pattern ("help("stringmeans to put the name of the item you want to get information about in parentheses enclosed in two quotation marks (“”) – this pattern has the same function as the previous method (method one) except that receiving information directly and without Login to the interactive guide. In fact, to obtain information about the case that no object (such as any of the commands symbols keywords modules and topicsor statement printin Python or 2x module name or …) is necessary for action to be:

# Python 2.x >>> help("keywords") Here is a list of the Python keywords. Enter any keyword to get more help. and elif if print as else import raise assert except in return break exec is try class finally lambda while continue for not with def from or yield del global pass >>> help("print") The "print" statement ********************* print_stmt ::= "print" ([expression ("," expression)* [","]] | ">>" expression [("," expression)+ [","]]) "print" evaluates each expression in turn and writes the resulting object to standard output (see below). If an object is not a string, it is first converted to a string using the rules for string conversions. The (resulting or original) string is then written. A space is written before each object is (converted and) written, unless the output system believes it is positioned at the beginning of a line. This is the case (1) when no characters have yet been written to standard output, (2) when the last character written to standard output is a whitespace character except "' '", or (3) when the last write operation on standard output was not a "print" statement. (In some cases it may be functional to write an empty string to standard output for this reason.) Note: Objects which act like file objects but which are not the built-in file objects often do not properly emulate this aspect of the file object's behavior, so it is best not to rely on this. : 

Call options

In addition to the Python call command on the command line, you can use a variety of options and commands. Of course, we have used them before; Like when we wanted to find the version of Python we wanted or even when we wanted to run a script. The fact is that the Python call command has a pattern, the full form of which is given below.

In Python 2x [ Python Documents ]:

python [-BdEiOQsRStuUvVWxX3?] [-c command | -m module-name | script | - ] [args] 

In Python 3x [ Python Documents ]:

python [-bBdEhiIOqsSuvVWx?] [-c command | -m module-name | script | - ] [args] 

As can be seen, this command can accept three sets of arguments:

 

First category (Options):

Contains some letters of the alphabet that come with a dash character -after the main command python; Some of these options are as follows:

  • q− (3x in Python only) – Ignores the initial message when entering Python Interactive Mode:

    user> python3 -q  >>> 2 + 2  4 
  • Q-(Python 2x only) – Used when executing a script to control the splitting operators /in it; After that, one of the words warn, new, old and warnall should be mentioned.

    • Qold: is the product of dividing two integers by one integer.
    • Qnew: The result of dividing two integers by a floating point number – like the 3x Python version.
    • Qwarn: The result of dividing two integers is an integer, with a warning message displayed for each operator.
    • Qwarnall: Similar to Qwarn, but for all split operators used in the script, only one warning message is displayed.
    python -Qnew script.py 

O-Or OO-– Basic codec optimization, which can improve the performance of the script to some extent. Using the option, in OO-addition to optimizing, also discards the documentation [3] (Docstrings) in the script:

python -O script.py 

tip

If you use these options, instead of the file pyc.(normal bytecode), a file with the extension pyo.(optimized bytecode) will be created.

  • B- – Python Interpreter refuses to save the bytecode of imported modules on disk:

    python -B script.py 
  • d- – Some additional debugging reports (if any) are displayed:

    python -d script.py 
  • i- – After executing the script, the command line enters the Python interactive mode:

    python -i script.py 
  • V-(Equal to version--) – Python version is displayed:

    python -V 
  • ?-Or h-(equal to help--) – A list of Python call options is displayed with a brief description:

    python -h 
  • S-– Module import siteis prevented:

    python -S 

    Normally the module siteis automatically imported when the Python interpreter is started and its task is to expand sys.path. For example; This module sys.pathadds the site-packages directory path .

    The site-packages directory stores third-party packages or libraries that we have installed using Python in Python.

    Whenever a module is imported, the Python interpreter looks for it within specific directories; These directories sys.pathare listed.

    For example – Python 3x on Windows :

    > python -q >>> import sys >>> sys.path ['', 'C:\\Python34', 'C:\\Windows\\SYSTEM32\\python34.zip', 'C:\\Python34\\DLLs', 'C:\\Python34\\lib', 'C:\\Python34\\lib\\site-packages'] >>> 

    For example – Python 3x in Gnolinux :

    user> python3 -qS >>> import sys >>> sys.path ['', '/usr/local/lib/python34.zip', '/usr/local/lib/python3.4/', '/usr/local/lib/python3.4/plat-linux', '/usr/local/lib/python3.4/lib-dynload'] >>> 

    The S option has been used and as you can see, there is no more news about the site-packages directory!

tip

The first directory in which the interpreter looks for the module name; The directory contains the script ''specified by the code above (because it is related to Python interactive mode) .

 

The interpreter sorts the directories in this list (from left to right).

You can pth.also sys.pathadd these directories by writing the path of your favorite directories to a text file with an extension and placing it in the site-packages directory . For example, we create the mypath.pth file (in Gnolinux operating system):

user> cd /usr/local/lib/python3.4/site-packages  user> sudo touch mypath.pth  user> sudo chmod 777 mypath.pth 

Open the mypath.pth file with a text editor and enter the list of directories you want at the bottom:

/home/saeid/Documents  /home/saeid/Documents/me 

All modules in these directories can now be imported; sys.pathNote the list :

user> python3 -q >>> import sys  >>> sys.path  ['', '/usr/local/lib/python34.zip', '/usr/local/lib/python3.4', '/usr/local/lib/python3.4/plat-linux', '/usr/local/lib/python3.4/lib-dynload', '/usr/local/lib/python3.4/site-packages', '/home/saeid/Documents', '/home/saeid/Documents/me'] >>> 

The same can be done through programming, but after the script is finished (here: exit the interactive mode) the effect disappears:

user> python3 -q >>> import sys  >>> sys.path.append('/home/saeid/Documents')  >>> sys.path.append('/home/saeid/Documents/me') 

Adds the appenddesired directory function to the bottom of the list sys.path. Of course, you can specify your desired directory using the function insertinstead of appendits first argument sys.path; This allows the directory to search for the directory sooner than later directories – the benefit of this is determined when there is a module with the same name in separate directories; In this case, the module that is seen earlier by the interpreter is imported as the desired module:

user> python3 -q >>> import sys  >>> sys.path.insert(1,'/home/saeid/Documents/me')  >>> sys.path  ['', '/home/saeid/Documents/me', '/usr/local/lib/python34.zip', '/usr/local/lib/python3.4', '/usr/local/lib/python3.4/plat-linux', '/usr/local/lib/python3.4/lib-dynload', '/usr/local/lib/python3.4/site-packages'] >>> 

You will learn a few lessons later that value sys.pathis actually an object of type listappendAnd insert also are functions  [4]  that list can be called by an object of type . At this point, just remember that positions listare numbered in an object of type zero.

The second category:

  • c command- – This template allows you to execute Python commands without entering interactive mode or creating scripts:

    user> python3 -c "import sys; print(sys.path)"  ['', '/usr/local/lib/python34.zip', '/usr/local/lib/python3.4', '/usr/local/lib/python3.4/plat-linux', '/usr/local/lib/python3.4/lib-dynload', '/usr/local/lib/python3.4/site-packages'] 

    Attention

    Commands must be enclosed in quotation marks.

    The use of semicolon ( ;) ‌ is not mandatory at the end of Python commands, but if we want to put several commands in a row, we must use it.

m module-name-– This template allows you to run a module (from the list sys.path) as a module __main__.

The most interesting example to illustrate the application of this template is the implementation of the module SimpleHTTPServer. When you need to get a web server up and running quickly and you do not want to get involved with installing and configuring Apache or other web servers; You can use this Python module. This module gives you the features of a simple web server. Of course, this module is integrated in the 3x version of Python http.server.

In Python 2x [ Python Documents ]:

user> python -m SimpleHTTPServer 8080 

In Python 3x [ Python Documents ]:

user> python3 -m http.server 8080 

Attention

Using this template, like the import time, the module extension (py) is not written.

 

You can not enter the port number, in which case port 8000 is considered the default.

But what is the meaning of module __main__?

When a module is imported (for the first time), the Python interpreter automatically executes all the code inside it. In some cases it may be a py file. Contains code that should only be executed in script mode; In this case, when the file is imported, these codes are also executed, which is not the wish of the programmer! On the other hand, in Python there is a series of special and predefined values ​​and variables such as __name__. The variable __name__refers to the module name; In script mode (executing a module directly – example command: – explained in the previous lesson) the value is equal to a special value, which can be used to control the execution of code.python script.py__name____main__

Consultants script codes to be written that their implementation depends on the implementation of the main function is usually ()maincalled in the end we can put a bet equal __name__ with  __main__ the implementation of the above, the code execution to only running the script (And not at the time of import) was assured

def main():
print("this runs only when executed directly")
if __name__ == '__main__':
main()
  • script– This template ( ) represents the same method of executing the script that was fully discussed in the previous lesson.python script.py

 

 

Third category (Arguments):

As mentioned earlier, values ​​can be passed to the script as an argument at runtime. These values sys.argvare available through script code. Note the example of the script below and its execution:

# file: Documents/script-argv-3x.py
# Python 3.x
import sys
print(sys.argv)
print(sys.argv[0])
print(sys.argv[1])
print(sys.argv[2])

High-write the script with two arguments arg_1and arg_2proceeding:

user> python3 Documents/script-argv-3x.py arg_1 arg_2 ['/home/saeid/Documents/script-argv-3x.py', 'arg_1', 'arg_2']  /home/saeid/Documents/script-argv-3x.py  arg_1  arg_2

The value is sys.argvalso an object of type list: […, Ο, Ο, Ο] – to access the elements in the list object, from a similar pattern [object [index where …, index = 0,1,2 , Is 3, is used; For example, [sys.argv[0 it sys.argvrefers to the first element in .

First member sys.argvor [sys.argv[0always contain the name of the script. Of course, except when c-used, in which case it will be equal to the value 'c-':

user> python3 -c "import sys; print(sys.argv)" 2  ['-c', '2']
[1] “Expression” is a piece of syntax that can be evaluated to a value, the phrase does not include “keywords”, and “statement” is part of a block of code that contains keywords and does something. Does. [Keywords will be reviewed in the future.]
[2] It was true that the word “object” was used instead of the word “value”; Because everything in Python is an object. For example, the number 5 is an object of class “Integers”.
[3] It is an explanation that comes at the beginning of functions, classes, and modules and is not ignored by the interpreter. [docstring to be checked in the future]
[4] The word “function” is not appropriate in the sense of an object. In the object-oriented definition, the word “method” is used instead of “function”; But at this stage, when objectivism has not yet been addressed, the word “function” was preferred.

Leave a Reply

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