Skip to main content

Command Palette

Search for a command to run...

SIMPLIFIED introduction to Python

Published
12 min read
C

I love coding I am a data scientist

What is Python?

Python is a high-level, general-purpose programming language. Its design philosophy emphasizes code readability with the use of significant indentation.

It is used for:

  • web development (server-side).

  • software development.

  • mathematics.

  • system scripting.

Python Install

If you find that you do not have Python installed on your computer, then you can download it for free from the following website: https://www.python.org/

What can python do?

  1. It can be used on a server to create web applications.

  2. It can be used alongside software to create workflows.

  3. Python can connect to database systems. It can also read and modify files.

  4. Python can be used to handle big data and perform complex mathematics.

  5. Python can be used for rapid prototyping.

Why Python?

-it has a simplified syntax and is not complicated, which gives more emphasis on natural language.

-It works on different platforms ie windows

-It has a syntax that allows developers to write programs with fewer lines than some other programming languages.

-It has a Mature and Supportive Python Community

**-**Big data, Machine Learning and Cloud Computing

Python Syntax compared to other programming languages

Python was designed for readability and has some similarities to the English language with influence from mathematics.

Python uses new lines to complete a command, as opposed to other programming languages which often use semicolons or parentheses.

Python relies on indentation, using whitespace, to define scope; such as the scope of loops, functions and classes. Other programming languages often use curly brackets for this purpose.

Python Indentation

Indentation refers to the spaces at the beginning of a code line.

Whereas in other programming languages, the indentation in code is for readability only, the indentation in Python is very important.

Python uses indentation to indicate a block of code.

Example

if 5 > 2:
print("Five is greater than two!")

Python Variables

In Python, variables are created when you assign a value to them:

Comments

Comments can be used to explain Python code.

Comments can be used to make the code more readable.

Comments can be used to prevent execution when testing code.

Example

Comments in Python:

#This is a comment.
print("Hello, World!")

Creating a Comment

Comments start with a # and Python will ignore them

Comments can be placed at the end of a line, and Python will ignore the rest of the line

Multiline Comments

Python does not have a syntax for multiline comments.

To add a multiline comment you could insert a # for each line

Python Variables

Variables

Variables are containers for storing data values.

Creating Variables

Python has no command for declaring a variable.

A variable is created the moment you first assign a value to it

Example

x = 5
y = "John"
print(x)
print(y)

Single or Double Quotes

String variables can be declared either by using single or double quotes

Case-Sensitive

Variable names are case-sensitive

Python Data Types

Built-in Data Types

In programming, a data type is an important concept.

Variables can store data of different types, and different types can do different things.

Python has the following data types built-in by default, in these categories:

Text Type:

str

Numeric Types:

int, float, complex

Sequence Types:

list, tuple, range

Mapping Type:

dict

Set Types:

set, frozenset

Boolean Type:

bool

Binary Types:

bytes, bytearray, memoryview

None Type:

NoneType

Getting the Data Type

You can get the data type of any object by using the type() functionSetting the Data Type

In Python, the data type is set when you assign a value to a variable:

Setting the Specific Data Type

If you want to specify the data type, you can use the following constructor functions:

Python Numbers

There are three numeric types in Python:

  • int

  • float

  • complex

Variables of numeric types are created when you assign a value to them

Int

Int, or integer, is a whole number, positive or negative, without decimals, of unlimited length.

Float

Float, or "floating point number" is a number, positive or negative, containing one or more decimals.

Python Strings

Strings in python are surrounded by either single quotation marks or double quotation marks.

'hello' is the same as "hello".

You can display a string literal with the print() function

Assign String to a Variable

Assigning a string to a variable is done with the variable name followed by an equal sign and the string

Multiline Strings

You can assign a multiline string to a variable by using three quotes:

Example

You can use three double quotes:

a = """Lorem ipsum dolor sit amet,
consectetur adipiscing elit,
sed do eiusmod tempor incididunt
ut labore et dolore magna aliqua."""
print(a)

Strings are Arrays

Like many other popular programming languages, strings in Python are arrays of bytes representing unicode characters.

However, Python does not have a character data type, a single character is simply a string with a length of 1.

Square brackets can be used to access elements of the string.

Looping Through a String

Since strings are arrays, we can loop through the characters in a string, with a for loop.

Python Booleans

Booleans represent one of two values: True or False.


Boolean Values

In programming, you often need to know if an expression is True or False.

You can evaluate any expression in Python, and get one of two answers, True or False.

When you compare two values, the expression is evaluated and Python returns the Boolean answer

Evaluate Values and Variables

The bool() function allows you to evaluate any value, and give you True or False in return

Most Values are True

Almost any value is evaluated to True if it has some sort of content.

Any string is True, except for empty strings.

Any number is True, except 0.

Any list, tuple, set, or dictionary are True, except for empty ones

Python Operators

Operators are used to performing operations on variables and values.

In the example below, we use the + operator to add together two values

Python divides the operators in the following groups:

  • Arithmetic operators

  • Assignment operators

  • Comparison operators

  • Logical operators

  • Identity operators

  • Membership operators

  • Bitwise operators

Python Arithmetic Operators

Arithmetic operators are used with numeric values to perform common mathematical operations:

OperatorNameExample
+Additionx + y
-Subtractionx - y
*Multiplicationx * y
/Divisionx / y
%Modulusx % y
**Exponentiationx ** y
//Floor divisionx // y

Python Assignment Operators

Assignment operators are used to assigning values to variables:

OperatorExampleSame As
\=x = 5x = 5
+=x += 3x+=3
-=x -= 3x = x - 3
*=x *= 3x = x * 3
/=x /= 3x = x / 3
%=x %= 3x = x % 3
//=x //= 3x = x // 3
**=x **= 3x = x ** 3
&=x &= 3x = x & 3
=x= 3x = x3
^=x ^= 3
\>>=x >>= 3x = x >> 3
<<=x <<= 3x = x << 3

ADVERTISEMENT


Python Comparison Operators

Comparison operators are used to compareing two values:

OperatorNameExampleTry it
\==Equalx == yTry it »
!=Not equalx != yTry it »
\>Greater thanx > yTry it »
<Less thanx < yTry it »
\>=Greater than or equal tox >= yTry it »
<=Less than or equal tox <= yTry it »

Python Logical Operators

Logical operators are used to combine conditional statements:

OperatorDescriptionExample
andReturns True if both statements are truex < 5 and x < 10
orReturns True if one of the statements is truex < 5 or x < 4
notReverse the result, and returns False if the result is true

Python Identity Operators

Identity operators are used to compare the objects, not if they are equal, but if they are the same object, with the same memory location:

OperatorDescription
isReturns True if both variables are the same objectx is y
is notReturns True if both variables are not the same object

Python Membership Operators

Membership operators are used to testing if a sequence is presented in an object:

OperatorDescriptionExample
inReturns True if a sequence with the specified value is present in the objectx in y
not inReturns True if a sequence with the specified value is not present in the objectx not in y

Python Bitwise Operators

Bitwise operators are used to compare (binary) numbers:

OperatorNameDescriptionExample
&ANDSets each bit to 1 if both bits are 1x & y
ORSets each bit to 1 if one of two bits is 1xy
^XORSets each bit to 1 if only one of two bits is 1x ^ y
~NOTInverts all the bits~x
<<Zero fill left shiftShift left by pushing zeros in from the right and let the leftmost bits fall offx << 2
\>>Signed right shiftShift right by pushing copies of the leftmost bit in from the left, and let the rightmost bits fall offx >> 2

Operator Precedence

Operator precedence describes the order in which operations are performed.

Example

Parentheses have the highest precedence, meaning that expressions inside parentheses must be evaluated first:

print((6 + 3) - (6 + 3))

Example

Multiplication * has higher precedence than addition +, and therefore multiplications are evaluated before additions:

print(100 + 5 * 3)

The precedence order is described in the table below, starting with the highest precedence at the top:

OperatorDescription
()Parentheses
**Exponentiation
+x -x ~xUnary plus, unary minus, and bitwise NOT
* / // %Multiplication, division, floor division, and modulus
+ -Addition and subtraction
<< >>
&Bitwise AND
^Bitwise XOR
``Bitwise OR
== != > >= < <= is is not in not inComparisons, identity, and membership operators
notLogical NOT
andAND
orOR

List

Lists are used to store multiple items in a single variable.

Lists are one of 4 built-in data types in Python used to store collections of data, the other 3 are Tuple, Set, and Dictionary, all with different qualities and usage.

Lists are created using square brackets

Tuple

Tuples are used to store multiple items in a single variable.

Tuple is one of 4 built-in data types in Python used to store collections of data, the other 3 are List, Set, and Dictionary, all with different qualities and usage.

A tuple is a collection that is ordered and unchangeable.

Tuples are written with round brackets

What is an Array?

An array is a special variable, which can hold more than one value at a time.

If you have a list of items (a list of car names, for example), storing the cars in single variables could look like this:

car1 = "Ford"
car2 = "Volvo"
car3 = "BMW"

However, what if you want to loop through the cars and find a specific one? And what if you had not 3 cars, but 300?

The solution is an array!

An array can hold many values under a single name, and you can access the values by referring to an index number.

Python Functions


A function is a block of code that only runs when it is called.

You can pass data, known as parameters, into a function.

A function can return data as a result.


Creating a Function

In Python a function is defined using the def keyword

Calling a Function

To call a function, use the function name followed by parenthesis

Arguments

Information can be passed into functions as arguments.

Arguments are specified after the function name, inside the parentheses. You can add as many arguments as you want, just separate them with a comma.

The following example has a function with one argument (fname). When the function is called, we pass along a first name, which is used inside the function to print the full name

Python Conditions and If statements

Python supports the usual logical conditions from mathematics:

  • Equals: a == b

  • Not Equals: a != b

  • Less than: a < b

  • Less than or equal to: a <= b

  • Greater than: a > b

  • Greater than or equal to: a >= b

These conditions can be used in several ways, most commonly in "if statements" and loops.

An "if statement" is written by using the if keyword.