Getting started with Python Language
Python is a widely used programming language. It is:
High-level: Python automates low-level operations such as memory management. It leaves the programmer with a bit less control but has many benefits including code readability and minimal code expressions.
General-purpose: Python is built to be used in all contexts and environments. An example for a non-general-purpose language is PHP: it is designed specifically as a server-side web-development scripting language. In contrast, Python can be used for server-side web-development, but also for building desktop applications.
Dynamically typed: Every variable in Python can reference any type of data. A single expression may evaluate to data of different types at different times. Due to that, the following code is possible:
Strongly typed: During program execution, you are not allowed to do anything that's incompatible with the type of data you're working with. For example, there are no hidden conversions from strings to numbers; a string made out of digits will never be treated as a number unless you convert it explicitly:
Beginner friendly :): Python's syntax and structure are very intuitive. It is high level and provides constructs intended to enable writing clear programs on both a small and large scale. Python supports multiple programming paradigms, including object-oriented, imperative and functional programming or procedural styles. It has a large, comprehensive standard library and many easy-to-install 3rd party libraries.
Its design principles are outlined in The Zen of Python.
Currently, there are two major release branches of Python which have some significant differences. Python 2.x is the legacy version though it still sees widespread use. Python 3.x makes a set of backwards-incompatible changes which aim to reduce feature duplication. For help deciding which version is best for you, see this article.
The official Python documentation is also a comprehensive and useful resource, containing documentation for all versions of Python as well as tutorials to help get you started.
There is one official implementation of the language supplied by Python.org, generally referred to as CPython, and several alternative implementations of the language on other runtime platforms. These include IronPython (running Python on the .NET platform), Jython (on the Java runtime) and PyPy (implementing Python in a subset of itself).
Python is a widely used high-level programming language for general-purpose programming, created by Guido van Rossum and first released in 1991. Python features a dynamic type system and automatic memory management and supports multiple programming paradigms, including object-oriented, imperative, functional programming, and procedural styles. It has a large and comprehensive standard library.
Two major versions of Python are currently in active use:
- Python 3.x is the current version and is under active development.
- Python 2.x is the legacy version and will receive only security updates until 2020. No new features will be implemented. Note that many projects still use Python 2, although migrating to Python 3 is getting easier.
You can download and install either version of Python here. See Python 3 vs. Python 2 for a comparison between them. In addition, some third-parties offer re-packaged versions of Python that add commonly used libraries and other features to ease setup for common use cases, such as math, data analysis or scientific use. See the list at the official site.
Verify if Python is installed
To confirm that Python was installed correctly, you can verify that by running the following command in your favorite terminal (If you are using Windows OS, you need to add path of python to the environment variable before using it in command prompt):
$ python --version
If you have Python 3 installed, and it is your default version (see Troubleshooting for more details) you should see something like this:
$ python --version Python 3.6.0
If you have Python 2 installed, and it is your default version (see Troubleshooting for more details) you should see something like this:
$ python --version Python 2.7.13
If you have installed Python 3, but
$ python --version outputs a Python 2 version, you also have Python 2 installed. This is often the case on MacOS, and many Linux distributions. Use
$ python3 instead to explicitly use the Python 3 interpreter.
Hello, World in Python using IDLE
IDLE is a simple editor for Python, that comes bundled with Python.
How to create Hello, World program in IDLE
- Open IDLE on your system of choice.
- In older versions of Windows, it can be found at
All Programsunder the Windows menu.
- In Windows 8+, search for
IDLEor find it in the apps that are present in your system.
- On Unix-based (including Mac) systems you can open it from the shell by typing
$ idle python_file.py.
- In older versions of Windows, it can be found at
- It will open a shell with options along the top.
In the shell, there is a prompt of three right angle brackets:
Now write the following code in the prompt:
>>> print("Hello, World")
>>> print("Hello, World") Hello, World
Hello World Python file
Create a new file
hello.py that contains the following line:
You can use the Python 3
Python 2 has a number of functionalities that can be optionally imported from Python 3 using the
__future__ module, as discussed here.
If using Python 2, you may also type the line below. Note that this is not valid in Python 3 and thus not recommended because it reduces cross-version code compatibility.
In your terminal, navigate to the directory containing the file
python hello.py, then hit the Enter key.
$ python hello.py Hello, World
You should see
Hello, World printed to the console.
You can also substitute
hello.py with the path to your file. For example, if you have the file in your home directory and your user is "user" on Linux, you can type
Launch an interactive Python shell
By executing (running) the
python command in your terminal, you are presented with an interactive Python shell. This is also known as the Python Interpreter or a REPL (for 'Read Evaluate Print Loop').
$ python Python 2.7.12 (default, Jun 28 2016, 08:46:01) [GCC 6.1.1 20160602] on linux Type "help", "copyright", "credits" or "license" for more information. >>> print 'Hello, World' Hello, World >>>
If you want to run Python 3 from your terminal, execute the command
$ python3 Python 3.6.0 (default, Jan 13 2017, 00:00:00) [GCC 6.1.1 20160602] on linux Type "help", "copyright", "credits" or "license" for more information. >>> print('Hello, World') Hello, World >>>
Alternatively, start the interactive prompt and load file with
python -i <file.py>.
In command line, run:
There are multiple ways to close the Python shell:
Alternatively, CTRL + D will close the shell and put you back on your terminal's command line.
If you want to cancel a command you're in the middle of typing and get back to a clean command prompt, while staying inside the Interpreter shell, use CTRL + C.
Other Online Shells
Various websites provide online access to Python shells.
Online shells may be useful for the following purposes:
- Run a small code snippet from a machine which lacks python installation(smartphones, tablets etc).
- Learn or teach basic Python.
- Solve online judge problems.
Disclaimer: documentation author(s) are not affiliated with any resources listed below.
- https://www.python.org/shell/ - The online Python shell hosted by the official Python website.
- https://ideone.com/ - Widely used on the Net to illustrate code snippet behavior.
- https://repl.it/languages/python3 - Powerful and simple online compiler, IDE and interpreter. Code, compile, and run code in Python.
- https://www.tutorialspoint.com/execute_python_online.php - Full-featured UNIX shell, and a user-friendly project explorer.
- http://rextester.com/l/python3_online_compiler - Simple and easy to use IDE which shows execution time
Run commands as a string
Python can be passed arbitrary code as a string in the shell:
This can be useful when concatenating the results of scripts together in the shell.
Shells and Beyond
Package Management - The PyPA recommended tool for installing Python packages is PIP. To install, on your command line execute
pip install <the package name>. For instance,
pip install numpy. (Note: On windows you must add pip to your PATH environment variables. To avoid this, use
python -m pip install <the package name>)
Shells - So far, we have discussed different ways to run code using Python's native interactive shell. Shells use Python's interpretive power for experimenting with code real-time. Alternative shells include IDLE - a pre-bundled GUI, IPython - known for extending the interactive experience, etc.
Programs - For long-term storage you can save content to .py files and edit/execute them as scripts or programs with external tools e.g. shell, IDEs (such as PyCharm), Jupyter notebooks, etc. Intermediate users may use these tools; however, the methods discussed here are sufficient for getting started.
Python tutor allows you to step through Python code so you can visualize how the program will flow, and helps you to understand where your program went wrong.
PEP8 defines guidelines for formatting Python code. Formatting code well is important so you can quickly read what the code does.
Python uses indentation to define control and loop constructs. This contributes to Python's readability, however, it requires the programmer to pay close attention to the use of whitespace. Thus, editor miscalibration could result in code that behaves in unexpected ways.
Python uses the colon symbol (
:) and indentation for showing where blocks of code begin and end (If you come from another language, do not confuse this with somehow being related to the ternary operator). That is, blocks in Python, such as functions, loops,
if clauses and other constructs, have no ending identifiers. All blocks start with a colon and then contain the indented lines below it.
Blocks that contain exactly one single-line statement may be put on the same line, though this form is generally not considered good style:
Attempting to do this with more than a single statement will not work:
An empty block causes an
pass (a command that does nothing) when you have a block with no content:
Spaces vs. Tabs
In short: always use 4 spaces for indentation.
Using tabs exclusively is possible but PEP 8, the style guide for Python code, states that spaces are preferred.
Python 3 disallows mixing the use of tabs and spaces for indentation. In such case a compile-time error is generated:
Inconsistent use of tabs and spaces in indentation and the program will not run.
Python 2 allows mixing tabs and spaces in indentation; this is strongly discouraged. The tab character completes the previous indentation to be a multiple of 8 spaces. Since it is common that editors are configured to show tabs as multiple of 4 spaces, this can cause subtle bugs.
Citing PEP 8:
When invoking the Python 2 command line interpreter with the
-toption, it issues warnings about code that illegally mixes tabs and spaces. When using
-ttthese warnings become errors. These options are highly recommended!
Many editors have "tabs to spaces" configuration. When configuring the editor, one should differentiate between the tab character ('\t') and the Tab key.
- The tab character should be configured to show 8 spaces, to match the language semantics - at least in cases when (accidental) mixed indentation is possible. Editors can also automatically convert the tab character to spaces.
- However, it might be helpful to configure the editor so that pressing the Tab key will insert 4 spaces, instead of inserting a tab character.
Python source code written with a mix of tabs and spaces, or with non-standard number of indentation spaces can be made pep8-conformant using autopep8. (A less powerful alternative comes with most Python installations: reindent.py)
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.
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.
To know the functionality of any function, we can use built in function
Built in modules contains extra functionalities.For example to get square root of a number we need to include
To know all the functions in a module we can assign the functions list to a variable, and then print the variable.
__doc__ is useful to provide some documentation in, say, functions
In addition to functions, documentation can also be provided in modules. So, if you have a file named
helloWorld.py like this:
You can access its docstrings like this:
- 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()
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
There are a number of collection types in Python. While types such as
str hold a single value, collection types hold multiple values.
A list can be empty:
The elements of a list are not restricted to a single data type, which makes sense given that Python is a dynamic language:
A list can contain another list as its element:
The elements of a list can be accessed via an index, or numeric representation of their position. Lists in Python are zero-indexed meaning that the first element in the list is at index 0, the second element is at index 1 and so on:
Indices can also be negative which means counting from the end of the list (
-1 being the index of the last element). So, using the list from the above example:
Lists are mutable, so you can change the values in a list:
Besides, it is possible to add and/or remove elements from a list:
Append object to end of list with
Add a new element to list at a specific index.
Remove the first occurrence of a value with
Get the index in the list of the first item whose value is x. It will show an error if there is no such item.
Count length of list
count occurrence of any item in list
Reverse the list
Remove and return item at index (defaults to the last item) with
L.pop([index]), returns the item
You can iterate over the list elements like below:
tuple is similar to a list except that it is fixed-length and immutable. So the values in the tuple cannot be changed nor the values be added to or removed from the tuple. Tuples are commonly used for small collections of values that will not need to change, such as an IP address and port. Tuples are represented with parentheses instead of square brackets:
The same indexing rules for lists also apply to tuples. Tuples can also be nested and the values can be any valid Python valid.
A tuple with only one member must be defined (note the comma) this way:
or just using
dictionary in Python is a collection of key-value pairs. The dictionary is surrounded by curly braces. Each pair is separated by a comma and the key and value are separated by a colon. Here is an example:
To get a value, refer to it by its key:
You can also get all of the keys in a dictionary and then iterate over them:
Dictionaries strongly resemble JSON syntax. The native
json module in the Python standard library can be used to convert between JSON and dictionaries.
set is a collection of elements with no repeats and without insertion order but sorted order. They are used in situations where it is only important that some things are grouped together, and not what order they were included. For large groups of data, it is much faster to check whether or not an element is in a
set than it is to do the same for a
set is very similar to defining a
Or you can build a
set using an existing
Check membership of the
You can iterate over a
set exactly like a list, but remember: the values will be in a arbitrary, implementation-defined order.
defaultdict is a dictionary with a default value for keys, so that keys for which no value has been explicitly defined can be accessed without errors.
defaultdict is especially useful when the values in the dictionary are collections (lists, dicts, etc) in the sense that it does not need to be initialized every time when a new key is used.
defaultdict will never raise a KeyError. Any key that does not exist gets the default value returned.
For example, consider the following dictionary
If we try to access a non-existent key, python returns us an error as follows
Let us try with a
defaultdict. It can be found in the collections module.
What we did here is to set a default value (Boston) in case the give key does not exist. Now populate the dict as before:
If we try to access the dict with a non-existent key, python will return us the default value i.e. Boston
and returns the created values for existing key just like a normal
Creating a module
A module is an importable file containing definitions and statements.
A module can be created by creating a
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.)
Modules can be imported by other modules.
Specific functions of a module can be imported.
Modules can be aliased.
A module can be stand-alone runnable script.
If the module is inside a directory and needs to be detected by python, the directory should contain a file named
Creating variables and assigning values
To create a variable in Python, all you need to do is specify the variable name, and then assign a value to it.
= to assign values to variables. There's no need to declare a variable in advance (or to assign a data type to it), assigning a value to a variable itself declares and initializes the variable with that value. There's no way to declare a variable without assigning it an initial value.
Variable assignment works from left to right. So the following will give you an syntax error.
You can not use python's keywords as a valid variable name. You can see the list of keyword by:
Rules for variable naming:
- Variables names must start with a letter or an underscore.
- The remainder of your variable name may consist of letters, numbers and underscores.
- Names are case sensitive.
Even though there's no need to specify a data type when declaring a variable in Python, while allocating the necessary area in memory for the variable, the Python interpreter automatically picks the most suitable built-in type for it:
Now you know the basics of assignment, let's get this subtlety about assignment in python out of the way.
When you use
= to do an assignment operation, what's on the left of
= is a name for the object on the right. Finally, what
= does is assign the reference of the object on the right to the name on the left.
So, from many assignment examples above, if we pick
pi = 3.14, then
pi is a name (not the name, since an object can have multiple names) for the object
3.14. If you don't understand something below, come back to this point and read this again! Also, you can take a look at this for a better understanding.
You can assign multiple values to multiple variables in one line. Note that there must be the same number of arguments on the right and left sides of the
The error in last example can be obviated by assigning remaining values to equal number of arbitrary variables. This dummy variable can have any name, but it is conventional to use the underscore (
_) for assigning unwanted values:
Note that the number of _ and number of remaining values must be equal. Otherwise 'too many values to unpack error' is thrown as above:
You can also assign a single value to several variables simultaneously.
When using such cascading assignment, it is important to note that all three variables
c refer to the same object in memory, an
int object with the value of 1. In other words,
c are three different names given to the same int object. Assigning a different object to one of them afterwards doesn't change the others, just as expected:
The above is also true for mutable types (like
dict, etc.) just as it is true for immutable types (like
So far so good. Things are a bit different when it comes to modifying the object (in contrast to assigning the name to a different object, which we did above) when the cascading assignment is used for mutable types. Take a look below, and you will see it first hand:
Nested lists are also valid in python. This means that a list can contain another list as an element.
Lastly, variables in Python do not have to stay the same type as which they were first defined -- you can simply use
= to assign a new value to a variable, even if that value is of a different type.
If this bothers you, think about the fact that what's on the left of
= is just a name for an object. First you call the
int object with value 2
a, then you change your mind and decide to give the name
a to a
string object, having value 'New value'. Simple, right?
bool: A boolean value of either
False. Logical operations like
not can be performed on booleans.
In Python 2.x and in Python 3.x, a boolean is also an
bool type is a subclass of the
int type and
False are its only instances:
If boolean values are used in arithmetic operations, their integer values (
False) will be used to return an integer result:
int: Integer number
Integers in Python are of arbitrary sizes.
Note: in older versions of Python, a
longtype was available and this was distinct from
int. The two have been unified.
float: Floating point number; precision depends on the implementation and system architecture, for CPython the
floatdatatype corresponds to a C double.
complex: Complex numbers
>= operators will raise a
TypeError exception when any operand is a complex number.
str: a unicode string. The type of
bytes: a byte string. The type of
str: a byte string. The type of
bytes: synonym for
unicode: a unicode string. The type of
Sequences and collections
Python differentiates between ordered sequences and unordered collections (such as
unicode) are sequences
reversed: A reversed order of
tuple: An ordered collection of
nvalues of any type (
n >= 0).
Supports indexing; immutable; hashable if all its members are hashable
list: An ordered collection of
n >= 0)
Not hashable; mutable.
set: An unordered collection of unique values. Items must be hashable.
dict: An unordered collection of unique key-value pairs; keys must be hashable.
An object is hashable if it has a hash value which never changes during its lifetime (it needs a
__hash__()method), and can be compared to other objects (it needs an
__eq__()method). Hashable objects which compare equality must have the same hash value.
In conjunction with the built-in datatypes there are a small number of built-in constants in the built-in namespace:
True: The true value of the built-in type
False: The false value of the built-in type
None: A singleton object used to signal that a value is absent.
...: used in core Python3+ anywhere and limited usage in Python2.7+ as part of array notation.
numpyand related packages use this as a 'include everything' reference in arrays.
NotImplemented: a singleton used to indicate to Python that a special method doesn't support the specific arguments, and Python will try alternatives if available.
None doesn't have any natural ordering. Using ordering comparison operators (
>) isn't supported anymore and will raise a
None is always less than any number (
None < -32 evaluates to
Testing the type of variables
In python, we can check the datatype of an object using the built-in function
In conditional statements it is possible to test the datatype with
isinstance. However, it is usually not encouraged to rely on the type of the variable.
For information on the differences between
isinstance() read: Differences between isinstance and type in Python
To test if something is of
Converting between datatypes
You can perform explicit datatype conversion.
For example, '123' is of
str type and it can be converted to integer using
Converting from a float string such as '123.456' can be done using
You can also convert sequence or collection types
Explicit string type at definition of literals
With one letter labels just in front of the quotes you can tell what type of string you want to define.
b'foo bar': results
bytesin Python 3,
strin Python 2
u'foo bar': results
strin Python 3,
unicodein Python 2
'foo bar': results
r'foo bar': results so called raw string, where escaping special characters is not necessary, everything is taken verbatim as you typed
Mutable and Immutable Data Types
An object is called mutable if it can be changed. For example, when you pass a list to some function, the list can be changed:
An object is called immutable if it cannot be changed in any way. For example, integers are immutable, since there's no way to change them:
Note that variables themselves are mutable, so we can reassign the variable
x, but this does not change the object that
x had previously pointed to. It only made
x point to a new object.
Data types whose instances are mutable are called mutable data types, and similarly for immutable objects and datatypes.
Examples of immutable Data Types:
Examples of mutable Data Types:
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:
You will receive information by entering keywords directly:
or within the utility:
which will show an explanation:
You can also request subclasses of modules:
You can use help to access the docstrings of the different modules you have imported, e.g., try the following:
and you'll get an error
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
IDLE - Python GUI
IDLE is Python’s 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
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.
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
PATHenvironment 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
PATHvariable 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.exefiles. For example, naming one version
python27to 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 -2and the latest version of Python 3 by running scripts with
This section assumes that the location of the
pythonexecutable has been added to the
If you're on Debian/Ubuntu/MacOS, open the terminal and type
pythonfor Python 2.x or
python3for Python 3.x.
which pythonto see which Python interpreter will be used.
The default Python on Arch Linux (and descendants) is Python 3, so use
python3for Python 3.x and
python2for Python 2.x.
Python 3 is sometimes bound to
python3. To use Python 2 on these systems where it is installed, you can use
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.
First, download the latest version of Python 2.7 from the official 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:
Warning: installation does not automatically modify the PATH environment variable.
Assuming that your Python installation is in C:\Python27, add this to your PATH:
Now to check if Python installation is valid write in cmd:
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:
Install Python 2.x using the MSI installer.
- Ensure Python is installed for all users.
- Optional: add Python to
PATHto make Python 2.x callable from the command-line using
Install Python 3.x using its respective installer.
- Again, ensure Python is installed for all users.
- Optional: add Python to
PATHto make Python 3.x callable from the command-line using
python. This may override Python 2.x
PATHsettings, so double-check your
PATHand ensure it's configured to your preferences.
- Make sure to install the
py launcherfor 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:
To use the corresponding version of
pip for a specific Python version, use:
The latest versions of CentOS, Fedora, Redhat Enterprise (RHEL) and Ubuntu come with Python 2.7.
To install Python 2.7 on linux manually, just do the following in terminal:
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:
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:
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 it’s not good for development. The version shipped with OS X may be out of date from the official current Python release, which is considered the stable production version. (source)
Install Python 2.7:
For Python 3.x, use the command
brew install python3 instead.
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
Installing a package is as simple as typing (in a terminal / command-prompt, not in the Python interpreter)
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:
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:
To upgrade a specific package use
Updating all outdated packages is not a standard functionality of
You can upgrade your existing pip installation by using the following commands
On Linux or macOS X:
You may need to use
sudowith pip on some Linux Systems
For more information regarding pip do read here.
String function - str() and repr()
There are two functions that can be used to obtain a readable representation of an object.
x.__repr__(): a representation of
eval will usually convert the result of this function back to the original object.
x.__str__(): a human-readable string that describes the object. This may elide some technical detail.
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.
For strings, this returns the string itself. The difference 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,
When writing a class, you can override these methods to do whatever you want:
Using the above class we can see the results:
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 different):
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.
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.
If the user types "Bob" and hits enter, the variable
name will be assigned to the string
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:
NB: It's recommended to use
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