PYTHON LANGUAGE
Developed by Guido Van Rossum , Python is the most trending language across the globe , its efficiency and excellent framework has attracted many programmers specially in the field of data analysis.
Syntax & Basics
-
When we give a computer a set of instructions, we say that we're programming it.
-
Syntax : Syntax mean a set of rules to be followed while writing the instructions.
-
Variable : Variable is a named storage container (memory location) used to hold values while executing the program. For eg- a=5, here a is a variable holding 5 as value.
-
Identifier: Identifiers are the name given to elements to be used in program such as variable, functions, modules etc. Identifiers must begin with an alphabet (A-Z) or underscore(_), can contain digits(0-9) and should not contain space or any other special character.
-
Data Type: It holds the type of value a variable holds and what type of operations can be performed on it. For eg.- Maths operations (like +, -) cannot be performed on a textual value.
Following are the categories of data types in python:-
Text - str example: "Delhi", 'F-10B'. They are enclosed in quotes.
-
Numeric - int, float, complex example: 56, -96.51, 2+3i respectively.
-
Sequence - list, tuple example: [2,5,8], (34,89,7) respectively.
-
Mapping - Dictionary example: {"Rno":12,"Name":"Pihu"}
-
-
Functions: Functions are collection of statements grouped under a name and code is executed only when function is called. Certain values can be passed as parameters while calling them.
-
Built-in functions: They are ready to use functions which provide great ease into doing a complex job. example : len("Python") will return 6 (no. of characters).
-
User defined: They are defined by the programmer. They are made using def statement.
-
Handling Input and Output
Python print()
Used to display provided data on the screen.
print() parameters:
-
sep - Used to separate the objects while printing. Default is space(' ' ).
-
end - It is printed at the last. Default is new line ('\n').
Python input()
Used to prompt user to enter value. By default, it will accept string value.
int() function is used convert the string input into integer so that arithmetic operations can be performed.
Code
Output
Code
Output
Data Types
Variables are storage containers which can be referred by user defined name. Variable value can be changed during anytime of the program depending upon the condition or information passed.
For ex. a=5, here a is a variable holding 5 as value.
Data Type specifies the type of data a variable is going to hold. Data can be of many types eg. integer, decimal numbers, alphanumeric, sequence of values etc.
Let us learn how to process different types of data in Python.
In Python, variable are not required to be associated with a particular data type when declared. Rather it can also change the data type as and when required.
For example:
>>>x=10 #Variable x declared of integer type
>>>type(x)
>>><class 'int'>
>>>x="India" # Variable x data type is changed to string
>>>type(x)
>>><class 'str'>
Types of Data Types
To write a good program you must know how to choose a perfect data type to make program efficient. Let us learn these Data types in detail
Numeric Data Type
-
Integer: It consists of whole numbers, means non fractional numbers. It can be signed or unsigned both ex. marks=20, Rno=12, x=-4
-
float: float is used to store numbers with decimals. Even if you store integer 9 in float type then it will be stored as 9.0 ex. weight=56.8, y=-10.5
-
complex: Complex number system has two parts a real and an imaginary number. You might study this concept in higher classes. ex. distance=2+1j
Boolean Data Type
-
Boolean data type represents truth value i.e. True or False. 1 and 0 can also be used in place of True and False respectively. ex. state=False
Dictionary Data Type
-
Dictionary is an unordered set of comma separated key : value pairs. Dictionary is declared in {} and each key should be a unique though values can repeat.
ex. medals={'TeamA':25, 'TeamB':32, 'TeamC':14}
Sequence Data Type
-
String: A string can hold any type of data such as letters, numbers, special characters. Strings are enclosed in single quotes (' ') or double quotes (" ").
ex. Houseno='B-19', name='Neer'
-
List: List is a compound data type, which holds group of values separated by comma (,). List is declared using square brackets [ ] and can contain value of any data type.
ex. student=[12,'Niyasa','60.5'], vowels=['a','e','i','o','u'], marks=[21, 20, 17, 24]
-
Tuple: Tuple is also like list with a difference that they cannot be changed/modified. Tuple is declared using round brackets ( )
ex. days=('Mon', 'Tue', 'Wed')
Indexing
We just talked about the sequence data type, but did you wonder, how are you going to access individual element from them. In sequence data types (string, list or tuple), each element is assigned with a serial number called index. In python, index begins with 0 in case of forward indexing and -1 in backward indexing.
Reading string1 from the given example:
>>> print(string1)
>>>PYTHONFORALL
>>>print(string1[4])
>>>'O'
>>>print(string1[-4])
>>>'R'
Reading list1 from the given example:
>>> print(list1)
>>>[15, 20, 4.5, 'H']
>>>print(list1[0])
>>>15
>>>print(list1[-1])
>>>'H'
Operators
Operator is a character or a symbol that represents a specific mathematical or logical action or process. Operators are used to perform operations on variables and values. For example: * returns product when applied on two numbers and > tells us which value is greater. In Python, we have different types of operators. Let us discuss them in detail.
Types of Operators
1. Arithmetic Operators
Arithmetical Operators are use to perform mathematical operations and returns calculated result. These operators work with numeric data type and math's rule BODMAS is also applied here.
Code
Output
2. Relational Operators
Relational Operators are used to determine the relation between the two values. They are also called comparison operators and returns True if the comparison is true otherwise returns False if the comparison is false. Relational Operators will always return a boolean value i.e. True or False.
3. Augmented Assignment Operators
Augmented assignment operators are the combination of assignment (=) operator with arithmetic operators (+ - * / % // **).
For example: x=x+5, can be written as x+=5.
Let us read all examples assuming value of variable x as 5.
4. Logical Operators
Logical Operators are basically used to connect two or more expressions with relational operators. These operators are used to create complex Boolean expressions. and, or, not are three logical operators offered by Python.
Before, we start with the examples here, we need to understand Truth Value Testing. It is a common way to show logical relationships between the expressions. Assuming x and y as expressions, see how logical operators work with them.
x and y
not x
x or y
Operator Precedence
Since, you have learnt about so many operator by now, little confusion might arise while using multiple operators together which one should be evaluated first. As BODMAS, covers only few arithmetic operators, but here we have so many other as well.
For example:
Try to evaluate this expression -
>>>17>8+2**4 and 9//2>=4
Solution -
>>>17>8+16 and 4>=4 #Here ** got the highest precedence
>>>False and True
>>> True
Let us know the order of precedence for all operators in Highest to Lowest order:
Data Type Conversions
When Python is dealing with an expression of mixed data types, then it internally converts the data type to another data type, usually higher to avoid data loss. This is known as implicit conversion.
For example:
>>> 8.5+2 #adding a float and int
>>> 10.5 # returns float, means internally 2 was considered as 2.0
This process do not need any user involvement.
Explicit type conversion or Type Casting
An explicit conversion means a user defined conversion, where user uses any of the given conversion function to convert the value in a desired format.
-
int() function is used convert the string input into integer so that arithmetic operations can be performed.
-
float() method is used convert the object input into float.
-
str() method is used to convert the object into string type.
-
The chr() method converts an integer to its Unicode character and returns it.
-
bool() method coverts a given value into a boolean value i.e. True or False
-
The type() method displays the data type of the object passed.