Discover the power of technology and learning with TechyBuddy

Python Core Concepts Made Simple: A 10-Minute Guide for All

Spread the knowledge
Python

In today’s world, every industry one or other way are depend on a software for its proper functioning whether its a banking, research, healthcare, automobile, travel or any other. There are huge list of programming languages that facilitate the software development process. Among these, Python stands out as the most lucrative and captivating programming language. As per a survey done on programming languages it is observed that python is the main coding language for more than 80% of developers. The biggest reason why Python was chosen worldwide is it is having extensive libraries and frameworks that ease the development and research.

Table of Content

Introduction

Currently, Python stands as the most popular general-purpose, interpreted, interactive, and high-level programming language. It supports both procedural and object-oriented programming paradigms. Its design concept uses the off-side rule to apply considerable indentation, which promotes code readability. In general, Python applications are smaller than those written in other languages, such as Java. The indentation requirements of the language mean that programmers type far less and are always readable.

Python uses garbage collection and dynamic typing. It is compatible with various programming paradigms, such as object-oriented, functional, and structured (especially procedural). It is sometimes referred to as a “batteries included” language due to its large collection of standard libraries.

Python’s greatest asset is its vast library of standard libraries, which can be utilized for the following purposes:

  • Web frameworks like Flask and Django (used by YouTube, Instagram, Dropbox)
  • Machine Learning and Data Science ( Sklearn, Tensorflow etc. )
  • Data Processing and Analytics
  • GUI Applications (like ivy, Tkinter, PyQt etc. )
  • Image processing (like OpenCV, Pillow)
  • Web scraping (like Scrapy, BeautifulSoup, Selenium)
  • Test frameworks
  • Multimedia
  • Scientific computing
  • Text processing and many more…

Python Core Concepts

In this section we are going to explore Python core concepts which includes

  1. Data Type
  2. Operators
  3. Control Flow
  4. Comprehensions
  5. Functions
  6. Exceptions handling
  7. Lambda
  8. Map and Filter

Python Data Types

Data types are the representation of or categorization of data items. It represents the kind of values it can hold and the type of operations that can be performed on it. Since everything is an object in Python data types are actually classes and variables are instances (object) of these classes.

The below list have some standard built-in data types available in Python:

  • Numeric : Integer, Float and Complex Number
  • Sequence Type : Str (String), List and Tuple
  • Boolean : True and False
  • Set
  • Dictionary
  • Binary Sequence Types : memoryview, bytearray and bytes

Numeric

In Python, data with numerical values are represented by the data type collectively called as numeric. An integer, floating point, or even complex number can be a part of a numeric value.

  • Integers – The int class represent integer value. It is made up of whole numbers only—no decimals or fractions are possible— but can have values which are either positive or negative. An integer value can be as lengthy as it wants to be in Python.
  • Float – The float class is represent float value. It is used to represent real numbers and to specify decimal places. When it is required to indicate scientific notation, the alphabet ‘e’ or ‘E’ is optionally inserted, with a positive or negative number.
  • Complex Numbers – A complex class is represent a complex number. The formula is given as (imaginary part) + (actual part)j. For example, 9+100j

Sequence Data Type

Python defines sequence data type as an ordered collection of either distinct or comparable data types. Sequences helps and enable the efficient way of grouping and storing of multiple values. Python has multiple types of sequences, lets explore each of them

String

Python strings are arrays of bytes that correspond to Unicode characters. One or more characters placed between either in a single, double, or triple quote is considered as a string. A character in Python is a string of length one; there is no such thing as a character data type. It is shown via the str class.

Python allows the creation of strings using single, double, or even triple quotes.

List

Lists are ordered collections of data that are , exactly as arrays declared in different languages. Since items in a list do not have to be of the same type, it is immensely flexible.

To create a list in Python, just enclose the sequence in square brackets [].

Tuple

Tuples are ordered collections of Python sequences, similar to lists data type. It is differ from a list as a tuple is immutable where as a list is. It means tuples cannot be modified after it has been created.If you need to have a modified version of current tuple then you need to create a new one. A tuple class serves as its representation.

A sequence of values separated by a “comma” is put together to form a tuple, either with or without parentheses to organize the data sequence. Any number of elements and any type of data (such as strings, integers, lists, etc.) can be present. It is possible to make it with just one part, but it requires some effort. To make one element tuple, there needs to be a trailing “comma” in addition to the element enclosed within parentheses.

Boolean

Only True or False, the two built-in values for data types Boolean can have. Boolean objects with values of True represent truth (true values), whereas those with values of False represent false values. However, non-Boolean objects can also be assessed and proven true or false in a Boolean environment. To indicate it, use the class bool. Capital “T” and “F” for True and False indicate that they are genuine booleans; otherwise, Python will generate an error. Additionally, a value of 0 (zero) is regarded as False, and any other value is regarded as True.

Set

A set is an unordered, mutable, iterable collection of data types without duplicates. i.e it contains only unique values. It can contains any number and any type of objects but the order in which they appear is not specified.

The built-in set() function can be used to generate sets with an iterable object or a sequence by enclosing the sequence in curly braces and separating it with a “comma.” A set can contain items of different data types; mixed-up data types can also be given to the set.

Dictionary

Unlike other data types that only have a single value as an element, dictionaries hold a key:value pair and are used to store data values in an unordered collection similar to a map. To improve optimization, the dictionary provides key-value. In a dictionary, a colon (:) separates each key-value pair, while a comma separates each key.

To build a dictionary in Python, enclose a list of elements in curly {} braces, with commas between each one. While keys in a dictionary cannot be duplicated and must be immutable, values within a dictionary can be of any datatype. The built-in dict() function can also be used to generate a dictionary. You can build an empty dictionary by simply enclosing it in curly braces{}. Dictionary keys differ depending on the case; keys with the same name but different cases will be handled differently and are not considered as same.

Binary Sequence Types

The fundamental built-in types for working with binary data are bytearray and bytes. Memory supports them by allowing access to other binary object’s memory without requiring a copy through the buffer protocol.

Bytes

Bytes objects are made up of immutable sequences of single bytes. Bytes objects have various methods that are only valid when working with ASCII compliant data because many primary binary protocols are based on the ASCII text encoding.

Bytes are having similar syntax to define literals as string has except having additional ‘b’ prefix representing bytes

  • Single quotes: b'strings which having embedded "double" quotes'
  • Double quotes: b"strings which having embedded 'single' quotes"
  • Triple quoted: b'''string in three single quotes'''b"""string in three double quotes"""

Bytes literals can also employ the ‘r’ prefix, just like string literals, to prevent escape sequence processing.

In addition to this bytes objects can also be created using bytes()

  • Build with given length of 5 with zero filled: bytes(5)
  • Build using an iterable of integers: bytes(range(20))
  • Copying existing binary data via the buffer protocol: bytes(obj)
Bytearray

A bytearray is a mutable as compared to bytes objects. To create a bytearray you need to call its constructor. There is no other way to create it. Consider below example of creating a bytearray.

  • Build an empty instance: bytearray()
  • Build with given length of 5 with zero filled: bytearray(5)
  • Build using an iterable of integers: bytearray(range(20))
  • Copying existing binary data via the buffer protocol: bytearray(b'Hi!')
Memoryview

A memoryview objects allow Python code to access the internal data of an object that supports the buffer pool protocol without copying.

It is capable of conceptualizing an element, which is the atomic memory unit that the original object manages. An element is a single byte for many simple kinds, such bytearrays and bytes, while other types, like arrays, it may have more bytes.

To view and get the data from memoryview, use slicing and indexing.

Python Operators

Arithmetic Operators

  • + for addition
  • – for subtraction
  • * for multiplication
  • / for division
  • // for floor division
  • % for modulo or remainder

Relational Operators

  • > for greater than
  • >= for greater than or equal to
  • < for less than
  • <= for less than or equal to
  • == for is equal to
  • != for is not equal to

Logical Operators

  • and − true only if both operands are true
  • or − true even if one operands is true
  • not − true if operand is false and vice versa

Bitwise Operators

  • & for bitwise AND
  • | for bitwise OR
  • ~ for bitwise NOT
  • ^ for bitwise XOR
  • >> for bitwise right-shift
  • << for bitwise left -shift

Assignment Operators

  • = used to assign the value on right side of it to variable on the left
  • += add and assign both
  • *= multiply and assign both
  • -= subtract and assign both
  • /= divide and assign both

Identity Operators

  • is − true if operands are identical
  • is not − false if operands are not identical

Membership Operators

  • in − true if value present in sequence
  • not in − false if value not present in sequence

Python Control Flow

Python supports below two type of control flow

  • Decision making
  • Loops

In Decision making multiple expressions are evaluated and yielding an outcome of TRUE or FALSE. If the outcome is FALSE, you must decide which statements to execute and which action to take.

Note: Any non-zero or non-null number is presumed to be TRUE in the Python programming language, and if it is either zero or null, it is assumed to be FALSE.

Python provides “If and Else” for decision making

If and Else

  • if statements: it is made up of a boolean expression and one or more statements that follows it. These statments runs only if boolean expression evaluates to TRUE
  • if…else statements: an optional else statement can be used with If statement and only executes when the boolean expression evaluated as FALSE
  • nested if statements: If statements can be nested, meaning that one if or else if statement can be used inside another if or else if statement.

Loops

By using loops, we can run a set of statements multiple times till the given boolean conditions are TRUE. Python offers the various categories of loop statements that we can use to run a statement or set of statements repeatedly. Lets explore them now:

  • while loop: Till a certain condition is true, a statement or set of statements are repeated in a while loop. Prior to starting the body of the loop, it tests the condition first.
  • for loop: Loop is controlled by the loop variable. We use loop variable to repeatedly runs a series of statements.
  • nested loops: You can also nested loops with in one another to write more complex logics

Loop Control Statements

The usual sequence of loop execution is altered by these statements. All automatically produced objects inside a scope are deleted upon exiting execution. Python supports the below three type of control statements

  • break: It moves control to the statement that follows the loop and ends the execution of the current loop statement.
  • continue: it terminates the current loop sequence by bypassing the remaining parts of the loop and transfer the control to the beginning of the loop to restarting next iteration after boolean condition check
  • pass: the pass statement is used where a syntactically statement is required to be executed but you do not want to run any commands or code to be run.

Python Comprehensions

Python has a unique way of creating new sequences which other programming languages does not have, a Comprehensions. Comprehensions provide us with a short and concise way to construct new sequences (such as lists, set, dictionary etc.) using sequences which have been already defined.

Current version of Python have below four comprehensions available:

  • List Comprehensions
  • Dictionary Comprehensions
  • Set Comprehensions
  • Generator Comprehensions

List Comprehension

A list comprehension is used to create a new list using another existing sequence object. It is made up of an expression, one or more FOR and an optional IF clauses all enclosed in a single square brackets. The expression will be evaluated in the context of the FOR and IF clauses that follow it, producing a new list as the outcome.

Python list-comprehension

Dictionary Comprehension

Similar to list comprehensions, we can also create a new dictionary using dictionary comprehensions. The basic structure and syntax of a dictionary comprehension is mentioned below. You can also use IF clause but it is optional here as well.

Python dict-comprehension

Set Comprehension

Set comprehensions are similar to list comprehensions too. The only difference is that it is enclosed in curly brackets { } instead of square brackets in list comprehension. As set comprehension is also using the curly brackets do not get confused with dictionary comprehensions, in dictionary comprehensions we have key:value pair but in set comprehension we did not. Here as well IF clause is optional.

Python set-comprehension

Generator Comprehension

List comprehensions and generator comprehensions are extremely similar in terms of syntax. Only difference in syntax is square brackets [] are used in list comprehensions, while circular brackets () are used in generator comprehensions.

Syntax-wise, list comprehensions and generator comprehensions are very similar. The lone distinction in syntax is that generator comprehensions use circular brackets () while list comprehensions use square brackets [].

Generator are more memory efficient as compare to list comprehensions. The fact that generators don’t allocate memory for the entire list immediately , rather they produce every value individually, which accounts for their memory efficiency.

Python generator-comprehension

Functions

A function is a logical, reusable, systematic collection of code that is used to perform a particular task from the collection of various related tasks. The idea is to combine together some of the most often performed activities into a function so that, rather than writing the same code repeatedly for various inputs, we can call the function repeatedly to reuse the code they contain.

Functions offer a high degree of code reuse and improved modularity for your program. You can write your own functions in Python in addition to using its many built-in functions, such as print(). User-defined functions, or UDFs, are the name given to those functions that you create.

Types of Arguments

Python supports below four types of arguments that you can pass while calling a function

  • Default argument: with this argument if the value of parameter is not provided while calling the function then a default value will be assumed. We need to provide default value while creating function.
  • Positional arguments: these arguments have to pass in same order as we have defined the parameters in function definition while creating it, if you change the argument position then you may get the unexpected output. Positional arguments are the mandatory arguments without passing them function will throw error.
  • Keyword or named arguments: these argument helps provide associated values along with argument names so that the caller need to remember the order of parameters in the function
  • Arbitrary arguments: arbitrarily any number of arguments can be passed using *args (Non-Keyword Arguments) and **kwargs  (Keyword Arguments)

Note: In Python, all arguments, or parameters, are passed in by reference. This implies that any changes made to a parameter inside of a function will likewise be reflected in the function that called it.

Lambda Function

It is also referred as anonymous function.

python-lambda
  • arguments: these are the input parameters and you can have any number of them
  • expression: It can be any single expression without any loops that it evaluates and return.

Properties of Lambda function:

  • Lambda function can have any number of arguments but only only one expression
  • It cannot have loops in its expression statements
  • Anywhere that function objects can be used, lambda functions can be utilized

Exception Handling

Errors detected during execution are called exceptions. Most exceptions are not handled by programs, however, and result in error messages by throwing exceptions to environment where that program has called.

BaseException: The universal foundation class for all exceptions. The root class for all non-fatal exceptions is called Exception, one of the subclasses of BaseException. Since they serve as a signal for the program to end, exceptions that are not subclasses of Exception are usually ignored. These include KeyboardInterrupt, which is raised when a user wants to stop the program, and SystemExit, which is triggered by sys.exit().

Exception is a wildcard that can be used to capture any error occur during runtime. Nonetheless, it is best practice to enable any unexpected exceptions to spread or propagate farther and to handle only those kinds of exceptions that we expect and plan to handle.

Handling Exceptions

In Python we have try and except statements to handle exceptions and to write codes that executes when any exception has been captured.

try statement

  • Control execute the code between try and except
  • If no exception raised then the except clause is bypassed
  • If any exception raised during the execution of the try clause, the rest of the statements is bypassed. Control then search for the exception named after the except keyword and first matched except clause is executed. Once except clause executed, control passes to next statement to try-except block if any present
  • If any exception raised and control does not found any matched exception name in the except clause, then it propagates the exception to its enclosed outer try statements if any; if no handler is found, it is treated as an unhandled exception and execution of the program stops with an exception message.

To setup handlers for various exceptions, a try statement can contain more than one except clause. But only one handler is executed for any exception. Exception handlers can only handle exceptions that arise in the associated try clause and not the unrelated try clauses. Multiple exceptions can be put together as a tuple in an except clause.

An optional else clause is also available with try … except statement, if present then it should be the last clause after all except clauses. It is useful for code that can be utilised if no exceptions has been raised.

The raise statement allows to raise a specified exception forcefully.

You can also create your own user defined exceptions as per your business or program requirements.

Learn more about Python

Leave a Comment

Your email address will not be published. Required fields are marked *

Scroll to Top