Most Windows and Mac computers come with Python pre-installed. You can check that via a Command Line search (Just run the Command python
). The particular appeal of Python is that you can write a program in any text editor, save it in .py format and then run via a Command-line. But as you learn to write more complex code or venture into data science, you might want to switch to an IDE or IDLE.
IDLE (Integrated Development and Learning Environment) comes installed along with all python installations. It makes use of Text highlight, where it make use of different colours to identify variables, function, commands, etc. This gives an advantage to the developer in findings errors. Python IDLE has a build Automator of some kind that compiles the code, and builds an executable program by adding in any necessary libraries, some of which you may not even be aware of. Those same tools make it easier to organize and include any optional libraries, or ones you’ve created yourself.
Shell is the default mode of operation for Python IDLE. In essence, it’s a simple loop that performs that following four steps:
Note: Python shell is a great place to test various small code snippets. We will be mainly using it. If a code snippet is starting with >>>
then it being executed in pyton shell.
Everything in python is implemented as an "object". Every "object" has a specific "Data type". The 4 most-used datatypes are as follows:
Integers (int) — an integer number to represent an object such as “number 3”.
<class 'int'>
-2, -1, 0, 1, 2, 3, 4, 5
<class 'float'>
-1.25, -1.0, -0.5, 0.0, 0.5, 1.0, 1.25
Encode a sequence of characters using a string. For example, the word “hello”. In Python 3, strings are immutable. If you already defined one, you cannot change it later on.
While you can modify a string with commands such as replace()
or join()
, they will create a copy of a string and apply modification to it, rather than rewrite the original one.
<class 'str'>
'Yo!', 'Hey', "what's up?", "Ola!!!"
A list is a sequence of objects enclosed within square brackets []
. It is a mutable sequence. It can be defined as a list of objects, or a list of lists. For example, the list of numbers 1, 2, 3, 4, 5.
<class 'list'>
[-2, 0, 1, 3.1415, 'Hello, world!']
NOTE: There are more datatypes like sets, Dictionaries, complex numbers, tuples, boolean.
Operator | Operation | Example |
---|---|---|
+ |
Addition | 2 + 3 = 5 |
- |
Subtraction | 2 - 3 = -1 |
* |
Multiplication | 2 * 3 = 6 |
/ |
Division | 3 / 2 = 1.5 |
// |
Floor Division | 5 // 2 = 2 |
% |
Modulus | 5 % 2 = 1 |
** |
Exponent | 2 ** 3 = 8 |
Operator | Operation | Example |
---|---|---|
== |
is equal to |
|
!= |
is not equal to |
|
>= |
Greater than or equal to |
|
> |
greater than |
|
<= |
less than or equal to |
|
< |
less than |
|
Boolean operations are used to combine logical expressions. For example, True and False
is False, True or False
is True, and not True
is False.
The following table shows the logical operators and their corresponding boolean values:
A | not A |
---|---|
True |
False |
False |
True |
A | B | A and B | A or B | A xor B |
---|---|---|---|---|
True |
True |
True |
True |
False |
True |
False |
False |
True |
True |
False |
True |
False |
True |
True |
False |
False |
False |
False |
False |
NOTE: nand
is equivalent to not and. nor
is equivalent to not or
and xnor
is equivalent to not xor
.
Python has a built-in function to create a string. It is called str()
and it takes in any object and returns a string. For example, the following code creates a string from a number:
>>> str(3)
'3'
>>> str(3.1415)
'3.1415'
>>> str('Hello, world!')
'Hello, world!'
You can create a string in three ways using single, double or triple quotes. Here’s an example of every option:
>>> string = "Let’s Learn Python!"
>>> another_string = 'It is very simple. You can do it!'
>>> long_string = '''Yes, you can even have a long string multi-line string.
It covers more than one line
and is beautiful!'''
NOTE: You can choose any one of the above but it is recommended to be consistent with their use within a program.
As the next step, you can use the print()
function to output your string in the console window. This lets you review your code and ensure that all functions well.
>>> print("Hello, world!")
'Hello, world!'
You can concatenate strings using the +
operator. For example, the following code concatenates two strings:
>>> string_1 = "Hello"
>>> string_2 = "World!"
>>> string_1 + " " + string_2
"Hello World!"
NOTE: You can’t apply + operator to two different data types e.g. string +
integer. If you try to do that, you’ll get the following Python error:
TypeError: can only concatenate str (not "int") to str
Say you have to add the same string multiple time. You would do it something like this:
>>> string_1 = "Hello"
>>> string_2 = string_1 + string_1 + string_1
>>> string_2
'HelloHelloHello'
You can replicate a string using the *
operator. For example, the following code replicates the string 'Hello'
three times:
>>> string_1 = "Hello"
>>> string_2 = 'Hello' * 3
>>> string_2
'HelloHelloHello'
You can store a string in a variable using the =
operator which is also called the assignment operator (Because it assigns the value). Strings incorporate data. So you can "pack" them inside a variable. Doing so makes it easier to work with complex Python programs. For example, the following code stores the string 'Hello'
in the variable string
:
string = 'Hello'
In short:
string
is the variable name.=
is the assignment operator which assigns the value.'Hello'
is the value being assigned.Now you can print the value in the variable like this:
>>> print(string)
'Hello'
See? You save yourself the effort of typing the whole string again and again by storing it in a variable.
Say you have to do this:
>>> name = 'John Smith'
>>> age = 900
>>> "Hello " + name + ", you are " + str(age) + " years old."
'Hello John Smith, You are 900 years old.'
Now, wouldn't you want a better and more efficient way to write the above thing? Presenting to you String Formatting. You can format a string like this:
>>> name = 'John Smith'
>>> age = 900
>>> "Hello %s, You are %d years old." % (name, age) # % formatting operator
'Hello John Smith, You are 900 years old.'
>>> "Hello {}, you are {} years old.".format(name, age) # format method
'Hello John Smith, you are 900 years old.'
>>> f"Hello {name}, you are {age} years old." # f-string-format method
'Hello John Smith, you are 900 years old.'
Formatting is a better alternative to concatenating strings. It is more readable and it is easier to read and understand. It is also MORE EFFICIENT. The f-strings method is the python 3 version of the .format()
method and is preferred due to increased code readability.
You can name a variable anything as long as it obeys the following rules:
For example, the following code is valid:
>>> variable = 'Hello, world!' # valid variable name
>>> variable_name = 'Hello' # valid variable name
>>> _variable_name = 'Hello' # valid variable name
>>> __variable__ = 'Hello' # valid variable name
>>> variable_name1 = 'Hello' # valid variable name
>>> 1variable_name = 'Hello' # invalid variable name
SyntaxError: invalid syntax
>>> variable-name = 'Hello' # invalid variable name
SyntaxError: invalid syntax
>>> variable name = 'Hello' # invalid variable name
SyntaxError: invalid syntax
Function | Description |
---|---|
print(value, ..., sep=' ', end='\n', file=sys.stdout, flush=False) |
Prints the values to a stream, or to sys.stdout by default. |
abs(number) |
Returns the absolute value of the number. |
min(iterable) |
With a single iterable argument, return its smallest item. |
max(iterable) |
With a single iterable argument, return its biggest item. |
sum(iterable, start=0) |
Return the sum of a 'start' value (default: 0) plus an iterable of numbers. |
pow(x, y, z=None) |
Equivalent to x ** y (with two arguments) or x ** y % z (with three arguments). |
round(number, ndigits=None) |
Round a number to a given precision in decimal digits. |
range(start=0, stop, step=1) |
Return an object that produces a sequence of integers from start (inclusive, defaults to 0) to stop (exclusive) by step (defaults to 1). |
slice(start=0, stop, step=1) |
Create a slice object. This is used for extended slicing. |
type(object) |
returns the class of the object. |
reversed(sequence) |
Return a reverse iterator over the values of the given sequence. |
property(fget=None, fset=None, fdel=None, doc-None) |
Property attribute. |
id(object) |
Returns the memory location of an object. Read more. |
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(object) prints help for the python object. |
hash(object) |
Return the hash value for the given object. Two objects that compare equal must also have the same hash value, but the reverse is not necessarily true. |
bin(number) |
Returns the binary (base 2) representation of an integer. |
oct(number) |
Returns the octal (base 8) representation of an integer. |
int(number, base=10) |
Returns the decimal (base 10) representation of a number (belonging to base 10 by default). |
float(number) |
Returns the floating point representation of a number. |
hex(number) |
Returns the hexadecimal (base 16) representation of an integer. |
str(object) |
Returns the string representation of an object. |
list(iterable=()) |
Built-in mutable sequence. If no argument is given, the constructor creates a new empty list. The argument must be an iterable if specified. |
tuple(iterable=()) |
Built-in immutable sequence. If no argument is given, the constructor returns an empty tuple. If iterable is specified the tuple is initialized from iterable's items. |
dict(iterable=()) |
Built-in immutable sequence to store data values in key: value pairs. A dictionary is a collection which is ordered, changeable and do not allow duplicatation (of keys). |
set(iterable=()) |
Builds an unordered collection of unique elements. |
frozenset(iterable=()) |
Build an immutable unordered collection of unique elements. Basically sets but immutable. |
bool(object) |
Returns the boolean value of an object. |
eval(source, globals=None, locals=None) |
Evaluate the given source in the context of globals and locals. |
exec(source, globals=None, locals=None) |
Execute the source in the context of globals and locals. The source may be a string or a code object. |
compile(source, filename, mode, flags=0, dont_inherit=False, optimize=-1, *, _feature_version=-1) |
Compile the source string (or bytes, if filename is present) into a code object that can be executed by exec() or eval() . |
globals() |
Return the dictionary that is used for the global namespace. |
locals() |
Return the dictionary that is used for the local namespace. |
vars(object=None) |
Return the __dict__ attribute of an object or a dictionary corresponding to the current local and global namespace. If no object is given, return a dictionary corresponding to the current global namespace. |
dir([object]) |
Return an alphabetized list of names in the current local and global namespace. If the optional argument, object, is given, it should be a module or a class, and only names defined by object will be listed. The list of names is sorted alphabetically, and does not include private names (names starting with "_ "). |
filter(function or None, iterable) |
Return an iterator yielding those items of iterable for which function(item) is true. If function is None , return the items that are true. |
map(function, iterable, ...) |
Return an iterator that applies function to each item of iterable, yielding the results. If more than one iterable is given, function must take as many arguments as there are iterables. |
We can define our own functions in Python using the def
keyword. The syntax is:
def function_name(parameter_list):
"""Function documentation string."""
# Above is optional but considered good practice.
# Code block...
return value
The def
keyword is followed by the function name, followed by parentheses containing the parameter list. The parameter list is optional, but if present, must be a list of comma-separated parameter names. The parameter list is followed by a colon and an indented block containing the function body. The indented block must begin with a docstring describing the function.
The function body consists of a sequence of statements. The statements are executed in the order in which they appear. Statements may be nested, and the indentation of the statements is significant. The return statement is used to return a value from a function. It is also possible to return a value from a function by assigning a value to the return
variable. The return statement can be used in the global scope, in a function, or in a generator. The return statement is optional, and if it is not present, the function will return None
. The returned values is what is started in variables or passed on.
The return
statement can be used in the global scope, in a function, or in a generator. The return statement is optional, and if it is not present, the function will return None
.
Now let us define some functions:
def print_text(text):
"""Print the given text."""
print(text)
The print_text
function takes one parameter, text
, and prints it to the screen. Since the return
statement is not used, the function returns None
.