Basics of Python Programming

       Basic topics you will learn here are ๐Ÿ‘‡๐Ÿ‘‡ 

Features of  Python
Writing & Executing a program
Literals 
Variables & Identifiers
Data Types
Input & Output Operations
Comments
Indentation
Operators
Expressions &
 order of Evaluations

 Features of Python:

1. Unsophisticated : 

It is an unsophisticated language. It allows the user to write the programs without following the strict rules viz., declaring the variable data types, usage of curly braces etc. It allows the programmer to provide the solution program rather than focusing on the structure and syntax.

 2. Easy :

Learning of Python programming language is very easy for the beginners also. Python is a Free and Open Source Software. This is software given by the FLOSS community to share the knowledge.

3. High-level :

The programmer need not worry about various low-level details required for the program. Python is understood as a high-level, interpreted general-purpose language. This means it is not your straight compiled language (like Java or C) but an interpreted dynamic language that has to be run in the given system using another program instead of its local processor.

4. Portable :

 The Python is a platform independent programming language. With the Byte code, the Python Program can be executed by any platform and hence the Python programs are portable. 

5. Interpreted : 

The Python programs can be directly executed from the Byte code. The Byte code is an executable code but it is an interpreted code. It translates the original source code into platform independent code. 

6. Object Oriented  : 

Python supports all the principles of object-oriented programming. The Python programs can be designed around the objects which concentrate on the data. Implementing various OOPs principles in Python is simple than compared to C++ or Java.

7 . Extensibility : 

These programs are extensible to C, C++ and Java. These programs can be executed by the Python. In this case, the programs can be treated as disabled codes.

 8. Embeddable : 

The scripting feature can be provided by embedding the Python program in to C or C++ programs.   

   9. Extensive Libraries :

The Python consists of huge standard library for handling regular expressions, threading, GUI etc

See the source image
Features of python 

Merits & Demerits :

See the source image
Merits and Demerits

Writing and Executing First Python Program:

When programming in Python, you have two basic options for running code : interactive mode and script mode . 

Interactive Mode: 

  Interactive mode is great for quickly and conveniently running single lines or blocks of code. Here's an example using the python shell that comes with a basic python installation. The “>>>” indicates that the shell is ready to accept interactive commands. Open the Python Interactive Mode. 

Enter the following code and press Enter, the message “Hello World” will display in the next line. 

Script Mode:

 If instead you are working with more than a few lines of code, or you‟re ready to write an actual program, script mode is what you need. Instead of having to run one line or block of code at a time, you can type up all your code in one text file, or script, and run all the code at once.

Step 1: Open notepad and type the following line
Step 2: Save the file as Hello.py
Step 3: Click Start->run->cmd->PythonProgramdirectory->python Hello.py

 Constants

A constant is a type of variable whose value cannot be changed. It is helpful to think of constants as containers that hold information which cannot be changed later.

 Literals :

Literal is a raw data given in a variable or constant. In Python, there are various types of literals they are as follows: 

  • Numeric Literals 
  • String Literals
  •  Boolean Literals
  • Special Literals  
  • Literal Collections                                                                                                                         

Numeric Literals:

Numeric Literals are immutable (unchangeable). Numeric literals can belong to 3 different numerical types: Integer, Float, and Complex.

a = 0b1010 #Binary Literals
b = 100 #Decimal Literal 
c = 0o310 #Octal Literal
d = 0x12c #Hexadecimal Literal     
#Float Literal
float_1 = 10.5 
float_2 = 1.5e2
#Complex Literal 
x = 3.14j
print(a, b, c, d)
print(float_1, float_2)
print(x, x.imag, x.real)

String Literals :

A string literal is a sequence of characters surrounded by quotes. We can use both single, double, or triple quotes for a string. And, a character literal is a single character surrounded by single or double quotes. strings = "This is Python"

char = "C"
multiline_str = """ string with more than one line code."""
unicode = u"\u00dcnic\u00f6de"
raw_str = r"raw \n string"
print(strings)
print(char)
print(multiline_str)
print(unicode)
print(raw_str)

Boolean Literals :

A Boolean literal can have any of the two values: True or False.

x = (1 == True)
y = (1 == False)
a = True + 4
b = False + 10
print("x is", x)
print("y is", y)
print("a:", a)
print("b:", b)

Special Literals :

Python contains one special literal i.e. None. We use it to specify that the field has not been created.

drink = "Available"
food = None
def menu(x):
 if x == drink:
 print(drink)
 else:
 print(food)
menu(drink)
menu(food)

Literal Collections :

There are four different literal collections List literals, Tuple literals, Dict literals, and Set literals.

fruits = ["apple", "mango", "orange"] #list
numbers = (1, 2, 3) #tuple
alphabets = {'a':'apple', 'b':'ball', 'c':'cat'} #dictionary
vowels = {'a', 'e', 'i' , 'o', 'u'} #set
print(fruits)
print(numbers)
print(alphabets)
print(vowels)

 Variables

In Python, variables can be initialized without declaration. Based on the value of the input data, the type of the variable will be automatically considered. A variable name should start with a letter followed by sequence of letters, numbers or underscore (_) special character. Integer data, floating point data and string data will be considered as primitive data type. Character data will be considered as string data with length 1.

>>> a=65
>>>a
65

 In Python, the string data will be considered as an array. The array index will start from 0.

>>> a='chapter-2'
>>> a
'chapter-2'
>>> a[1]
'h'

For string data, „+‟ represents the concatenation operation and „*‟ represents the repetition operation.
>>> a=('ha'+'i')
>>> a
'hai'
>>> a=('ha'*2)
>>> a
'haha'
Other than the primitive variables, Python also supports the following variables.

 Tuples: 

It is a list with a fixed number of elements. It uses parentheses for specification of data.

>>> x=(4,5,6)
>>> x[0]
4
>>> x[1]
5
>>> x[-1]
6
>>> x[2]
6

 The index „-1‟ represents the last element in the tuple. In case of tuple variable, the change of the values is not permitted. Lists: It is different than tuple. A list without a fixed number of elements. It uses square brackets for specification of data. The change of values of a list variable is allowed.                         
>>> x=[4,5,6]
>>> x[1]
5
>>> x[-1]
6
>>> x[2]
6
>>> x[0]=10
>>> x
[10, 5, 6]

Dictionaries: 

It is a variable used to maintain multiple typed elements. It uses curly braces for specification of data. It maintains the data by using {key:value,…} format. Multiple entries will be separated by the comma operator. The change of values is allowed.
>>> x={1:'a',2:2,3:5.8}
>>> x
{1: 'a', 2: 2, 3: 5.8}
>>> x[1]
'a'
>>> x[3]
5.8
>>> x[1]='b'
>>> x
{1: 'b', 2: 2, 3: 5.8}

 Identifiers

The identifier represents the names used in the Python program. The length of the identifier can be varied from one to another. The rules for validating the identifier are listed below.
  •  The identifier can be a combination of various elements viz., uppercase letters, lowercase letters, digits and underscore. 
  • Any one of the keyword is not permitted to act as identifier.
  • The first letter of the identifier should not be a digit. 
  •  Special alphabets viz., !,@,# etc… are also not permitted to be a part of identifier.

Data Types: 

In Python programming language, the data can be maintained by variables. The type of the variable represents the value stored within the variable. Type inferencing is allowed in Python. So, the general keywords like “int”, “float” etc. are not required for the variable.

See the source image
In Python, “type” keyword is used to get the data type assigned to the input data.
>>> type(100)
<class 'int'>
>>> type(15.27)
<class 'float'>
>>> type('abcd')
<class 'str'>

The “bool” data type contains two possible values viz., “True” and “False”
>>> bool
<class 'bool'>

The “False” value can be considered in any one of the following cases. 
  • If the value is “None” .
  • If the value is “0” or “0.0” .
  • If the input value is empty list, tuple or string.
>>> bool('a')
True
>>> bool('')
False

Input & Output  Operation:

 input ( ) : This function first takes the input from the user and then evaluates the expression, which means Python automatically identifies whether user entered a string or a number or list. If the input provided is not correct then either syntax error or exception is raised by python. For example
 # Python program showing 
# a use of input() 
val = input("Enter your value: ") 
print(val)
print ( ) : This is the output operation used in python . The string which we can write in this function displays  in the output prompt.
#print(" This is your output")

Comments: 

In Python, the comments can be specified in any one of the following two ways. They are
  •  “#” is used to represent the single line comment. 
  •  Multiple line comment statements are started and ended with the '''   ''' delimeter.

Indentation:

In Python programming language, group of code or statements are arranged in an individual block. Each block can be separated with the indentation.

Block1    

        Block2     

            Block3

         Block2 

Block1  

 Structure blocks in Python with indentation๐Ÿ‘†๐Ÿ‘†

Operators

The Python programming language supports the following operators.

See the source image
Operators

Arithmetic Operators :

The arithmetic operators are used to perform the arithmetic operations between any two operands. Various arithmetic operators are 

  •  The „+‟ operator is used to perform the addition operation between the two input data values. 
  • The „-‟ operator is used to perform the subtraction operation between the two input data values. 
  • The „*‟ operator is used to perform the multiplication operation between the two input data values.
  • The „/‟ operator is used to perform the division operation between the two input data values. 
  • The „%‟ operator is used to return the remainder of the division operation performed between the two input data values. 
  • The „**‟ operator is used to compute the exponential calculation.
  •  The „//‟ operator is used to perform the floor division operation between the two input data values. It returns the quotient of the division operation. The decimal points in the quotient result will be removed. If any one of the input is negative then the quotient result is rounded towards negative infinity. For example the two numbers considered are 20 and 10 then the result of

a-b = 10
a+b = 30
a*b = 200
a/b = 2
a%b = 0 (remainder is 0)
a**2 = 400 (202)

-a//b = -2 (a is negative, so the quotient will be rounded to towards negative infinity)


Comparison (Relational) Operators :

These operators are used to estimate the relation between the given two input values. Various relational operators are

  • The „==‟ operator is used to compare the two given input values whether they are equal or not. It returns True when both are equal otherwise it returns False.
  • The „!=‟ operator is used to compare the two given input values whether they are equal or not. It returns True when both are not equal otherwise it returns False.
  • The „>‟ operator is used to compare the two given input values whether the left side value is greater than right side value or not. It returns True if the left side value is greater than the other value otherwise it returns False. 
  • The „<‟ operator is used to compare the two given input values whether the left side value is less than right side value or not. It returns True if the left side value is less than the other value otherwise it returns False.
  • The „>=‟ operator is used to compare the two given input values whether the left side value is greater than or equal to right side value or not. It returns True if the left side value is greater than or equal to the other value otherwise it returns False.
  • The „<=‟ operator is used to compare the two given input values whether the left side value is less than or equal to right side value or not. It returns True if the left side value is less than or equal to the other value otherwise it returns False.

For example the two numbers considered are 20 and 10 then the result of

(a==b) → False

(a!=b) → True

(a>b) → True

(a<b) → False

(a>=b) → True

(a<=b) → False

Assignment Operators :

 The assignment operator is used to assign the input value to the variable. The assignment operator can be grouped with the arithmetic operators and are called as compound assignment operators. Various assignment operators are

  •  The „=‟ operator is used to assign the input value (right side value) to the variable (left side variable).
  •  The „+=‟ is used to add the right side value and the left side value and assigns the result to the left side variable. 
  • The „-=‟ is used to subtract the right side value and the left side value and assigns the result to the left side variable. 
  • The „*=‟ is used to multiply the right side value and the left side value and assigns the result to the left side variable. 
  • The „/=‟ is used to divide the right side value and the left side value and assigns the result to the left side variable. 
  • The „*=‟ is used to compute the exponential of the right side value and the left side value and assigns the result to the left side variable. 
  • The „+=‟ is used to compute the floor division of the right side value and the left side value and assigns the result to the left side variable. 

The results of the following operators are 

(a=20) → value of a is 20

(a=20), (a+=10) → value of a is 30 

(a=20), (a-=10) → value of a is 10 

(a=20), (a*=10) → value of a is 200

(a=20), (a/=10) → value of a is 2

(a=20), (a**=2) → value of a is 400

(a=20), (a//=10) → value of a is -2

Logical Operators :

 The logical relation between two input values is computed by the logical operators. Various logical operators are 

  • The „and‟ is called as Logical AND operator. It returns True only when both the inputs are True.
  • The „or‟ is called as Logical OR operator. It returns True when at least one of input is True. 
  • The „not‟ is called as Logical NOT operator. It returns the negativity of the input value.   For example, if two input numbers a and b are 1 and 0 then the results of the following operations are

(a and b) → False
(a or b) → True
(not (a)) → False

Bitwise Operators :

The bitwise operators works on bit by bit of the input data value. For each value, the 8 bit ASCII code will be considered and on these bits, the following operations are performed. 
  • The „&‟ is called as binary AND operation. It will select the resultant bit to True only when the corresponding two input bit values are True otherwise it is False.
  • The „|‟ is called as binary OR operation. It will select the resultant bit to True when at least one of the corresponding two input bit values are True otherwise it is False. 
  • The „^‟ is called as binary XOR operation. It will select the resultant bit to True only when the corresponding two input bit values are different otherwise it is False. 
  • The „~‟ is called as binary ones complement operation. It will set the resultant bit to the complemented input bit value. 
  • The „<<‟ is called as binary Left Shift Operation. It will left shift the left side value. The right side value will specify the required number of shift operations. 
  • The „>>‟ is called as binary Right Shift Operation. It will right shift the left side value. The right side value will specify the required number of shift operations.
For example, if the two numbers considered are a=101 b=011. The results of the following operations are
(a&b) → 001
(a|b) → 111
(a^b) → 110
(~a) → 010

Membership Operators :

 The membership operators in Python are used for strings, lists or tuples. They focus to test the membership in the sequence. Various operators are
  • The „in‟ operator is used to search the input element in the sequence. If it is found then returns true otherwise returns false. 
  • The „not in‟ operator is used to search the input element in the sequence. If it is not found then returns true otherwise returns false
x=(1,2,3)
y=2 
a=(y in x)
print("in operator result=",a)
b=(y not in x)
print("not in operator result=",b)

Output:
in operator result= True
not in operator result= False


Identity Operators:

 The identity operators are used to evaluate whether the given two objects points to the same memory location or not. Various operators are 
  • The „is‟ operator is used to return true if both objects points to the same memory location otherwise it returns false.
  • The „is not‟ operator is used to return true if both objects are not pointing to the same memory location otherwise it returns false.
x=(1,2,3)
y=2 
a=(y is x)
print("is operator result=",a)
b=(y is not x) 
print("not is operator result=",b)                                             
#Output:
is operator result= False
not is operator result= True

Expressions and Order of Evaluations :

 Atom is a basic element of Python expression. An atom can be an identifier or literal. An Atom also consists of various forms enclosed in brackets, parentheses or braces. Name is an atom representing an identifier. Both the Byte and String literals are allowed in Python. Multiple expressions are separated by comma operator in a parenthesized form. The expressions re evaluated based on the following Table.

Operator Precedence

In the ๐Ÿ‘† table you will observe the precedence and Associativity of python operators.Operator Precedence is used in an expression with more than one operator with different precedence to determine which operation to perform first.Operator Associativity means If an expression contains two or more operators with the same precedence then Operator Associativity is used to determine. It can either be Left to Right or from Right to Left.

















Comments