SIMPLIFIED introduction to Python
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?
It can be used on a server to create web applications.
It can be used alongside software to create workflows.
Python can connect to database systems. It can also read and modify files.
Python can be used to handle big data and perform complex mathematics.
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: |
|
Numeric Types: |
|
Sequence Types: |
|
Mapping Type: |
|
Set Types: |
|
Boolean Type: |
|
Binary Types: |
|
None Type: |
|
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:
intfloatcomplex
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:
| Operator | Name | Example | ||
| + | Addition | x + y | ||
| - | Subtraction | x - y | ||
| * | Multiplication | x * y | ||
| / | Division | x / y | ||
| % | Modulus | x % y | ||
| ** | Exponentiation | x ** y | ||
| // | Floor division | x // y |
Python Assignment Operators
Assignment operators are used to assigning values to variables:
| Operator | Example | Same As | |||||
| \= | x = 5 | x = 5 | |||||
| += | x += 3 | x+=3 | |||||
| -= | x -= 3 | x = x - 3 | |||||
| *= | x *= 3 | x = x * 3 | |||||
| /= | x /= 3 | x = x / 3 | |||||
| %= | x %= 3 | x = x % 3 | |||||
| //= | x //= 3 | x = x // 3 | |||||
| **= | x **= 3 | x = x ** 3 | |||||
| &= | x &= 3 | x = x & 3 | |||||
| = | x | = 3 | x = x | 3 | |||
| ^= | x ^= 3 | ||||||
| \>>= | x >>= 3 | x = x >> 3 | |||||
| <<= | x <<= 3 | x = x << 3 |
ADVERTISEMENT
Python Comparison Operators
Comparison operators are used to compareing two values:
| Operator | Name | Example | Try it |
| \== | Equal | x == y | Try it » |
| != | Not equal | x != y | Try it » |
| \> | Greater than | x > y | Try it » |
| < | Less than | x < y | Try it » |
| \>= | Greater than or equal to | x >= y | Try it » |
| <= | Less than or equal to | x <= y | Try it » |
Python Logical Operators
Logical operators are used to combine conditional statements:
| Operator | Description | Example | |
| and | Returns True if both statements are true | x < 5 and x < 10 | |
| or | Returns True if one of the statements is true | x < 5 or x < 4 | |
| not | Reverse 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:
| Operator | Description | ||
| is | Returns True if both variables are the same object | x is y | |
| is not | Returns 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:
| Operator | Description | Example | |
| in | Returns True if a sequence with the specified value is present in the object | x in y | |
| not in | Returns True if a sequence with the specified value is not present in the object | x not in y |
Python Bitwise Operators
Bitwise operators are used to compare (binary) numbers:
| Operator | Name | Description | Example | |||
| & | AND | Sets each bit to 1 if both bits are 1 | x & y | |||
| OR | Sets each bit to 1 if one of two bits is 1 | x | y | |||
| ^ | XOR | Sets each bit to 1 if only one of two bits is 1 | x ^ y | |||
| ~ | NOT | Inverts all the bits | ~x | |||
| << | Zero fill left shift | Shift left by pushing zeros in from the right and let the leftmost bits fall off | x << 2 | |||
| \>> | Signed right shift | Shift right by pushing copies of the leftmost bit in from the left, and let the rightmost bits fall off | x >> 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:
| Operator | Description | ||
() | Parentheses | ||
** | Exponentiation | ||
+x -x ~x | Unary 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 in | Comparisons, identity, and membership operators | ||
not | Logical NOT | ||
and | AND | ||
or | OR |
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.