✨PYTHON is the new C✨

ALL YOU NEED TO KNOW ABOUT PYTHON LANGUAGE 🐍

Generally, the Pythons are better than anything else at killing - Dave Barry

Hola readers, This Article is all about Python programming, basically a Bootcamp of Python 🐍. I tried to include as much I can and sorry to not include everything as I am just a Human after all.

Now The biggest question arises Why choose Python 🐍?

It is a well-known fact that the Mother of all languages is the C Language. No one can deny that it is the foundation of programming but as time changes so do everything. So the majority of companies, developers, (me 😜 ) is shifting to the Python Language due to various factors listed below:

  1. Python language is incredibly easy to use and learn for new beginners and newcomers.
  2. Vast Community of Developers.
  3. Python Programming language is heavily backed by Facebook, Amazon Web Services, and especially Google.
  4. The big supportive community of python.
  5. There are many frameworks and libraries are available for the python language.
  6. Python language is efficient, reliable, and much faster than most modern languages.
  7. Can run in nearly any kind of environment.
  8. Can do almost anything like Machine Learning, Data Science, Cloud computing, Deep Learning, E.t.c.

The joy of coding Python should be in seeing short, concise, readable classes that express a lot of action in a small amount of clear code, not in reams of trivial code that bores the reader to death - Guido Van Rossum

CONTENT :

Introduction to Python: Keywords, Identifiers, Statements, Comments & Data Types.

Python I/O, Import, Operators, Namespaces and few useful functions.

Flow Control (Loop and Conditions).

Python Data Types (List, Tuples, Dictionary, Strings).

Indexing and Slicing with sequences.

Exceptions Handling (basics)

dir() in python.

f string in python.

Functions and Modules.

List Comprehensions.

Iterators and Generators.

Classes and Objects in Python.

Closures and Decorators.

Descriptors and Properties.

Bonus: Is python interpreted or compiled?

Python is the “most powerful language you can still read” - Paul Dubois

Photo by Ilija Boshkov on Unsplash

Introduction to Python: Keywords, Identifiers, Statements, Comments & Data Types.

Python is a simple, general-purpose interpreted, interactive, highly readable object-oriented, and high-level programming language. It was created by Guido van Rossum during 1985- 1990. Python source code is also available under the GNU General Public License (GPL).

Python Keywords are the reserved words and one cannot use them as constant or variable or any other identifier names. All the Python keywords contain lowercase letters only.

Python identifier is a name used to identify a variable, function, class, module, or another object. An identifier starts with a letter A to Z or a to z or an underscore (_) followed by zero or more letters, underscores, and digits (0 to 9).

For example, Python and python are two different identifiers.

Python Statements are the Instructions written in the source code for execution. There are Multi-Line Statements: Statements in Python generally end with a new line. Python does, however, allow the use of the line continuation character (\) to denote that the line should continue.

Using semicolons(;) :
flag = 0;
Using Continuation Character (\):
sumo = 1 + 2 + 3 + \
4 + 5 + 6

Python Comments are useful information that the developers provide to make the reader understand the source code. It explains the logic or a part of it used in the code. Comments are usually helpful to someone maintaining or enhancing your code when you are no longer around to answer questions about it. Comments are of two types:

Single line comments: Python single line comment starts with hashtag symbol with no white spaces (#) and lasts till the end of the line.

# I am a comment and you are a snake.

Multi-line string as a comment: Python multi-line comment is a piece of text enclosed in a delimiter (""") on each end of the comment.

''' 
I am a comment
and you are still a snake.
'''

Since everything is an Object in Python programming, Python Data types are actually classes and variables are instance (object) of these classes.

Python Numbers:

Integers, floating-point numbers, and complex numbers fall under this category. They are defined as int, float and complex classes in Python.

List:

It is an ordered sequence of items. It is one of the most used data types in Python and is very flexible. All the items in a list do not need to be of the same type.

Items separated by commas are enclosed within brackets [ ].

Tuple:

It is an ordered sequence of items same as a list. The only difference is that tuples are immutable. Tuples once created cannot be modified. Tuples are used to write-protect data and are usually faster than lists as they cannot change dynamically.

It is defined within parentheses () where items are separated by commas.

String:

It is the sequence of Unicode characters. We can use single quotes or double quotes to represent strings. Multi-line strings can be denoted using triple quotes, ''' or """.

Set:

It is an unordered collection of unique items. Set is defined by values separated by a comma inside braces { }. Items in a set are not ordered.

Dictionary:

Dictionary is an unordered collection of key-value pairs.

In Python, dictionaries are defined within braces {} with each item being a pair in the form key:value. Key and value can be of any type.

2. Python I/O, Import, Operators, Namespaces, and few useful functions.

Python Built-in functions like input() and print() are widely used for Standard I/O operations respectively.

We can import a module using the import statement and access the definitions inside it using the dot operator (.). Here is an example:

In Python, one can say a namespace as a mapping of every name you have defined to corresponding objects. In simple words, a namespace is a collection of names. A namespace containing all the built-in names is created when we start the Python interpreter and exists as long as the interpreter runs.

This is the reason that built-in functions like id(), print() etc. are always available to us from any part of the program. Each module creates its own global namespace.

Here are same basic Python functions such as len(), range(), list(), min(), max(), round(), abs(), pow(),strip(), split(), type(), e.t.c. These functions are are very commonly used functions in various applications.

Click Here to know all about Built-in functions in Python.

3. Flow Control (Loop and Conditions).

One can say Flow Control — control of the “flow” of executed code. It is its ability to make decisions as to what to do next.

Types of Flow Control:

The most common flow control types used in Python Programming are as follows:-

The most basic type of flow control is the humble if statement:

x=3
if x==3:
print("x is equal to 3.")
elif x>3:
print("x is greater than 3")
else:
print("x is smaller than 3")

Another important and most useful flow control statement are Loops:

The simplest loop is a while loop. A while loop is given a condition and executes the loop until the condition is false. (If the condition is false, it does nothing.)

a=1
while a > 0:
print("I love chicken")

The most common loop, however, is for. Most languages have for loops that simply loop with some syntactic help. Python for loops are more versatile - they loop through containers.

for i in range(5):
print(i)

Also, there are two useful flow control statements within loops:

break escapes the current loop, and moves on after it. For example:

for i in range(100):
if i==5:
break
print(i)

continue works similarly, but instead of escaping the loop, it starts the next iteration immediately:

for i in range(10):
if i==5:
continue
print(i)

To know more about the Loops you can check here.

4. Python Data Types (List, Tuples, Dictionary, Strings).

We have seen these Python data types above in this article, but now we see its implementation in details:

Lists in Python:
Lists are just like the arrays declared in other languages. But the most powerful thing is that list need not be always homogeneous. A single list can contain strings, integers, as well as objects. Lists can also be used for implementing stacks and queues. Lists are mutable, i.e., they can be altered once declared.


L = [1, “a” , “string”]
print L

Tuples in Python:
A tuple is a sequence of immutable Python objects. Tuples are just like lists with the exception that tuples cannot be changed once declared. Tuples are usually faster than lists.

tupl = (1, “a”, “string”) 
print(tupl)

Dictionary in Python:
In python, a dictionary is similar to hash or maps in other languages. It consists of key-value pairs. The value can be accessed by a unique key in the dictionary.


d = dict() # or d = {}
# Add a key — value pairs to dictionary
d[‘xyz’] = 123
d[‘abc’] = 345
print d

Strings in Python:
A string is a sequence of characters. It can be declared in python by using double-quotes(“ “). Strings are immutable, i.e., they cannot be changed.

str = “This is a string and you are merely a snake”
print (str)
Photo by Roman Synkevych on Unsplash

Life is short (You need Python )
Bruce Eckel

5. Indexing and Slicing with sequences.

The best part of Python is this indexing and slicing as in Python, the string data type is a sequence made up of one or more individual characters that could consist of letters, numbers, whitespace characters, or symbols.

Indexing means referring to an element of an iterable by its position within the iterable. Each of a string’s characters corresponds to an index number and each character can be accessed using their index number.

# declaring the string 
str = “I told you earlier that You are a Snake!”
# accessing the character of str at 0th index
print(str[0])
# accessing the character of str at 6th index
print(str[6])

Strings in python support indexing and slicing. To extract a single character from a string, follow the string with the index of the desired character surrounded by square brackets ([ ]), remembering that the first character of a string has index zero.

The syntax for slicing in python :

string[start : end : step]
start : the starting index.
end : the end index(this is not included in substring).
step : It is an optional argument.
#For Example:
str =”Python is a snake just like you!”
# slicing using indexing sequence
print(str[: 3])
print(str[1 : 5 : 2])

To know more about indexing and slicing Click Here.

6. Exceptions Handling (basics).

In Python, an error can be a syntax error or an exception.

Errors are the problems in a program due to which the program will stop the execution. Whereas, exceptions are raised when some internal event occurs which changes the normal flow of the program.

Below is the simple program to handle the simple Runtime error as the list doesn’t have 3rd element.

7. dir() in python.

The dir() method tries to return a list of valid attributes of the object.

Return Value from dir():

dir() tries to return a list of valid attributes of the object.

  • If the object has __dir__() method, the method will be called and must return the list of attributes.
  • If the object doesn’t have __dir__() method, this method tries to find information from the __dict__ attribute (if defined), and from the type object. In this case, the list returned dir() may not be complete.
  • If an object is not passed to dir() method, it returns the list of names in the current local scope.
class Person:
def __dir__(self):
return ['age', 'name', 'salary']

teacher = Person()
print(dir(teacher))
# o/p: ['age', 'name', 'salary']

8. f string in python.

String formatting is attractively designing your string using formatting techniques provided by the particular programming language.

f-string evaluates at runtime of the program. It’s swift compared to the previous methods.

f-string having an easy syntax compared to previous string formatting techniques of Python. We will explore every bit of this formatting using different examples.

Also called “formatted string literals,” f-strings are string literals that have an f at the beginning and curly braces containing expressions that will be replaced with their values. The expressions are evaluated at runtime and then formatted using the __format__ protocol. As always, the Python docs will help you to learn more.

9. Functions and Modules.

A function is a block of organized, reusable code that is used to perform a single, related action.

We have Built-in Functions as discussed earlier in this article and we can even create our own function termed as User-Defined Functions.

Function blocks begin with the keyword def followed by the function name and parentheses ( ( ) ).

Syntax:

def function_name( parameters ):
function_body
return [expression]

A Module allows you to logically organize your Python code. A module is a Python object with arbitrarily named attributes that you can bind and reference.

Generally saying, a module is a file consisting of Python code. A module can define functions, classes, and variables. A module can also include runnable code.

10. List Comprehensions.

List comprehension is an elegant way to define and create lists based on existing lists.

Example: Iterating through a string Using List Comprehension

h_letters = [ letter for letter in 'human' ]
print( h_letters)

When we run the program, the output will be:

['h', 'u', 'm', 'a', 'n']

Syntax of List Comprehension:

[expression for item in list]

11. Iterators and Generators.

A Python Generator function lends us a sequence of values to python iterate on.

>>> def even(x):
while(x!=0):
if x%2==0:
yield x
x-=1
>>> for i in even(8):
print(i)
Output:
8
6
4
2

A Python iterator returns us an iterator object- one value at a time.

>>> iter_obj=iter([3,4,5])
>>> next(iter_obj)

3

>>> next(iter_obj)

4

12. Classes and Objects in Python.

A python is an object oriented programming language. Unlike procedure-oriented programming languages like C, where the main emphasis is on functions, object-oriented programming emphasizes on objects.

In Python, class definitions begin with a class keyword. A class is a user-defined blueprint or prototype from which objects are created. An Object is an instance of a Class. A class is like a blueprint while an instance is a copy of the class with actual values.

13. Closures and Decorators.

A Closure is a nested function that has access to a free variable from an enclosing function that has finished its execution. Three characteristics of a Python closure are:

  • it is a nested function.
  • it has access to a free variable in the outer scope.
  • it is returned from the enclosing function.

def outerFunction(text):
text = text
def innerFunction():
print(text)
return innerFunctionif __name__ == '__main__':
myFunction = outerFunction('Hey!')
myFunction()

Python has an interesting feature called decorators to add functionality to an existing code.

This is also called meta programming as a part of the program tries to modify another part of the program at compile time.


def hello_decorator():
print(“Gfg”)
‘’’Above code is equivalent to -def hello_decorator():
print(“Gfg”)

hello_decorator = gfg_decorator(hello_decorator)’’’

14. Descriptors in Python.

Descriptors are Python objects that implement a method of the descriptor protocol, which gives you the ability to create objects that have special behavior when they’re accessed as attributes of other objects.

__get__(self, obj, type=None) -> object
__set__(self, obj, value) -> None
__delete__(self, obj) -> None
__set_name__(self, owner, name)

If your descriptor implements just .__get__(), then it’s said to be a non-data descriptor. If it implements .__set__() or .__delete__(), then it’s said to be a data descriptor. Note that this difference is not just about the name, but it’s also a difference in behavior.

Is python interpreted or compiled?

As we know that the Python language is an interpreted language. But that is half correct as the python program is first compiled and then interpreted. The compilation part is hidden from the programmer thus, many programmers believe that it is an interpreted language. The compilation part is done first when we execute our code and this will generate byte code and internally this byte code gets converted by the python virtual machine(p.v.m) according to the underlying platform(machine+operating system).

Thanks for reading 😇

“Technical content writer”

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store