Skip to main content

Python

Python Introduction

  1. Python is a general-purpose high-level programming language, interpreted, interactive and object-oriented scripting language.
  2. Python was developed by Guido van Rossum in the late eighties and early nineties (Feb 20th 1991) at the National Research Institute for Mathematics and Computer Science in the Netherlands.
  3. The name Python was selected from the TV Show “Monty Python’s Flying Circus”, which was broadcasted in BBC from 1969 to 1974.
  4. Python is recommended as first programming language for beginners.
Guido developed Python language by taking almost all programming features from different languages
  1. Functional Programming Features from C & ABC (Most of syntax in Python Derived from C and ABC languages.)
  2. Object Oriented Programming Features from C++
  3. Scripting Language Features from Perl and Shell Script
  4. Modular Programming Features from Modula-3

Applications: – Where we can use Python:

We can use everywhere. The most common important application areas are

  1. Desktop based Applications
  2. Web based Applications
  3. Databased Applications
  4. Network based Applications
  5. Gaming Applications
  6. Data Science Applications
  7. Artificial Intelligence Applications
  8. Machine Learning Applications
  9. Deep Learning Applications
  10. Data Analytics Applications
  11. Neural Network Applications
  12. Natural Language Processing Applications
  13. Robotic Applications
  14. IOT Applications
Note:
  1. Internally Google and Youtube use Python coding
  2. NASA and Nework Stock Exchange Applications developed by Python.
  3. Top Software companies like Google, Microsoft, IBM, Yahoo using Python.

Features of Python:

  1. Simple and easy to learn: Python is a simple programming language. When we read Python program,we can feel like reading english statements. The syntaxes are very simple and only 30+ kerywords are available. When compared with other languages, we can write programs with very less number of lines. Hence more readability and simplicity. We can reduce development and cost of the project.
  2. Freeware and Open Source: We can use Python software without any licence and it is freeware. Its source code is open,so that we can we can customize based on our requirement. Eg: Jython is customized version of Python to work with Java Applications.
  3. High Level Programming language: Python is high level programming language and hence it is programmer friendly language. Being a programmer we are not required to concentrate low level activities like memory management and security etc..
  4. Platform Independent: Once we write a Python program,it can run on any platform without rewriting once again. Internally PVM is responsible to convert into machine understandable form.
  5. Portability: Python programs are portable. ie we can migrate from one platform to another platform very easily. Python programs will provide same results on any paltform.
  6. Dynamically Typed: In Python we are not required to declare type for variables. Whenever we are assigning the value, based on value, type will be allocated automatically.Hence Python is considered as dynamically typed language. But Java, C etc are Statically Typed Languages b’z we have to provide type at the beginning only. This dynamic typing nature will provide more flexibility to the programmer.
  7. Both Procedure Oriented and Object Oriented: Python language supports both Procedure oriented (like C, pascal etc) and object oriented (like C++, Java) features. Hence, we can get benefits of both like security and reusability etc
  8. Interpreted: We are not required to compile Python programs explcitly. Internally Python interpreter will take care that compilation. If compilation fails interpreter raised syntax errors. Once compilation success then PVM (Python Virtual Machine) is responsible to execute.
  9. Extensible: We can use other language programs in Python. The main advantages of this approach are: We can use already existing legacy non-Python code, We can improve performance of the application
  10. Embedded: We can use Python programs in any other language programs. i.e we can embedd Python programs anywhere.
  11. Extensive Library: Python has a rich inbuilt library. Being a programmer we can use this library directly and we are not responsible to implement the functionality. etc…

Limitations of Python:

  1. Performance wise not up to the mark b’z it is interpreted language.
  2. Not using for mobile Applications

Flavors of Python:

  1. CPython: It is the standard flavor of Python. It can be used to work with C lanugage Applications
  2. Jython or JPython: It is for Java Applications. It can run on JVM
  3. IronPython: It is for C#.Net platform
  4. PyPy: The main advantage of PyPy is performance will be improved because JIT compiler is available inside PVM.
  5. RubyPython For Ruby Platforms
  6. CondaPython It is specially designed for handling large volume of data processing.

Python Versions:

  1. Python 1.0V introduced in Jan 1994
  2. Python 2.0V introduced in October 2000
  3. Python 3.0V introduced in December 2008

Note: Python 3 won’t provide backward compatibility to Python 2 i.e there is no guarantee that Python 2 programs will run in Python3. Current version: Python 3.8.1

 

To Print “Hello World” in C Programming Language:

  1. #include<stdio.h>
  2. #include<conio.h>
  3. void main()
  4. {
  5. clrscr();
  6. printf(“Hello World”);
  7. getch();
  8. }
  9. Save the Code with .c extension, compile and run the code

To Print “Hello World” in JAVA Programming Language:

  1. class Hello
  2. {
  3. public static void main(String args[])
  4. {
  5. System.out.println(“Hello world”);
  6. }
  7. }
  8. Save the code with .java extension, compile and run the code

 

# Print “Hello World” in PYTHONprint(“Hello World”)

 

Hello World

 

To Print the sum of 5 numbers in C Language

  1. #include<stdio.h>
  2. #include<conio.h>
  3. void main()
  4. {
  5. clrscr();
  6. int a = 10;
  7. int b = 20;
  8. int c = 30;
  9. int d = 40;
  10. int e = 50;
  11. int sum;
  12. sum = a+b+c+d+e;
  13. printf(“%d”, sum);
  14. getch();
  15. }

 

# Print the sum of 5 numbers in PYTHONa,b,c,d,e=10,20,30,40,50; print(a+b+c+d+e) # Swapping of 2 numbersa,b=100,200a,b = b,aprint(a)print(b) # Reverse a stringa = ‘Venkateswara Rao’a[::-1]

 

150200100

 

‘oaR arawsetakneV’

 

What is the output in C Language

  1. #include<stdio.h>
  2. include<conio.h>
  3. void main()
  4. {
  5. int a = 200*200/200;
  6. printf(“%d”,a)
  7. getch();
  8. }
Output is -127 in C Language, based on int range i.e., -32768 to +32767, but in python we don’t have a range

 

a = 9999999999999999999999999999999999999999999999999999999999999999999999print(a)

 

9999999999999999999999999999999999999999999999999999999999999999999999

 

Identifiers

  • A name in Python program is called identifier.
  • It can be class name or function name or module name or variable name.
  • a = 10 #### Rules to define identifiers in Python:
  1. The only allowed characters in Python are
    • alphabet symbols(either lower case or upper case)
    • digits(0 to 9)
    • underscore symbol(_) By mistake if we are using any other symbol like $ then we will get syntax error.
    • abc = 10
    • ab$c =20
  2. Identifier should not starts with digit
    • 123abc
    • abc123
  3. Identifiers are case sensitive. Of course Python language is case sensitive language.
    • a=10
    • A=100

Identifier:

  1. Alphabet Symbols (Either Upper case OR Lower case)
  2. If Identifier is start with Underscore (_) then it indicates it is private.
  3. Identifier should not start with Digits.
  4. Identifiers are case sensitive.
  5. We cannot use reserved words as identifiers. Eg: def=10
  6. There is no length limit for Python identifiers. But not recommended to use too lengthy identifiers.
  7. Dollor Symbol is not allowed in Python.

Note:

  1. If identifier starts with _ symbol then it indicates that it is private. Eg: _a
  2. If identifier starts with (two under score symbols) indicating that strongly private identifier. Eg: b
  3. If the identifier starts and ends with two underscore symbols then the identifier is language defined special name,which is also known as magic methods. Eg: add
    • a1 = 10 #Valid
    • _a = 10 #Valid
    • a_7 = 10 #Valid
    • 1a = 10 #Invalid
    • a%7 = 10 #Invalid
    • a 7 = 10 #Invalid

Multiple Assignment:

Python allows us to assign a value to multiple variables in a single statement which is also known as multiple assignment.
We can apply multiple assignments in two ways either by assigning a single value to multiple variables or assigning multiple values to multiple variables. Lets see given examples.

  1. Assigning single value to multiple variables Ex: x=y=z=10
  2. Assigning multiple values to multiple variables: Ex: a,b,c=10,20,30

 

Reserved Words

  1. In Python some words are reserved to represent some meaning or functionality.
  2. Such type of words are called Reserved words.
  3. There are 35 reserved words available in Python.
    • True,False,None
    • and, or ,not,is
    • if,elif,else
    • while,for,break,continue,return,in,yield
    • try,except,finally,raise,assert
    • import,from,as,class,def,pass,global,nonlocal,lambda,del,with

Note:

  1. All Reserved words in Python contain only alphabet symbols.
  2. Except the following 3 reserved words, all contain only lower case alphabet symbols i.e, True, False & None
    • Eg: a= true – invalid
    • a=True – valid

 

import keywordkeyword.kwlist

output

[‘False’, ‘None’, ‘True’, ‘and’, ‘as’, ‘assert’, ‘async’, ‘await’, ‘break’, ‘class’, ‘continue’, ‘def’, ‘del’, ‘elif’, ‘else’, ‘except’, ‘finally’, ‘for’, ‘from’, ‘global’, ‘if’, ‘import’, ‘in’, ‘is’, ‘lambda’, ‘nonlocal’, ‘not’, ‘or’, ‘pass’, ‘raise’, ‘return’, ‘try’, ‘while’, ‘with’, ‘yield’]

 

Data Types

  • Data Type represent the type of data present inside a variable.
  • In Python we are not required to specify the type explicitly. Based on value provided,the type will be assigned automatically.Hence Python is Dynamically Typed Language.
  • Python contains the following inbuilt data types
    1. int
    2. float
    3. complex
    4. bool
    5. str
    6. bytes
    7. bytearray
    8. range
    9. list
    10. tuple
    11. set
    12. frozenset
    13. dict
    14. None

Note: Python contains several inbuilt functions

  1. type() to check the type of variable
  2. id() to get address of object
  3. print() to print the value

int data type:

We can use int data type to represent whole numbers (integral values)Eg: a=10type(a) #intNote: In Python2 we have long data type to represent very large integral values.But in Python3 there is no long type explicitly and we can represent long values also by using int type only.

NOTE: All Fundamental data types in python are IMMUTABLE

We can represent int values in the following ways

  1. Decimal form
  2. Binary form
  3. Octal form
  4. Hexa decimal form
Decimal form(base-10):

It is the default number system in PythonThe allowed digits are: 0 to 9Eg: a =10

Binary form(Base-2):

The allowed digits are : 0 & 1Literal value should be prefixed with 0b or 0BEg: a = 0B1111a =0B123a=b111

Octal Form(Base-8):

The allowed digits are : 0 to 7Literal value should be prefixed with 0o or 0O.Eg: a=0o123a=0o786

Hexa Decimal Form(Base-16):

The allowed digits are : 0 to 9, a-f (both lower and upper cases are allowed)Literal value should be prefixed with 0x or 0XEg:a =0XFACEa=0XBeefa =0XBeerNote: Being a programmer we can specify literal values in decimal, binary, octal and hexa decimal forms. But PVM will always provide values only in decimal form.a=10b=0o10c=0X10d=0B10print(a)10print(b)8print(c)16print(d)2

Base Conversions

NumPy is a popular Python library used for numerical computing. It provides support for large, multi-dimensional arrays and matrices, along with a collection of mathematical functions to operate on these arrays efficiently. NumPy is widely used in scientific computing, data analysis, machine learning, and more.

Some key features of NumPy include:

  1. ndarray: NumPy’s main data structure is the ndarray, a flexible array object that can be used to represent vectors, matrices, and higher-dimensional arrays. These arrays are efficient for storing and manipulating large amounts of data.
  2. Mathematical functions: NumPy provides a wide range of mathematical functions for performing operations on arrays, such as linear algebra, statistical analysis, Fourier transforms, and more. These functions are optimized for performance and can handle large datasets efficiently.
  3. Broadcasting: NumPy allows for broadcasting, which is a powerful technique that extends the capabilities of arrays by performing operations on arrays of different shapes. This makes it easier to work with arrays of different dimensions and sizes.
  4. Integration with other libraries: NumPy integrates well with other Python libraries such as pandas, scikit-learn, and matplotlib, making it a key component of the scientific Python ecosystem.

Overall, NumPy is a versatile and powerful library that is essential for numerical computing in Python. By leveraging its array manipulation capabilities and mathematical functions, developers can efficiently perform complex calculations and data analysis tasks.