Python Basics: What makes Python so Powerful?

Last updated on Mar 10,2023 28.8K Views
I love technology and I love sharing it with everyone. I work... I love technology and I love sharing it with everyone. I work as a Research Analyst at edureka! Happy Learning

Python Basics: What makes Python so Powerful?

edureka.co

Python, you’ve heard of it and wonder what’s so special with this language. With the rise of Machine Learning and Artificial Intelligence, it is impossible to get away from it. You may question yourself, is Python easy to learn? Let me tell you, it actually is! and I am here to help you get started with Python Programming Certification.

This blog will be a walk-through for:

Let’s get started.

What is Python?

Python in simple words is a High-Level Dynamic Programming Language that is interpreted. Guido van Rossum, the father of Python had simple goals in mind when he was developing it, easy looking code, readable and open source. Python is ranked as the 3rd most prominent language followed by JavaScript and Java in a survey held in 2018 by Stack Overflow which serves as proof to it being the most growing language.


Features of Python

Python is currently my favorite and most preferred language to work on because of its simplicity, powerful libraries, and readability. You may be an old school coder or may be completely new to programming, Python is the best way to get started!

Python provides features listed below :

To sum it up, Python has a simple syntax, is readable, and has great community support. You may now have the question, What can you do if you know Python? Well, you have a number of options to choose from. 

Now when you know that Python has such an amazing feature set, why don’t we get started with the Python Basics?

Jumping to the Python Basics

To get started off with the Python Basics, you need to first install Python in your system right? So let’s do that right now! You should know that most Linux and Unix distributions these days come with a version of Python out of the box. To set yourself up, you can follow this step-to-step guide.

Once you are set up, you need to create your first project. Follow these steps:

You’re done. You have set up your files to start coding with Python. Are you excited to start coding? Let’s begin. The first and foremost, the “Hello World” program.

print('Hello World, Welcome to edureka!')

Output: Hello World, Welcome to edureka!

There you are, that’s your first program. And you can tell by the syntax, that it is super easy to understand. Let us move over to comments in Python Basics.

Comments in Python

Single line comment in Python is done using the # symbol and ”’ for multi-line commenting. If you want to know more about comments, you can read this full-fledged guide. Once you know commenting in Python Basics, let’s jump into variables in Python Basics.

Variables

Variables in simple words are memory spaces where you can store data or values. But the catch here in Python is that the variables don’t need to be declared before the usage as it is needed in other languages. The data type is automatically assigned to the variable. If you enter an Integer, the data type is assigned as an Integer. You enter a string, the variable is assigned a string data type. You get the idea. This makes Python dynamically typed language. You use the assignment operator (=) to assign values to the variables.

a = 'Welcome to edureka!'
b = 123
c = 3.142
print(a, b, c)

Output: Welcome to edureka! 123 3.142
You can see the way I have assigned the values to those variables. This is how you assign values to variables in Python. And if you are wondering, yes, you can print multiple variables in a single print statement. Now let us go over Data Types in Python Basics.

Data Types in Python

Data types are basically data that a language supports such that it is helpful to define real-life data such as salaries, names of employees and so on. The possibilities are endless. The data types are as shown below:

Numeric Data Types

As the name suggests, this is to store numerical data types in the variables. You should know that they are immutable, meaning that the specific data in the variable cannot be changed.

There are 3 numerical data types :

a = 10
b= 3.142
c = 10+6j

So now that you have understood the various numerical data types, you can understand converting one data type into another data type in this blog of Python Basics.

Type Conversion

Type Conversion is the conversion of a data type into another data type which can be really helpful to us when we start programming to obtain solutions for our problems. Let us understand with examples.

a = 10
b = 3.142
c = 10+6j
print(int(b), float(a), str(c))

Output: 10.0 3 ’10+6j’
You can understand, type conversion by the code snippet above. ‘a’ as an integer, ‘b’ as a float and ‘c’ as a complex number. You use the float(), int(), str() methods that are in-built in Python which helps us to convert them. Type Conversion can be really important when you move into real-world examples.

A simple situation could be where you need to compute the salary of the employees in a company and these should be in a float format but they are supplied to us in the string format. So to make our work easier, you just use type conversion and convert the string of salaries into float and then move forward with our work. Now let us head over to the List data type in Python Basics.

Lists

List in simple words can be thought of as arrays that exist in other languages but with the exception that they can have heterogeneous elements in them, i.e, different data types in the same list. Lists are mutable, meaning that you can change the data that is available in them.

For those of you who do not know what an array is, you can understand it by imagining a Rack that can hold data in the way you need it to. You can later access the data by calling the position in which it has been stored which is called as Index in a programming language. Lists are defined using either the a=list() method or using a=[] where ‘a’ is the name of the list.

You can see from the above figure, the data that is stored in the list and the index related to that data stored in the list. Note that the Index in Python always starts with ‘0’. You can now move over to the operations that are possible with Lists.

List operations are as shown below in the tabular format.

Code SnippetOutput ObtainedOperation Description
a[2]135Finds the data at index 2 and returns it
a[0:3][3.142, ‘Hindi’, 135]Data from index 0 to 2 is returned as the last index mentioned is always ignored.
a[3] = ‘edureka!’moves ‘edureka!’ to index 3The data is replaced in index 3
del a[1]Deletes ‘Hindi’ from the listDelete items and it does not return any item back
len(a)3Obtain the length of a variable in Python
a * 2Output the list ‘a’ twiceIf a dictionary is multiplied with a number, it is repeated that many number of times
a[::-1]Output the list in the reverse orderIndex starts at 0 from left to right. In reverse order, or, right to left, the index starts from -1. 
a.append(3)3 will be added at the end of the listAdd data at the end of the list
a.extend(b)[3.142, 135, ‘edureka!’, 3, 2]‘b’ is a list with value 2. Adds the data of the list ‘b’ to ‘a’ only. No changes are made to ‘b’.
a.insert(3,’hello’)[3.142, 135, ‘edureka!’, ’hello’, 3, 2]Takes the index and the value and adds value to that index.
a.remove(3.142)[135, ‘edureka!’, ’hello’, 3, 2]Removes the value from the list that has been passed as an argument. No value returned.
a.index(135)0Finds the element 135 and returns the index of that data
a.count(‘hello’)1It goes through the string and finds the times it has been repeated in the list
a.pop(1)‘edureka!’Pops the element in the given index and returns the element if needed.
a.reverse()[2, 3, ‘hello’, 135]It just reverses the list
a.sort()[5, 1234, 64738]Sorts the list based on ascending or descending order. 
a.clear()[]Used to remove all the elements that are present in the list.

Now that you have understood the various list functions, let’s move over to understanding Tuples in Python Basics.

Tuples

Tuples in Python are the same as lists. Just one thing to remember, tuples are immutable. That means that once you have declared the tuple, you cannot add, delete or update the tuple. Simple as that. This makes tuples much faster than Lists since they are constant values.

Operations are similar to Lists but the ones where updating, deleting, adding is involved, those operations won’t work. Tuples in Python are written a=() or a=tuple() where ‘a’ is the name of the tuple.

a = ('List', 'Dictionary', 'Tuple', 'Integer', 'Float')
print(a)

Output = (‘List’, ‘Dictionary’, ‘Tuple’, ‘Integer’, ‘Float’)

That basically wraps up most of the things that are needed for tuples as you would use them only in cases when you want a list that has a constant value, hence you use tuples. Let us move over to Dictionaries in Python Basics.

Dictionary

Dictionary is best understood when you have a real-world example with us. The most easy and well-understood example would be of the telephone directory. Imagine the telephone directory and understand the various fields that exist in it. There is the Name, Phone, E-Mail and other fields that you can think of. Think of the Name as the key and the name that you enter as the value. Similarly, Phone as key, entered data as value. This is what a dictionary is. It is a structure that holds the key, value pairs.

Dictionary is written using either the a=dict() or using a={} where a is a dictionary. The key could be either a string or integer which has to be followed by a “:” and the value of that key.

MyPhoneBook = { 'Name' : [ 'Akash', 'Ankita' ] ,
'Phone' : [ '12345', '12354' ] ,
'E-Mail' : [ 'akash@rail.com', 'ankita@rail.com' ]}
print (MyPhoneBook)

Output: { ‘Name’ : [‘Akash’, ‘Ankita’], ‘Phone’ : [‘12345’, ‘12354’], ‘E-Mail’ : [‘akash@rail.com’,’ankita@rail.com’]}

Accessing elements of the Dictionary

You can see that the keys are Name, Phone, and EMail who each have 2 values assigned to them. When you print the dictionary, the key and value are printed. Now if you wanted to obtain values only for a particular key, you can do the following. This is called accessing elements of the dictionary.

print(MyPhoneBook['E-Mail'])

Output : [‘akash@rail.com’,’ankita@rail.com’]

Operations of Dictionary

Code SnippetOutput ObtainedOperation Description
MyPhoneBook.keys()dict_keys([‘Name’, ‘Phone’, ‘E-Mail’])Returns all the keys of the dictionary
MyPhoneBook.values()dict_values([[‘Akash’, ‘Ankita’], [12345, 12354], [‘ankita@rail.com’, ‘akash@rail.com’]])Returns all the values of the dictionary
MyPhoneBook[‘id’]=[1, 2]{‘Name’: [‘Akash’, ‘Ankita’], ‘Phone’: [12345, 12354], ‘E-Mail’: [‘ankita@rail.com’, ‘akash@rail.com’], ‘id’: [1, 2]} is the updated value.The new key, value pair of id is added to the dictionary
MyPhoneBook[‘Name’][0]=”Akki”‘Name’: [‘Akki’, ‘Ankita’]Access the list of names and change the first element.
del MyPhoneBook[‘id’]{‘Name’: [‘Akash’, ‘Ankita’], ‘Phone’: [12345, 12354], ‘E-Mail’: [‘ankita@rail.com’, ‘akash@rail.com’]}The key, value pair of ID has been deleted
len(MyPhoneBook)33 key-value pairs in the dictionary and hence you obtain the value 3
MyPhoneBook.clear(){}Clear the key, value pairs and make a clear dictionary

You may now have a better understanding of dictionaries in Python Basics. Hence let us move over to Sets in this blog of Python Basics.

Sets

A set is basically an un-ordered collection of elements or items. Elements are unique in the set. In Python, they are written inside curly brackets and separated by commas. You can see that even if there are similar elements in set ‘a’, it will still be printed only once because sets are a collection of unique elements.

a = {1, 2, 3, 4, 4, 4}
b = {3, 4, 5, 6}
print(a,b)

Output : {1, 2, 3, 4} {3, 4, 5, 6}

Operations in Sets

Code SnippetOutput ObtainedOperation Description
a | b{1, 2, 3, 4, 5, 6}Union operation where all the elements of the sets are combined.
a & b{3, 4}Intersection operation where only the elements present in both sets are selected.
a – b{1, 2}Difference operation where the elements present in ‘a’ and ‘b’ are deleted and remaining elements of ‘a’ is the result.
a ^ b{1, 2, 5, 6}Symmetric difference operation where the intersecting elements are deleted and the remaining elements in both sets is the result.

Sets are simple to understand, so let us move over to strings in Python Basics.

Strings

Strings in Python are the most used data types, especially because they are easier for us humans to interact with. They are literally words and letters which makes sense as to how they are being used and in what context. Python hits it out of the park because it has such a powerful integration with strings. Strings are written within a single (‘’) or double quotation marks (“”). Strings are immutable meaning that the data in the string cannot be changed at particular indexes.

The operations of strings with Python can be shown as:

Note: The string here I use is : mystsr =”edureka! is my place”

Code SnippetOutput ObtainedOperation Description
len(mystr)20Finds the length of the string
mystr.index(‘!’)7Finds the index of the given character in the string
mystr.count(‘!’)1Finds the count of the character passed as the parameter
mystr.upper()EDUREKA! IS MY PLACEConverts all the string into the upper case
mystr.split(‘ ‘)[‘edureka!’, ‘is’, ‘my’, ‘place’]Breaks the string based on the delimiter passed as the parameter.
mystr.lower()edureka! is my placeConverts all the strings of the string into lower case
mystr.replace(‘ ‘, ‘,’)edureka!,is,my,placeReplaces the string which has old value with the new value.
mystr.capitalize()Edureka! is my placeThis capitalizes the first letter of the string

These are just a few of the functions available and you can find more if you search for it.

Splicing in Strings

Splicing is breaking the string into the format or the way you want to obtain it. For more about this topic, you can read this blog. There are many in-built functions in Python for which you can look up at this article here. That basically sums up the data types in Python. I hope you have a good understanding of the same and if you have any doubts, please leave a comment and I will get back to you as soon as possible.

Now let us move over to Operators in Python Basics.

Operators in Python

Operators are constructs you use to manipulate the data such that you can conclude some sort of solution to us. A simple example would be that if there were 2 friends having 70 rupees each, and you wanted to know the total they each had, you would add the money. In Python, you use the + operator to add the values which would sum up to 140, which is the solution to the problem.

Python has a list of operators which can be grouped as : 

Let us move ahead and understand each of these operators carefully.

Note: Variables are called operands that come on the left and right of the operator. Ex :

a=10
b=20
a+b

Here ‘a’ and ‘b’ are the operands and + is the operator.

Arithmetic Operator

They are used to perform arithmetic operations on data.

OperatorDescription
+Adds the values of the operands
Subtracts the value of the right operator with the left operator
*Multiples left operand with the right operand
/Divides the left operand with the right operand
%Divides the left operand with the right operand and returns the remainder
**Performs the exponential of the left operand with the right operand

The code snippet below will help you understand it better.

a = 2
b = 3
print(a+b, a-b, a*b, a/b, a%b, a**b, end=',')

Output : 5, -1, 6, 0.6666666666666666, 2, 8

Once you have understood what the arithmetic operators are in Python Basics, let us move to assignment operators.

Assignment Operators

As the name suggests, these are used to assign values to the variables. Simple as that.

The various assignment operators are :

OperatorDescription
=It is used to assign the value on the right to the variable on the left
+=Notation for assigning the value of the addition of the left and right operand to the left operand.
-=Notation for assigning the value of the difference of the left and right operand to the left operand.
*=Short-hand notation for assigning the value of the product of the left and right operand to the left operand. 
/=Short-hand notation for assigning the value of the division of the left and right operand to the left operand.
%=Short-hand notation for assigning the value of the remainder of the left and right operand to the left operand.
**=Short-hand notation for assigning the value of exponential of the left and right operand to the left operand.

Let us move ahead to comparison operators in this blog of Python Basics.

Comparison Operators

These operators are used to bring out the relationship between the left and right operands and derive a solution that you would need. It is as simple as to say that you use them for comparison purposes. The output obtained by these operators will be either true or false depending if the condition is true or not for those values.

OperatorDescription
==Find out whether the left and right operands are equal in value or not
!=Find out whether the values of left and right operators are not equal
<Find out whether the value of the right operand is greater than that of the left operand
>Find out whether the value of the left operand is greater than that of the right operand
<=Find out whether the value of the right operand is greater than or equal to that of the left operand
>=Find out whether the value of the left operand is greater than or equal to that of the right operand

You can see the working of them in the example below :

a = 21 
b = 10 
if a == b:
    print ( 'a is equal to b' )
if a != b
    print ( 'a is not equal to b' )
if a < b:
    print ( 'a is less than b' )
if a > b: 
    print ( 'a is greater than b' ) 
if a <= b: 
    print ( 'a is either less than or equal to b' ) 
if a >= b:
    print ( 'a is either greater than or equal to b' )

Output :
a is not equal to b
a is greater than b
a is either greater than or equal to b

Let us move ahead with the bitwise operators in the Python Basics.

Bitwise Operators

To understand these operators, you need to understand the theory of bits. These operators are used to directly manipulate the bits.

OperatorDescription
&Used to do the AND operation on individual bits of the left and right operands
|Used to do the OR operation on individual bits of the left and right operands
^Used to do the XOR operation on individual bits of the left and right operands
~Used to do the 1’s compliment operation on individual bits of the left and right operands
<<Used to shift the left operand by right operand times. One left shift is equivalent to multiplying by 2.
>>Used to shift the left operand by right operand times. One right shift is equivalent to dividing by 2.

It would be better to practice this by yourself on a computer. Moving ahead with logical operators in Python Basics.

Logical Operators

These are used to obtain a certain logic from the operands. We have 3 operands.

a = True
b = False
print(a and b, a or b, not a)

Output: False True False

Moving over to membership operators in Python Basics.

Membership Operators

These are used to test whether a particular variable or value exists in either a list, dictionary, tuple, set and so on.

The operators are : 

a = [1, 2, 3, 4]
if 5 in a:
    print('Yes!')
if 5 not in a:
    print('No!')

Output: No!

Let us jump ahead to identity operators in Python Basics.

Identity Operator

These operators are used to check whether the values, variables are identical or not. As simple as that.

The operators are : 

a = 5
b = 5
if a is b:
    print('Similar')
if a is not b:
    print('Not Similar!')

That right about concludes it for the operators of Python.

Before moving over to namespaces, I would suggest you go over Python Functions’ article to get a better understanding of functions in Python. Once you have done that, let us move ahead to namespacing in Python Basics.

Namespacing and Scopes

You do remember that everything in Python is an object, right? Well, how does Python know what you are trying to access? Think of a situation where you have 2 functions with the same name. You would still be able to call the function you need. How is that possible? This is where namespacing comes to the rescue.

Namespacing is the system that Python uses to assign unique names to all the objects in our code. And if you are wondering, objects can be variables and methods. Python does namespacing by maintaining a dictionary structure. Where names act as the keys and the object or variable acts as the values in the structure. Now you would wonder what is a name?

Well, a name is just a way that you use to access the objects. These names act as a reference to access the values that you assign to them.

Example: a=5, b=’edureka!’

If I would want to access the value ‘edureka!’ I would simply call the variable name by ‘b’ and I would have access to ‘edureka!’. These are names. You can even assign methods names and call them accordingly.

import math
square_root = math.sqrt
print('The square root is ',square_root(9))

Output: The root is 3.0

Namespacing works with scopes. Scopes are the validity of a function/variable/value inside the function or class they belong to. Python built-in functions namespacing covers all the other scopes of Python. Functions such as print() and id() etc. can be used even without any imports and be used anywhere. Below them is the global and local namespacing. Let me explain the scope and namespacing in a code snippet below :

def add():
    x = 3
    y = 2
    def add2():
        p, q, r = 3, 4, 5
        print('Inside add2 printing sum of 3 numbers:'(p+q+r))
    add2()
    print('The values of p, q, r are :', p, q, r)
    print('Inside the add printing sum of 2 numbers:'(x+y))
add()

As you can see with the code above, I have declared 2 functions with the name add() and add2(). You have the definition of the add() and you later call the method add(). Here in add() you call add2() and so you are able to get the output of 12 since 3+4+5 is 12. But as soon as you come out of add2(), the scope of p,q,r is terminated meaning that p,q,r are only accessible and available if you are in add2(). Since you are now in add(), there is no p,q,r and hence you get the error and execution stops.

You can get a better understanding of the scopes and namespacing from the figure below. The built-in scope covers all of Python making them available whenever needed. The global scope covers all of the programs that are being executed. The local scope covers all of the methods being executed in a program. That is basically what namespacing is in Python. Let us move ahead with flow control in Python Basics.

Flow Control and Conditioning in Python

You know that code runs sequentially in any language, but what if you want to break that flow such that you are able to add logic and repeat certain statements such that your code reduces and are able to obtain a solution with lesser and smarter code. After all, that is what coding is. Finding logic and solutions to problems and this can be done using loops in Python and conditional statements.

Conditional statements are executed only if a certain condition is met, else it is skipped ahead to where the condition is satisfied. Conditional statements in Python are the if, elif and else.

Syntax:

if condition:
    statement
elif condition:
    statement
else:
    statement

This means that if a condition is met, do something. Else go through the remaining elif conditions and finally if no condition is met, execute the else block. You can even have nested if-else statements inside the if-else blocks.

a = 10 
b = 15 
if a == b: 
    print ( 'They are equal' ) 
elif a > b: 
    print ( 'a is larger' ) 
else : 
    print ( 'b is larger' )

Output: b is larger

With conditional statements understood, let us move over to loops. You would have certain times when you would want to execute certain statements again and again to obtain a solution or you could apply some logic such that a certain similar kind of statements can be executed using only 2 to 3 lines of code. This is where you use loops in Python.

Loops can be divided into 2 kinds.

Loops in Python or any other language have to test the condition and they can be done either before the statements or after the statements. They are called :

You have 2 kinds of loops in Python:

Let us understand each of these loops with syntaxes and code snippets below.

For Loops: These loops are used to perform a certain set of statements for a given condition and continue until the condition has failed. You know the number of times that you need to execute the for loop.

Syntax:

 for variable in range: statements 

The code snippet is as below :

basket_of_fruits= ['apple', 'orange', 'pineapple', 'banana']
for fruit in basket_of_fruits:
    print(fruit, end=',')

Output: apple, orange, pineapple, banana

This is how the for loops work in Python. Let us move ahead with the while loop in Python Basics.

While Loops: While loops are the same as the for loops with the exception that you may not know the ending condition. For loop conditions are known but the while loop conditions may not.

Syntax:

while condition:
    statements

The code snippet is as :

second = 10 
while second >= 0: 
    print(second, end='->')
    second-=1 
print('Blastoff!')

Output : 10->9->8->7->6->5->4->3->2->1->Blastoff!

This is how the while loop works.

You later have nested loops where you embed a loop into another. The code below should give you an idea.

count = 1
for i in range(10):
    print(str(i) * i)
    for j in range(0, i):
        count = count+1

Output :

1

22

333

4444

55555

666666

777777

88888888

999999999

You have the first for loop which prints the string of the number. The other for loop adds the number by 1 and then these loops are executed until the condition is met. That is how for loop works. And that wraps up our session for loops and conditions. Moving ahead with file handling in Python Basics.

File Handling with Python

Python has built-in functions that you can use to work with files such as reading and writing data from or to a file. A file object is returned when a file is called using the open() function and then you can do the operations on it such as read, write, modify and so on.

If you would like to know about file handling in detail, you can go through the complete tutorial- File handling in Python.

The flow of working with files is as follows : 

Syntax:

File_object = open('filename','r')

Where mode is the way you want to interact with the file. If you do not pass any mode variable, the default is taken as the read mode.

ModeDescription
rDefault mode in Python. It is used to read the content from a file.
wUsed to open in write mode. If a file does not exist, it shall create a new one else truncates the contents of the present file.
xUsed to create a file. If the file exists, the operation fails
aOpen a file in append mode. If the file does not exist, then it opens a new file.
bThis reads the contents of the file in binary.
tThis reads the contents in text mode and is the default mode in Python.
+This opens the file for updating purposes.

Example:

file = open('mytxt','w')
string = ' --Welcome to edureka!-- '
for i in range(5):
    file.write(string)
file.close()

Output: –Welcome to edureka!– –Welcome to edureka!– –Welcome to edureka!– –Welcome to edureka!– –Welcome to edureka!– in mytxt file

You can go ahead and try more and more with files. Let’s move over to the last topics of the blog. OOPS and objects and classes. Both of these are closely related.

OOPS

Older programming languages were structured such that data could be accessed by any module of the code. This could lead to potential security issues that led developers to move over to Object-Oriented Programming that could help us emulate real-world examples into code such that better solutions could be obtained.

There are 4 concepts of OOPS which are important to understand. They are:

I would suggest you go over this article on Python Classes and Objects (OOPS Programming).

I hope you have enjoyed reading this blog and understood the basics of Python. Stay tuned for more. Happy Learning!

Now that you have understood Python Basics, check out the Python training in Faridabad by Edureka, a trusted online learning company with a network of more than 250,000 satisfied learners spread across the globe.

Edureka’s Python Programming Certification Training course is designed for students and professionals who want to be a Python Programmer. The course is designed to give you a head start into Python programming and train you for both core and advanced concepts.

Got a question for us? Please mention it in the comments section of this “Python Basics: What makes Python so Powerful” blog and we will get back to you as soon as possible.

Upcoming Batches For Python Programming Certification Course
Course NameDateDetails
Python Programming Certification Course

Class Starts on 18th May,2024

18th May

SAT&SUN (Weekend Batch)
View Details
Python Programming Certification Course

Class Starts on 22nd June,2024

22nd June

SAT&SUN (Weekend Batch)
View Details
BROWSE COURSES
REGISTER FOR FREE WEBINAR Prompt Engineering Explained