Python is a programming language or more specifically computer programming language. In case you are a complete beginner, computer programming language are the basis of all the software applications, mobile applications which are built using some kind of programming language . Even in traditional calculators, there was a software program written in some programming language which was taking our inputs and giving us outputs.
A program is basically set of commands written in a particular pattern to achieve desired results.
It is an interpreted kind of programming language
Simplest of other high level languages
It is used in variety of applications such as Software Development, Data Science, Machine Learning, Data Engineering, Web Development etc
There is an official repository of python which is PyPI or python package index.
Over 1 lakh packages are available which can be installed using pip
Below is the program to add two numbers. It has 3 variable 'a', 'b' and 'sum' where 'sum' holds the addition of the two numbers that will be assigned to variable 'a' and 'b'. At last, we have inbuilt python function which is "print" to print the sum of two numbers. Try the code in the editor below and feel free to tweak the code and try different things to explore.
a=2
b=3
sum=a+b
print(sum)
In simple terms indentation is the space from the left.
It should be consistent throughout the code. If you use "tab" key for space then use same everywhere or if you use "space bar" for space use same everywhere within the code.
With indentation, we will be able to tell the program that it is a block of code
This is needed as we need to add space when we add loop or if-else statement within our program in order to tell the compiler or computer that these statements or commands are inside that loop.
Lets consider the below example :
Whenever you work with code, you work with data and that data can be of different types like number, floating number, characters etc.
for example: if you are woring on a code which is having requirement of first name and last names, then these kind of data will be character or in case code is having data like percentage or score then that data will be of number or floating number.
Unlike other programming languages, in python you do not need to explicitly define data type. Python automatically detects when you assing any data to variable. Also you dont need to explicitly specify size of the data as it will adjust accordingly and maximum size depends on memoryof the system.
Let's understand primary data types in python:
As the name suggests, it can have all integers from negative to positive
For Example:
a = 1
here variable "a" is given value 1, which is integer, if you check type of variable "a" it will show you as integer
As the name suggests, it can have all floating values from negative to positive
For Example:
a = 1.5
here variable "a" is given value 1.5, which is a floating point number, if you check type of variable "a" it will show you as float
As the name suggests, it can have all integers from negative to positive
For Example:
a = "python tutorial"
here variable "a" is given value "python tutorial", which is a string value, if you check type of variable "a" it will show you as string
We will see examples in next section "Working With Strings".
As the name suggests, it can have all integers from negative to positive
For Example:
a = True
here variable "a" is given value True, which is boolean value,if you check type of variable "a" it will show you as Boolean
Boolean values i.e. 'True' and 'false' works eith logical and comparison operators. Logical operators like 'and' , 'or', 'not' operators. Comparison operators like '==', '!=', '<', '>', '<=', '>='
For Example: below code will result in "True" as num_1 is greater than num_2 otherwise it would have given false.
num_1 = 5
num_2 = 3
result = num_1 > num_2
print(result)
String is the most common data type when working with any data and one needs to perform various operations on string.
To perform various operations, python provides various built in function to work with strings. Some of the commonly used functions are explained below :
This in-built function is used to calculate length of a string. This function can be used with other data types and structures also.
below is the example of len() function applied on a string:
my_string="Apples are great"
print(len(my_string))
We have applied the length function on our string which is stored in a variable "my_string". Notice that we have enclosed length function within print function inorder to output the length on console. Without print function, it would calculate on backend but won't show length to us.
This function will convert the characters of a string to capital letters.
my_string="Apples are great"
my_string.upper()
print(my_string.upper())
This function will not update the main string. Your main string will remain same until you update it. Below is the example to explain it.
my_string="Apples are great"
print(my_string.upper())
print(my_string)
my_string1=my_string.upper()
print(my_string1)
This will result in the lowercase characters when applied on string.
my_string="Apples are great"
print(my_string.lower())
This will remove the leading and trailing spaces from the string.
It will not remove the spaces in between the string.
my_string=" Apples are great "
print(my_string.strip())
There are two more strip functions :
lstrip() to strip spaces only on left of the string
rstrip() to strip spaces only on right of the string
With this function one can replace a character, words orwords from a string with the other character of your need.
Try the below examples within the editor and check the output.
my_string="How do you do ?"
print(my_string.replace("do","to"))
print(my_string.replace("d", "k"))
In the above examples you can see that the first option within replace() function is the character or word of the string which you want to replace and the second option is the character or word which you want to add at the place of the old character.
This will give number occurrences of a character, word or string within you string element
Consider the below example :
my_string="How do you do ?"
print("occurrences of 'do' are : " , my_string.count("do"))
print("occurrences of 'd' are : " , my_string.count("d"))
print("occurrences of 'o' are : " , my_string.count("o"))
Try the above examples in code editor.
Below is the program to count after certain position.
my_string="How do you do ?"
print( my_string.count("do",7,15))
This means that we want to check occurrence of the word or character after the 7th postion only. It will not count the occurrence of the word before that position.
Remember that counting starts from 0.
To understand slicing, consider the below diagram and understand how positions are calculated.
In the above example you can see that positive index (index means position of character within a string) starts from 0 and from left where as the negative index starts from "-1" and from right most character of the string
Let's jump to the function and examples to undertand how it works:
[:]
my_string="How do you do ?"
print( my_string[:])
With this , you will get you whole string back.
On the left and right of ":" , you need to provide index i.e. position of character.
One the left you need to give the index from where you want to start fetching the string and on the right you need to give the index till when you want to fetch.
Let's check the next example to understand more.
my_string="How do you do ?"
print( my_string[1:5])
The number on the left , in the above example it is 1, represent from where we need to start fetching the string and the number on the right , 5 in above example, represent position before which it should have extracted the string.
this means that [1:5] will extract data from position 1 to 4.
Notice that it includes spaces also as space is also a character.
my_string="How do you do ?"
print( my_string[1:9:2])
In the above example, one more number is introduced i.e. 2 , the number here in slice function means how many places one need to skip while fetching data or in other words one need to select every second word from string starting from 1 i.e. first it will fetch character at position 1, then 3 ,5 and so on.
Now you have understood data types, to work on the data, we need to store or structure it within python program to work with the data and apply logics on it to get the desired results.
lets understand in how many ways this data can be stored or arranged within python program.
When data is represented or you can say stored within program in between square brackets then python consider it as list
For Example:
[1,2,3,4,5]
["a","b","c","d","e"]
[1,"b",3,"c",5]
We can not just write it like above only, one has to assign this list to some variable like below:
num_list=[1,2,3,4,5]
here num_list is variable which has been assigned a list as its value
When round brackets are used for data then python consider it as Tuple
For Example:
(1,2,3,4,5)
("a","b","c","d","e")
(1,"b",3,"c",5)
When we need data to be arranged as key-value pair, python dictonary comes into picture
Data in dictonary is aranged in between curly braces
For Example:
{"name":"rohan", "age":23}
Here "name" is key and its value is "rohan"
Set in python is used to arrange data in unordered fashion as well as unique value only. This means it holds a particular value once and will not contain any duplicte value.
For Example:
ex_set = {1,2,"a",3}
Sets are also arranged in between curly braces
Looping means doing a certain task or applying a certaing logic repetedly for a finite or infinite number of times and when you create such thing it is called as a loop.
For Example:
A company wants to check salary of all employees working in IT department and suppose there are 5 employees
Salary=[100,200,150,250,300]
We can loop over this list to print salary of each employee. We don't need to write print command again and again. We will see further this in for loop type.
Let's now understand types of list
When there is a range on which we can loop then for loops are used
For Example:
salary=[100,"200",150,250,300]
for sal in salary:
print(sal)
In the above example the word "sal" in the second line is a loop variable which is declared directly within the statement which will be used to loop over the values within list. So, for the first loop or first iteration , "sal" will hold the first element of the list and for second iteration , it will hold second element of the list and so on.
When we have only conditions to iterate over and dont have any range then while loops are preferred
While Loop continues to execute until a given condition is satisfied . It is not used to iteratewhen we have a range or elements to iterate over like in For Loop.
For Example:
count=0
while count < 5:
print(count)
count=count+1
Lets take one more example with else statement:
count=0
while count < 5:
print(count)
count=count+1
else:
print( "maximum limit has reached")
In the above example,we have added else statement which will be executed once while statement condition gets false.
We can perform nested operations on loop when we have loops inside another loop
Now you have understood loop, lets understand in how many ways we can control a loop which are also called loop control statements.
When we want to exit the loop after certain condition is met then we can use break statement within our loop.
Break statement will stop the loop iteration and the loop will not continue for rest of its itertion. The program outside and after the loop will be executed.
Break statement to be placed at a position where we want to break the loop.
Example:
count=0
fruit='banana'
while count < 5:
print(count)
count=count+1
if (fruit=='apple'):
print("fruit is apple, exiting the loop")
break
print( "maximum limit has reached")
print( "we are out of the loop")
In the above example, the program will break the loop if fruit is apple and will not perform any task within that loop and continue with other tasks outside that loop if any.
"Continue" statement is used when we do not want to break the loop but we want to jump to next iteration of the same loop but statements after continue won't be executed once "continue" statement is executed.
Consider the below example to understand this:
count=0
while count < 5:
count=count+1
if (count==3):
print("moving to next iteration")
continue
print(count)
print( "we are out of the loop")
When count reaches to 3, the statement will not print the count as it is after continue statement but the next iteration will start and it will execute the statements in order
Try this in the editor and explore
It is a mathematical series introduced by Italian mathematician "Fibonacci".
Let's understand what is the series :
0,1,1,2,3,5,8,13...
It starts with 0 and the next number is 1. These numbers are fixed at first two positions. The next number is the sum of previous two numbers.
This means that the third number would be : 0 + 1 =1
Fourth number would be sum of previous two numbers i.e. sum of second and third number:
1 + 1 = 2
In this way the series will go on.
Let's try to achieve this series with python program:
a=0
b=1
for i in range(9):
if (i==0 or i==1):
print(i)
else:
c=a+b
print(c)
a=b
b=c
This is an iterative loop method. There are other methods also which we will study later in the advance course.
We have used range function within for loop. "range()" is an inbuilt python function.
"range(9)" will run for 9 iteration i.e. from 0 to 8. This means , variable "i" will start from 0 till 8 i.e. total 9 iterations.