Python Programming

Aman Jaiswal
7 min readApr 30, 2022

The following are the topics that will be discussed in this blog post:

  • Python introduction
  • Python Data Structures
  • Functions in Python
  • OOPs in Python

Let's dive deep………..

Python Introduction

Python is a powerful programming language. It is very popular and used by many companies, including Google, NASA, and Industrial Light and Magic. Python is easy to learn for beginners and has many modules and libraries that allow for robust programming. Python is a great language for scripting, automation, and web development.

Advantages of Python

  1. Python is easy to learn for beginners and has a very simple syntax.
  2. Python is an interpreted language, which means that it does not need to be compiled before it is run. This makes it very easy to test and debug programs.
  3. Python is a high-level language, which means that it abstracts away many of the details of low-level languages such as C++. This makes Python programs shorter and easier to read than programs written in other languages.
  4. Python is an object-oriented language, which means that it supports programming techniques that allow data and code to be organized into objects. This makes Python programs more modular and easier to maintain.
  5. Python is a cross-platform language, which means that it can run on any operating system. This makes Python programs very portable.

Disadvantages of Python

  1. Python is an interpreted language, which means that it is slower than compiled languages such as C++.
  2. Python is a dynamically typed language, which means that variables can be assigned to any data type. This can lead to errors if variables are not used consistently.
  3. Python is a high-level language, which means that it can be difficult to interface with low-level systems such as databases or hardware.
  4. Python is an object-oriented language, which means that it can be difficult to understand programs written in other languages.

Python Data Structures

Python has a few very useful data structures built into it. We will explore the following data structures:-

  • List
  • Dictionary
  • Tuple
  • Set
  • Frozen Set
  • String
  • Byte Array

LIST

The most basic data structure in Python is the “list”. Lists are similar to arrays in C, but they have a few more built-in functions and are more flexible for use as data structures. A list is created by putting a comma-separated list of values between square brackets. Lists are mutable, meaning they can be changed in place without creating a new object.

>>> my_list = [1,2,3,4,5]

  • You can access elements in a list by their index.

>>> my_list[0] {output:- 1}

>>> my_list[1] {output:- 2}

>>> my_list[-1] {output:- 5}

  • Lists can be sliced, which means you can select a sub-list of a list.

>>> my_list[2:4] {output:-[3, 4]}

>>> my_list[:3] {output:-[1, 2, 3]}

>>> my_list[3:] {output:- [4, 5]}

  • Lists also support concatenation, which means you can combine two lists together into a new list.

>>> my_list + [6, 7, 8] {output:- [1, 2, 3, 4, 5, 6, 7, 8]}

  • You can mutate a list by indexing into it and assigning a new value.

>>> my_list[0] = “a”

>>> my_list {output:- [‘a’, 2, 3, 4, 5]}

>>> my_list[2:4] = [“c”, “d”]

>>> my_list {output:- [‘a’, 2, ‘c’, ‘d’, 5]}

  • List methods are functions that are called on lists.

>>> my_list.append(“e”)

>>> my_list {output:- [‘a’, 2, ‘c’, ‘d’, 5, ‘e’]}

>>> my_list = [3, 8, 1, 9]

>>> my_list.sort()

>>> my_list {output:-[1, 3, 8, 9]}

>>> my_list.reverse()

>>> my_list {output:- [9, 8, 3, 1]}

>>> my_list.index(8) {output:- 1}

>>> my_list.remove(8)

>>> my_list {output:- [9, 3, 1]}

>>> my_list.pop() {output:- 1}

>>> my_list {output:-[9, 3]}

DICTIONARY

Dictionary in Python is an unordered collection of data values, used to store data values like a map, unlike other Data Types that hold only a single value as an element, Dictionary holds the key: value pair. Each key-value pair in a Dictionary is separated by a colon: whereas each key is separated by a ‘comma’.

A Dictionary is mutable. It can be changed after its creation.

Dictionary is defined within braces {} where keys are mapped to values, separated by a colon:

Keys in a dictionary must be unique and must be of immutable data types such as Strings, Integers, and tuples, but the values can be repeated and be of any type.

Creating a Dictionary

Dict = {‘Tim’: 18,’Charlie’:12, ‘Tiffany’:22, ‘Robert’:25}

print (Dict[‘Tiffany’]) {output:- 22}

Dict = {‘Tim’: 18,’Charlie’:12, ‘Robert’:25, ‘Tiffany’:22}

#update value

Dict.update({“Sarah”:9})

#remove entry with key ‘Tim’

del Dict[‘Tim’]

#remove all entries in dict

Dict.clear()

#delete entire dictionary

del Dict

TUPLE

A tuple is a data structure in Python that is similar to a list, but the elements in a tuple cannot be changed once it is created.

Here is an example of a tuple:

tuple = (‘apple’, ‘banana’, ‘cherry’)

print(tuple)

SET

A set is a collection that is unordered and unindexed. In Python, sets are written with curly brackets.

Example: thisset = {“apple”, “banana”, “cherry”}

Print the number of items in the set:

len(thisset)

FROZEN SET

A frozen set is an immutable set object in Python. Once a set is created, you cannot add or remove elements from it.

This is an example of how to create a frozen set:

s = frozenset([1, 2, 3])

print(s) # Output: frozenset({1, 2, 3})

STRING

A string is a list of characters in order. Each character in a string has a numeric position. The first character is at position 0, the second is at position 1, and so on. You can access individual characters in a string by using subscript notation.

For example, if the string “Python” is stored in the variable my_string, you can access individual characters like this:

my_string = “Python”

print(my_string[0]) # Prints “P”

BYTEARRAY

A bytearray is a mutable sequence of integers in the range 0 <= x < 256. They are stored in memory as a contiguous block of bytes. You can create a bytearray from a list of integers using the bytearray() function:

>>> bytearray([0, 1, 2, 3, 4, 5, 6, 7, 8, 9]) bytearray(b’\x00\x01\x02\x03\x04\x05\x06\x07\x08\t’)

You can also create a byte array from a string using the bytearray() function:

>>> bytearray(“Hello, world!”, “utf-8”)

bytearray(b’Hello, world!’)

Once you have a bytearray, you can modify its contents using standard list operations:

>>> ba = bytearray([0, 1, 2, 3, 4, 5, 6, 7, 8, 9])

>>> ba[5] = 42 >>> ba bytearray(b’\x00\x01\x02\x03\x04*\x06\x07\x08\t’)

You can also use the append() and extend() methods to add new elements to a bytearray:

>>> ba.append(10)

>>> ba.extend([11, 12, 13])

>>> ba bytearray(b’\x00\x01\x02\x03\x04*\x06\x07\x08\t\n\x0b\x0c\r’)

Finally, you can convert a bytearray back into a string using the decode() method:

>>> ba.decode(“utf-8”) ‘\x00\x01\x02\x03\x04*\x06\x07\x08\t\n\x0b\x0c\r’

Functions

Python has a set of built-in functions that you can use on lists/arrays.

Function with their Description:-

  1. all() — Returns True if all elements in the list are true

2. any() — Returns True if any element in the list is true

3. enumerate() — Returns an enumerate object of the list

4. len() — Returns the length of the list

5. list() — Converts an iterable (tuple, string, set, dictionary) to a list

6. max() — Returns the largest element in the list

7. min() — Returns the smallest element in the list

8. sorted() — Returns a sorted list

9. sum() — Returns the sum of all elements in the list

# all()

Returns True if all elements in the list are true

l = [1, 3, 4, 5]

print(all(l)) {output:- True}

l = [0, False]

print(all(l)) {output:- False}

l = [1, 3, 4, 0]

print(all(l)) {output:- False}

# any()

Returns True if any element in the list is true

l = [1, 3, 4, 0]

print(any(l)) {output:- True}

l = [0, False]

print(any(l)) {output:- False}

l = [0, False, 5]

print(any(l)) {output:- True}

l = [0, False, 0]

print(any(l)) {output:- False}

# enumerate()

Returns an enumerate object of the list

l = [‘a’, ‘b’, ‘c’]

obj = enumerate(l)

print(list(enumerate(l))) {output:- [(0, ‘a’), (1, ‘b’), (2, ‘c’)]}

# len()

Returns the length of the list

l = [1, 2, 3, 4, 5]

print(len(l)) {output:- 5}

# list()

Converts an iterable (tuple, string, set, dictionary) to a list

t = (1, 2, 3, 4, 5)

print(list(t)) {output:- [1, 2, 3, 4, 5]}

s = ‘abcde’

print(list(s)) {output:- [‘a’, ‘b’, ‘c’, ‘d’, ‘e’]}

# max()

Returns the largest element in the list

l = [1, 2, 3, 4, 5]

print(max(l)) {output:- 5}

# min()

Returns the smallest element in the list

l = [1, 2, 3, 4, 5]

print(min(l)) {output:- 1}

# sorted()

Returns a sorted list

l = [3, 1, 4, 2, 5]

print(sorted(l)) {output:- [1, 2, 3, 4, 5]}

# sum()

Returns the sum of all elements in the list

l = [1, 2, 3, 4, 5]

print(sum(l)) {output:- 15}

Object Oriented Programming in Python

In object-oriented programming, data is organized into objects. An object is a collection of data and methods that act on that data.

For example, a car is an object that has data, such as the make, model, and year, as well as methods, such as drive and brake.

In Python, objects are created by defining classes. A class is a template for creating objects.

Here is an example of a class definition:

Example of Class Defination

The __init__ method is a special method that is called when an object is created. The data for the object is passed in as arguments to the __init__ method.

The drive and brake methods are called actions or behavior. They are defined like any other function, but they must have a reference to the object they are acting on, which is done by using the self keyword.

Once a class has been defined, we can create objects by using the class as a template.

Here is an example of creating an object from the Car class:

  • my_car = Car(“Tesla”, “Model A”, 2022)

This creates an object with the data attributes make, model, and year set to “Tesla”, “Model A”, and 2022, respectively.

We can access the data attributes of an object by using the dot notation:

  • my_car.make {output:- “Tesla”}
  • my_car.model {output:- “Model A”}
  • my_car.year {output:- 2022}

Thanks for reading!!!!!!!!!!!!!!!!!!!!!!!!

Please do not hesitate to contact me if you have any questions.

--

--