Section 1.6: IDLE – Python GUI

IDLE is Pythons Integrated Development and Learning Environment and is an alternative to the command line. As the name may imply, IDLE is very useful for developing new code or learning python. On Windows this comes with the Python interpreter, but in other operating systems you may need to install it through your package manager.

The main purposes of IDLE are:

 Multi-window text editor with syntax highlighting, autocompletion, and smart indent

 Python shell with syntax highlighting

 Integrated debugger with stepping, persistent breakpoints, and call stack visibility

 Automatic indentation (useful for beginners learning about Python’s indentation)

 Saving the Python program as .py files and run them and edit them later at any them using IDLE.

In IDLE, hit F5 or run Python Shell to launch an interpreter. Using IDLE can be a better learning experience for new users because code is interpreted as the user writes.

Note that there are lots of alternatives, see for example this discussion or this list.

Troubleshooting

 Windows

If you’re on Windows, the default command is python. If you receive a “‘python’ is not recognized” error, the most likely cause is that Python’s location is not in your system’s PATH environment variable. This can be accessed by right-clicking on ‘My Computer’ and selecting ‘Properties’ or by navigating to ‘System’ through ‘Control Panel’. Click on ‘Advanced system settings’ and then ‘Environment Variables…’. Edit the PATH variable to include the directory of your Python installation, as well as the Script folder (usually C:\Python27;C:\Python27\Scripts). This requires administrative privileges and may require a restart.

When using multiple versions of Python on the same machine, a possible solution is to rename one of the python.exe files. For example, naming one version python27.exe would cause python27 to become the Python command for that version.

You can also use the Python Launcher for Windows, which is available through the installer and comes by default. It allows you to select the version of Python to run by using py -[x.y] instead of python[x.y]. You can use the latest version of Python 2 by running scripts with py 2 and the latest version of Python 3 by running scripts with py 3.

 Debian/Ubuntu/MacOS

This section assumes that the location of the python executable has been added to the PATH environment variable.

If you’re on Debian/Ubuntu/MacOS, open the terminal and type python for Python 2.x or python3 for Python 3.x.

Type which python to see which Python interpreter will be used.

 Arch Linux

The default Python on Arch Linux (and descendants) is Python 3, so use python or python3 for Python 3.x and python2for Python 2.x.

 Other systems

Python 3 is sometimes bound to python instead of python3. To use Python 2 on these systems where it is installed, you can use python2.

Section 1.7: User Input

Interactive input

To get input from the user, use the input function (note: in Python 2.x, the function is called raw_input instead, although Python 2.x has its own version of input that is completely dierent):

Python 2.x Version ≥ 2.3

name raw_input(“What is your name? “)

# Out: What is your name? _

Security Remark Do not use input() in Python2 – the entered text will be evaluated as if it were a Python expression (equivalent to eval(input()) in Python3), which might easily become a vulnerability. See this article for further information on the risks of using this function.

Python 3.x Version ≥ 3.0

name input(“What is your name? “)

# Out: What is your name? _

The remainder of this example will be using Python 3 syntax.

The function takes a string argument, which displays it as a prompt and returns a string. The above code provides a prompt, waiting for the user to input.

name input(“What is your name? “)

# Out: What is your name?

If the user types “Bob” and hits enter, the variable name will be assigned to the string “Bob”:

name input(“What is your name? “)

#Out: What is your name? Bobprint(name)

#Out: Bob

Note that the input is always of type str, which is important if you want the user to enter numbers. Therefore, you need to convert the str before trying to use it as a number:

input(“Write a number:”)

#Out: Write a number: 10 x / 2

#Out: TypeError: unsupported operand type(s) for /: ‘str’ and ‘int’ float(x) / 2

#Out: 5.0

NB: It’s recommended to use try/except blocks to catch exceptions when dealing with user inputs. For instance, if your code wants to cast a raw_input into an int, and what the user writes is uncastable, it raises a ValueError.

Section 1.8: Built in Modules and Functions

A module is a file containing Python definitions and statements. Function is a piece of code which execute some logic.

>>> pow(2,3)

#8

 

 

To check the built in function in python we can use dir(). If called without an argument, return the names in the current scope. Else, return an alphabetized list of names comprising (some of) the attribute of the given object, and of attributes reachable from it.

>>>dir(__builtins__)

[

‘ArithmeticError’‘AssertionError’‘AttributeError’‘BaseException’‘BufferError’‘BytesWarning’‘DeprecationWarning’‘EOFError’‘Ellipsis’‘EnvironmentError’‘Exception’‘False’‘FloatingPointError’‘FutureWarning’‘GeneratorExit’‘IOError’‘ImportError’‘ImportWarning’‘IndentationError’‘IndexError’‘KeyError’‘KeyboardInterrupt’‘LookupError’‘MemoryError’‘NameError’‘None’‘NotImplemented’‘NotImplementedError’‘OSError’‘OverflowError’‘PendingDeprecationWarning’‘ReferenceError’‘RuntimeError’‘RuntimeWarning’‘StandardError’‘StopIteration’‘SyntaxError’‘SyntaxWarning’‘SystemError’‘SystemExit’‘TabError’,

‘True’‘TypeError’‘UnboundLocalError’‘UnicodeDecodeError’‘UnicodeEncodeError’‘UnicodeError’‘UnicodeTranslateError’‘UnicodeWarning’‘UserWarning’‘ValueError’‘Warning’‘ZeroDivisionError’‘__debug__’‘__doc__’,

‘__import__’‘__name__’‘__package__’‘abs’‘all’‘any’‘apply’‘basestring’‘bin’‘bool’‘buffer’‘bytearray’‘bytes’‘callable’‘chr’‘classmethod’‘cmp’‘coerce’‘compile’‘complex’‘copyright’‘credits’‘delattr’‘dict’‘dir’‘divmod’‘enumerate’‘eval’‘execfile’‘exit’‘file’‘filter’‘float’‘format’‘frozenset’‘getattr’‘globals’‘hasattr’‘hash’‘help’‘hex’,

‘id’‘input’‘int’‘intern’‘isinstance’‘issubclass’‘iter’‘len’‘license’‘list’‘locals’‘long’‘map’‘max’‘memoryview’‘min’‘next’‘object’‘oct’‘open’‘ord’,

‘pow’‘print’‘property’‘quit’‘range’‘raw_input’‘reduce’‘reload’‘repr’‘reversed’’round’‘set’‘setattr’‘slice’‘sorted’‘staticmethod’‘str’,

‘sum’‘super’‘tuple’‘type’‘unichr’‘unicode’‘vars’‘xrange’‘zip’

]

To know the functionality of any function, we can use built in function help .

>>>help(max)

Help on built-in function max in module __builtin__max(…)

max(iterable[key=func]) –> value

max(abc…[key=func]) –> value

With a single iterable argumentreturn its largest item. With two or more argumentsreturn the largest argument.

Built in modules contains extra functionalities. For example to get square root of a number we need to include math module.

>>>import math

>>>math.sqrt(16# 4.0

To know all the functions in a module we can assign the functions list to a variable, and then print the variable.

>>>import math

>>>dir(math)

[‘__doc__’‘__name__’‘__package__’‘acos’‘acosh’,

‘asin’‘asinh’‘atan’‘atan2’‘atanh’‘ceil’‘copysign’‘cos’‘cosh’‘degrees’‘e’‘erf’‘erfc’‘exp’‘expm1’‘fabs’‘factorial’‘floor’‘fmod’‘frexp’‘fsum’‘gamma’‘hypot’‘isinf’‘isnan’‘ldexp’‘lgamma’‘log’‘log10’‘log1p’‘modf’‘pi’‘pow’‘radians’‘sin’‘sinh’‘sqrt’‘tan’‘tanh’‘trunc’]

it seems __doc__ is useful to provide some documentation in, say, functions

 

>>>math.__doc__

‘This module is always available. It provides access to the\nmathematical functions defined by the C standard.’

In addition to functions, documentation can also be provided in modules. So, if you have a file namedhelloWorld.py like this:

“””This is the module docstring.”””

def sayHello():

“””This is the function docstring.””” return ‘Hello World’

You can access its docstrings like this:

>>>import helloWorld

>>>helloWorld.__doc__

‘This is the module docstring.’

>>>helloWorld.sayHello.__doc__ ‘This is the function docstring.’

 For any user defined type, its attributes, its class’s attributes, and recursively the attributes of its class’s base classes can be retrieved using dir()

>>>class MyClassObject(object):

… pass

>>>dir(MyClassObject)

[‘__class__’‘__delattr__’‘__dict__’‘__doc__’‘__format__’‘__getattribute__’‘__hash__’‘__init__’‘__module__’‘__new__’‘__reduce__’‘__reduce_ex__’‘__repr__’‘__setattr__’‘__sizeof__’‘__str__’‘__subclasshook__’‘__weakref__’]

Any data type can be simply converted to string using a builtin function called str. This function is called by default when a data type is passed to print

>>> str(123)

# “123”

 

 

Section 1.9: Creating a module

A module is an importable file containing definitions and statements.

A module can be created by creating a .py file.

# hello.py

def say_hello(): print(“Hello!”)

Functions in a module can be used by importing the module.

For modules that you have made, they will need to be in the same directory as the file that you are importing them into. (However, you can also put them into the Python lib directory with the pre-included modules, but should be avoided if possible.)

$ python

>>>import hello

>>>hello.say_hello()

=> “Hello!”

Modules can be imported by other modules.

#greet.py import hello hello.say_hello()

Specific functions of a module can be imported.

# greet.py

from hello import say_hello say_hello()

Modules can be aliased.

# greet.py

import hello as ai ai.say_hello()

A module can be stand-alone runnable script.

# run_hello.py

if __name__ == ‘__main__’from hello import say_hello say_hello()

Run it!

$python run_hello.py => “Hello!”

If the module is inside a directory and needs to be detected by python, the directory should contain a file named__init__.py.

Section 1.10: Installation of Python 2.7.x and 3.x

Note: Following instructions are written for Python 2.7 (unless specified): instructions for Python 3.x are similar.

Windows

First, download the latest version of Python 2.7 from the ocial Website (https://www.python.org/downloads/). Version is provided as an MSI package. To install it manually, just double-click the file.

By default, Python installs to a directory:

C:\Python27\

Warning: installation does not automatically modify the PATH environment variable.

Assuming that your Python installation is in C:\Python27, add this to your PATH:

 

C:\Python27\;C:\Python27\Scripts\

Now to check if Python installation is valid write in cmd:

python –version

Python 2.x and 3.x Side-By-Side

To install and use both Python 2.x and 3.x side-by-side on a Windows machine:

1. Install Python 2.x using the MSI installer.

 Ensure Python is installed for all users.

 Optional: add Python to PATH to make Python 2.x callable from the command-line using python.

2. Install Python 3.x using its respective installer.

 Again, ensure Python is installed for all users.

 Optional: add Python to PATH to make Python 3.x callable from the command-line using python. This may override Python 2.x PATH settings, so double-check your PATH and ensure it’s configured to your preferences.

 Make sure to install the py launcher for all users.

Python 3 will install the Python launcher which can be used to launch Python 2.x and Python 3.x interchangeably from the command-line:

P:\>py –3

Python 3.6.1 (v3.6.1:69c0db5Mar 21 201717:54:52) [MSC v.1900 32 bit (Intel)] on win32 Type “help”“copyright”“credits” or “license” for more information.

>>>

C:\>py –2

Python 2.7.13 (v2.7.13:a06454b1afa1Dec 17 201620:42:59) [MSC v.1500 32 Intel)] on win32 Type “help”“copyright”“credits” or “license” for more information.

>>>

To use the corresponding version of pip for a specific Python version, use:

C:\>py –3 -m pip -V

pip 9.0.1 from C:\Python36\lib\site-packages (python 3.6)

C:\>py –2 -m pip -V

pip 9.0.1 from C:\Python27\lib\site-packages (python 2.7)

Linux

The latest versions of CentOS, Fedora, Red Hat Enterprise (RHEL) and Ubuntu come with Python 2.7. To install Python 2.7 on linux manually, just do the following in terminal:

wget –no-check-certificate https://www.python.org/ftp/python/2.7.X/Python-2.7.X.tgz tar -xzf Python-2.7.X.tgz

cd Python-2.7.X

./configure make

sudo make install

Also add the path of new python in PATH environment variable. If new python is in /root/python-2.7.X then run export PATH $PATH:/root/python-2.7.X

Now to check if Python installation is valid write in terminal:

python –version

Ubuntu (From Source)

If you need Python 3.6 you can install it from source as shown below (Ubuntu 16.10 and 17.04 have 3.6 version in the universal repository). Below steps have to be followed for Ubuntu 16.04 and lower versions:

sudo apt install build-essential checkinstall

sudo apt install libreadline-gplv2-dev libncursesw5-dev libssl-dev libsqlite3-dev tk-dev libgdbm- dev libc6-dev libbz2-dev

wget https://www.python.org/ftp/python/3.6.1/Python-3.6.1.tar.xz tar xvf Python-3.6.1.tar.xz

cd Python-3.6.1/

./configure –enable-optimizations sudo make altinstall

macOS

As we speak, macOS comes installed with Python 2.7.10, but this version is outdated and slightly modified from the regular Python.

The version of Python that ships with OS X is great for learning but its not good for development. The version shipped with OS X may be out of date from the ocial current Python release, which is considered the stable production version. (source)

Install Homebrew:

/usr/bin/ruby e “$(curl -fsSL https://raw.githubusercontent.com/Homebrew/install/master/install)”

Install Python 2.7:

brew install python

For Python 3.x, use the command brew install python3 instead.

Section 1.11: String function – str() and repr()

There are two functions that can be used to obtain a readable representation of an object.

repr(x) calls x.__repr__(): a representation of xeval will usually convert the result of this function back to the original object.

str(x) calls x.__str__(): a human-readable string that describes the object. This may elide some technical detail.

repr()

For many types, this function makes an attempt to return a string that would yield an object with the same value when passed to eval(). Otherwise, the representation is a string enclosed in angle brackets that contains the name of the type of the object along with additional information. This often includes the name and address of the object.

str()

For strings, this returns the string itself. The dierence between this and repr(object) is that str(object) does not always attempt to return a string that is acceptable to eval(). Rather, its goal is to return a printable or ‘human readable’ string. If no argument is given, this returns the empty string, .

Example 1:

“””w’o”w”””

repr(s) # Output: ‘\’w\\\’o”w\”

str(s) # Output: ‘w\’o”w’

eval(str(s)) == # Gives a SyntaxError eval(repr(s)) == # Output: True

Example 2:

import datetime

today datetime.datetime.now()

str(today) # Output: ‘2016-09-15 06:58:46.915000’

repr(today) # Output: ‘datetime.datetime(2016, 9, 15, 6, 58, 46, 915000)’

When writing a class, you can override these methods to do whatever you want:

class Represent(object):

def __init__(selfxy): self.xself.y xy

def __repr__(self):

return “Represent(x={},y=\”{}\”)”.format(self.xself.y)

def __str__(self):

return “Representing x as {} and y as {}”.format(self.xself.y)

Using the above class we can see the results:

Represent(1“Hopper”print(r) # prints __str__

print(r.__repr__# prints __repr__: ‘<bound method Represent.__repr__ of Represent(x=1,y=”Hopper”)>’

rep r.__repr__() # sets the execution of __repr__ to a new variable print(rep) # prints ‘Represent(x=1,y=”Hopper”)’

r2 eval(rep) # evaluates rep

print(r2) # prints __str__ from new object

print(r2 == r) # prints ‘False’ because they are different objects

Section 1.12: Installing external modules using pip

pip is your friend when you need to install any package from the plethora of choices available at the python package index (PyPI). pip is already installed if you’re using Python 2 >= 2.7.9 or Python 3 >= 3.4 downloaded from python.org. For computers running Linux or another *nix with a native package manager, pip must often be manually installed.

On instances with both Python 2 and Python 3 installed, pip often refers to Python 2 and pip3 to Python 3. Using pip will only install packages for Python 2 and pip3 will only install packages for Python 3.

Finding / installing a package

Searching for a package is as simple as typing

$ pip search <query>

# Searches for packages whose name or summary contains <query>

Installing a package is as simple as typing (in a terminal / command-prompt, not in the Python interpreter)

$

pip install [package_name]

# latest version of the package

$

pip

install [package_name]==x.x.x

# specific version of the package

$

pip

install ‘[package_name]>=x.x.x’

# minimum version of the package

 

 

 

 

where x.x.x is the version number of the package you want to install.

When your server is behind proxy, you can install package by using below command:

$pip –proxy http://<server address>:<portinstall

Upgrading installed packages

When new versions of installed packages appear they are not automatically installed to your system. To get an overview of which of your installed packages have become outdated, run:

$ pip list –outdated

To upgrade a specific package use

$ pip install [package_name] –upgrade

Updating all outdated packages is not a standard functionality of pip.

Upgrading pip

You can upgrade your existing pip installation by using the following commands

 On Linux or macOS X:

$ pip install -U pip

You may need to use sudo with pip on some Linux Systems

 On Windows:

py -m pip install -U pip

or

python -m pip install -U pip

For more information regarding pip do read here.

Section 1.13: Help Utility

Python has several functions built into the interpreter. If you want to get information of keywords, built-in functions, modules or topics open a Python console and enter:

>>>help()

You will receive information by entering keywords directly:

>>>help(help)

or within the utility:

helphelp

which will show an explanation:

Help on _Helper in module _sitebuiltins object:

class _Helper(builtins.object)

|Define the builtin ‘help’.

|This is a wrapper around pydoc.help that provides a helpful message

|when ‘help’ is typed at the Python interactive prompt.

|Calling help() at the Python prompt starts an interactive help session.

|Calling help(thing) prints help for the python object ‘thing’.

|Methods defined here:

|__call__(self, *args, **kwds)

|__repr__(self)

|———————————————————————-

|Data descriptors defined here:

|__dict__

|dictionary for instance variables (if defined)

|__weakref__

|list of weak references to the object (if defined)

You can also request subclasses of modules:

help(pymysql.connections)

You can use help to access the docstrings of the dierent modules you have imported, e.g., try the following:

>>>help(math)

and you’ll get an error

>>> import math

>>>help(math)

And now you will get a list of the available methods in the module, but only AFTER you have imported it. Close the helper with quit