PYTHON PART - 1
PYTHON DATA TYPES ,OPERATORS AND STRINGS
Python Overview
What is Python
- Python is a dynamically typed, General Purpose Programming Language that supports an object-oriented programming approach as well as a functional programming approach.
- Python is also an interpreted and high-level programming language.
- It was created by Guido Van Rossum in 1989.
Features of Python
- Python is simple and easy to understand.
- It is Interpreted and platform-independent which makes debugging very easy.
- Python is an open-source programming language.
- Python provides very big library support. Some of the popular libraries include NumPy, Tensorflow, Selenium, OpenCV, etc.
- It is possible to integrate other programming languages within python.
What is Python used for
- Python is used in Data Visualization to create plots and graphical representations.
- Python helps in Data Analytics to analyze and understand raw data for insights and trends.
- It is used in AI and Machine Learning to simulate human behavior and to learn from past data without hard coding.
- It is used to create web applications.
- It can be used to handle databases.
- It is used in business and accounting to perform complex mathematical operations along with quantitative and qualitative analysis.
Installation & Getting Started
Steps to Install Python:
- Visit the official python website: https://www.python.org/
- Download the executable file based on your Operating System and version specifications.
- Run the executable file and complete the installation process.
Version:
After installation check the version of python by typing following command: ‘python --version’.
Starting Python:
Open Python IDE or any other text editor of your preferred choice. Let’s understand python code execution with the simplest print statement. Type the following in the IDE:
Now save the file with a .py extension and Run it. You will get the following output:
Installing Packages:
To install packages in Python, we use the pip command.
e.g. pip install "Package Name"
Following command installs pandas package in Python.
What is Syntax?
In simplest words, Syntax is the arrangement of words and phrases to create well-formed sentences in a language. In the case of a computer language, the syntax is the structural arrangement of comments, variables, numbers, operators, statements, loops, functions, classes, objects, etc. which helps us understand the meaning or semantics of a computer language.
For E.g. a ‘comment’ is used to explain the functioning of a block of code. It starts with a ‘#’.
More on comments in the comments chapter.
For E.g. a block of code is identified by an ‘indentation’. Have a look at the following code, here print(i) is said to be indented with respect to the link above it. In simple words, indentation is the addition of spaces before the line "print(i)"
Python Comments
A comment is a part of the coding file that the programmer does not want to execute, rather the programmer uses it to either explain a block of code or to avoid the execution of a specific part of code while testing.
Single-Line Comments:
To write a comment just add a ‘#’ at the start of the line.
Example 1:
Output:
Example 2:
Output:
Example 3:
Output:
Multi-Line Comments:
To write multi-line comments you can use ‘#’ at each line or you can use the multiline string.
Example 1: The use of ‘#’.
Output:
Example 2: The use of multiline string.
Output:
Python Variables
Variables are containers that store information that can be manipulated and referenced later by the programmer within the code.
In python, the programmer does not need to declare the variable type explicitly, we just need to assign the value to the variable.
Example:
It is always advisable to keep variable names descriptive and to follow a set of conventions while creating variables:
- Variable name can only contain alpha-numeric characters and underscores (A-z, 0-9, and _ )
- Variable name must start with a letter or the underscore character.
- Variables are case sensitive.
- Variable name cannot start with a number.
Example:
Sometimes, a multi-word variable name can be difficult to read by the reader. To make it more readable, the programmer can do the following:
Example:
Scope of variable:
The scope of the variable is the area within which the variable has been created. Based on this a variable can either have a local scope or a global scope.
Local Variable:
A local variable is created within a function and can be only used inside that function. Such a variable has a local scope.
Example:
Output:
Global Variable:
A global variable is created in the main body of the code and can be used anywhere within the code. Such a variable has a global scope.
Example:
Output:
Data Types
Data type specifies the type of value a variable requires to do various operations without causing an error. By default, python provides the following built-in data types:
Numeric data: int, float, complex
int: 3, -8, 0
float: 7.349, -9.0, 0.0000001
complex: 6 + 2i
more on numeric data types in the number chapter.
Text data: str
str: “Hello World!!!”, “Python Programming”
Boolean data:
Boolean data consists of values True or False.
Sequenced data: list, tuple, range
list: A list is an ordered collection of data with elements separated by a comma and enclosed within square brackets. Lists are mutable and can be modified after creation.
Example:
Output:
tuple: A tuple is an ordered collection of data with elements separated by a comma and enclosed within parentheses. Tuples are immutable and can not be modified after creation.
Example:
Output:
range: returns a sequence of numbers as specified by the user. If not specified by the user then it starts from 0 by default and increments by 1.
Example:
Output:
Mapped data: dict
dict: a dictionary is an unordered collection of data containing a key:value pair. The key:value pairs are enclosed within curly brackets.
Example:
Output:
Binary data: bytes, bytearray, memoryview
bytes: bytes() function is used to convert objects into byte objects, or create empty bytes object of the specified size.
Example:
Output:
bytearray: bytearray() function is used to convert objects into bytearray objects, or create empty bytearray object of the specified size.
Example:
Output:
memoryview: memoryview() function returns a memory view object from a specified object.
Example:
Output:
Set data:
Set is an unordered collection of elements in which no element is repeated. The elements of sets are separated by a comma and contained within curly braces.
Example:
Output:
None:
None is used to define a null value. When we assign a None value to a variable, we are essentially resetting it to its original empty state which is not the same as zero, an empty string or a False value.
Example:
Output:
Python Numbers
In Python, numbers are of the following data types:
- int
- float
- complex
int
int is a positive or a negative integer of any length. int should not be a decimal or a fraction.
Example:
Output:
Float
A float is a positive or a negative decimal number. It can be an exponential number or a fraction.
Example:
Output:
complex
Complex numbers are a combination of real and imaginary number. They are of the form a + bj, where a is the real part and bj is the imaginary part.
Example:
Output:
Data Conversion
- The process of converting numeric data from one type to another is called as type conversion.
- To convert from integer to float, we use float() function.
To convert from integer to complex, we use the complex() function.
Example:
Output:
- To convert from float to integer, we use int() function. int() function rounds of the given number to the nearest integer value.
To convert from float to complex, we use the complex() function.
Example:
Output:
Note: complex numbers cannot be converted to integer or float.
Type Casting
Similar to type conversion, type casting is done when we want to specify a type on a variable.
Example:
Output:
Python Operators
Python Booleans
Boolean consists of only two values; True and False.
Why are Boolean’s needed?
Consider the following if-else statement:
Is it True that X is greater than 13 or is it False?
- Thus Booleans are used to know whether the given expression is True or False.
- bool() function evaluates values and returns True or False.
Here are some examples where the Boolean returns True/False values for different datatypes.
None:
Output:
Numbers:
Output:
Strings:
Output:
Lists:
Output:
Tuples:
Output:
Sets and Dictionaries:
Output:
Python Strings
What are strings?
In python, anything that you enclose between single or double quotation marks is considered a string. A string is essentially a sequence or array of textual data.
Strings are used when working with Unicode characters.
Example:
Output:
Note: It does not matter whether you enclose your strings in single or double quotes, the output remains the same.
Sometimes, the user might need to put quotation marks in between the strings. Example, consider the sentence: He said, “I want to eat an apple”.
How will you print this statement in python?
Wrong way ❌
Output:
Right way ✔️
Output:
What if you want to write multiline strings?
Sometimes the programmer might want to include a note, or a set of instructions, or just might want to explain a piece of code. Although this might be done using multiline comments, the programmer may want to display this in the execution of programmer. This is done using multiline strings.
Example:
Output:
Operation on Strings
Length of a String:
We can find the length of a string using len() function.
Example:
Output:
String as an Array:
A string is essentially a sequence of characters also called an array. Thus we can access the elements of this array.
Example:
Output:
Note: This method of specifying the start and end index to specify a part of a string is called slicing.
Example:
Output:
Loop through a String:
Strings are arrays and arrays are iterable. Thus we can loop through strings.
Example:
Output:
String Methods
Python provides a set of built-in methods that we can use to alter and modify the strings.
upper() : The upper() method converts a string to upper case.
Example:
Output:
lower() : The lower() method converts a string to upper case.
Example:
Output:
strip() : The strip() method removes any white spaces before and after the string.
Example:
Output:
rstrip() : the rstrip() removes any trailing characters.
Example:
Output:
replace() : the replace() method replaces a string with another string.
Example:
Output:
split() : The split() method splits the give string at the specified instance and returns the separated strings as list items.
Example:
Output:
There are various other string methods that we can use to modify our strings.
capitalize() : The capitalize() method turns only the first character of the string to uppercase and the rest other characters of the string are turned to lowercase. The string has no effect if the first character is already uppercase.
Example:
Output:
center() : The center() method aligns the string to the center as per the parameters given by the user.
Example:
Output:
We can also provide padding character. It will fill the rest of the fill characters provided by the user.
Example:
Output:
count() : The count() method returns the number of times the given value has occurred within the given string.
Example:
Output:
endswith() : The endswith() method checks if the string ends with a given value. If yes then return True, else return False.
Example 1:
Output:
Example 2:
Output:
We can even also check for a value in-between the string by providing start and end index positions.
Example:
Output:
find() : The find() method searches for the first occurrence of the given value and returns the index where it is present. If given value is absent from the string then return -1.
Example:
Output:
As we can see, this method is somewhat similar to the index() method. The major difference being that index() raises an exception if value is absent whereas find() does not.
Example:
Output:
index() : The index() method searches for the first occurrence of the given value and returns the index where it is present. If given value is absent from the string then raise an exception.
Example:
Output:
As we can see, this method is somewhat similar to the find() method. The major difference being that index() raises an exception if value is absent whereas find() does not.
Example:
Output:
isalnum() : The isalnum() method returns True only if the entire string only consists of A-Z, a-z, 0-9. If any other characters or punctuations are present, then it returns False.
Example 1:
Output:
Example 2:
Output:
isalpha() : The isalnum() method returns True only if the entire string only consists of A-Z, a-z. If any other characters or punctuations or numbers(0-9) are present, then it returns False.
Example 1:
Output:
Example 2:
Output:
islower() : The islower() method returns True if all the characters in the string are lower case, else it returns False.
Example 1:
Output:
Example 2:
Output:
isprintable() : The isprintable() method returns True if all the values within the given string are printable, if not, then return False.
Example 1:
Output:
Example 2:
Output:
isspace() : The isspace() method returns True only and only if the string contains white spaces, else returns False.
Example 1:
Output:
Example 2:
Output:
istitle() : The istitile() returns True only if the first letter of each word of the string is capitalized, else it returns False.
Example 1:
Output:
Example 2:
Output:
isupper() : The isupper() method returns True if all the characters in the string are upper case, else it returns False.
Example 1:
Output:
Example 2:
Output:
replace() : The replace() method can be used to replace a part of the original string with another string.
Example:
Output:
startswith() : The endswith() method checks if the string starts with a given value. If yes then return True, else return False.
Example 1:
Output:
Example 2:
Output:
We can even also check for a value in-between the string by providing start and end index positions.
Example:
Output:
swapcase() : The swapcase() method changes the character casing of the string. Upper case are converted to lower case and lower case to upper case.
Example:
Output:
title() : The title() method capitalizes each letter of the word within the string.
Example:
Output:
Format Strings
What if we want to join two separated strings?
We can perform concatenation to join two or more separate strings.
Example:
Output:
In the above example, we saw how one can concatenate two strings. But how can we concatenate a string and an integer?
Output:
As we can see, we cannot concatenate a string to another data type.
So what’s the solution?
We make the use of format() method. The format() methods places the arguments within the string wherever the placeholders are specified.
Example:
Output:
We can also make the use of indexes to place the arguments in specified order.
Example:
Output:
Escape Characters
Escape Characters are very important in python. It allows us to insert illegal characters into a string like a back slash, new line or a tab.
Single/Double Quote: used to insert single/double quotes in the string.
Example:
Output:
New Line: inserts a new line wherever specified.
Example:
Output:
Tab: inserts a tab wherever specified.
Example:
Output:
Backspace: erases the character before it wherever it is specified.
Example:
Output:
Backslash: used to insert a backslash into a string.
Example:
Output:
Comments
Post a Comment