Introduction To PYTHON

07 Jul, 2022
Python is a widely used general-purpose, high level programming language. It was created by Guido van Rossum in 1991 and further developed by the Python Software Foundation. It was designed with an emphasis on code readability, and its syntax allows programmers to express their concepts in fewer lines of code.
Python is a programming language that lets you work quickly and integrate systems more efficiently.
There are two major Python versions: Python 2 and Python 3. Both are quite different.
Beginning with Python programming:
1) Finding an Interpreter:
Before we start Python programming, we need to have an interpreter to interpret and run our programs. There are certain online interpreters like https://ide.geeksforgeeks.org/ that can be used to run Python programs without installing an interpreter.
Windows: There are many interpreters available freely to run Python scripts like IDLE (Integrated Development Environment) that comes bundled with the Python software downloaded from http://python.org/.
Linux: Python comes preinstalled with popular Linux distros such as Ubuntu and Fedora. To check which version of Python you’re running, type “python” in the terminal emulator. The interpreter should start and print the version number.
macOS: Generally, Python 2.7 comes bundled with macOS. You’ll have to manually install Python 3 from http://python.org/.
2) Writing our first program:
Just type in the following code after you start the interpreter.
# Script Begins  print("GeeksQuiz")  # Scripts Ends
Output:
GeeksQuiz
Let’s analyze the script line by line.
Line 1: [# Script Begins] In Python, comments begin with a #. This statement is ignored by the interpreter and serves as documentation for our code.
Line 2: [print(“GeeksQuiz”)] To print something on the console, print() function is used. This function also adds a newline after our message is printed(unlike in C). Note that in Python 2, “print” is not a function but a keyword and therefore can be used without parentheses. However, in Python 3, it is a function and must be invoked with parentheses.
Line 3: [# Script Ends] This is just another comment like in Line 1.
Introduction to Python | Sample Video for Python Foundation Course | GeeksforGeeks - YouTubeGeeksforGeeks528K subscribersIntroduction to Python | Sample Video for Python Foundation Course | GeeksforGeeksWatch laterShareCopy linkInfoShoppingTap to unmuteIf playback doesn't begin shortly, try restarting your device.You're signed outVideos you watch may be added to the TV's watch history and influence TV recommendations. To avoid this, cancel and sign in to YouTube on your computer.CancelConfirmMore videosMore videosSwitch cameraShareInclude playlistAn error occurred while retrieving sharing information. Please try again later.Watch on0:000:000:00 / 6:16•Live•<div class="player-unavailable"><h1 class="message">An error occurred.</h1><div class="submessage"><a href="https://www.youtube.com/watch?v=KWnoiOimNbs" target="_blank">Try watching this video on www.youtube.com</a>, or enable JavaScript if it is disabled in your browser.</div></div>
Python designed by Guido van Rossum at CWI has become a widely used general-purpose, high-level programming language.
Prerequisites:
Knowledge of any programming language can be a plus.
Reason for increasing popularity
Emphasis on code readability, shorter codes, ease of writingProgrammers can express logical concepts in fewer lines of code in comparison to languages such as C++ or Java.Python supports multiple programming paradigms, like object-oriented, imperative and functional programming or procedural.There exists inbuilt functions for almost all of the frequently used concepts.Philosophy is “Simplicity is the best”.
Emphasis on code readability, shorter codes, ease of writing
Programmers can express logical concepts in fewer lines of code in comparison to languages such as C++ or Java.
Python supports multiple programming paradigms, like object-oriented, imperative and functional programming or procedural.
There exists inbuilt functions for almost all of the frequently used concepts.
Philosophy is “Simplicity is the best”.
LANGUAGE FEATURES
InterpretedThere are no separate compilation and execution steps like C and C++.Directly run the program from the source code.Internally, Python converts the source code into an intermediate form called bytecodes which is then translated into native language of specific computer to run it.No need to worry about linking and loading with libraries, etc.
There are no separate compilation and execution steps like C and C++.
Directly run the program from the source code.
Internally, Python converts the source code into an intermediate form called bytecodes which is then translated into native language of specific computer to run it.
No need to worry about linking and loading with libraries, etc.
Platform IndependentPython programs can be developed and executed on multiple operating system platforms.Python can be used on Linux, Windows, Macintosh, Solaris and many more.
Python programs can be developed and executed on multiple operating system platforms.
Python can be used on Linux, Windows, Macintosh, Solaris and many more.
Free and Open Source; Redistributable
High-level LanguageIn Python, no need to take care about low-level details such as managing the memory used by the program.
In Python, no need to take care about low-level details such as managing the memory used by the program.
SimpleCloser to English language;Easy to LearnMore emphasis on the solution to the problem rather than the syntax
Closer to English language;Easy to Learn
More emphasis on the solution to the problem rather than the syntax
EmbeddablePython can be used within C/C++ program to give scripting capabilities for the program’s users.
Python can be used within C/C++ program to give scripting capabilities for the program’s users.
Robust:Exceptional handling featuresMemory management techniques in built
Exceptional handling features
Memory management techniques in built
Rich Library SupportThe Python Standard Library is very vast.Known as the “batteries included” philosophy of Python ;It can help do various things involving regular expressions, documentation generation, unit testing, threading, databases, web browsers, CGI, email, XML, HTML, WAV files, cryptography, GUI and many more.Besides the standard library, there are various other high-quality libraries such as the Python Imaging Library which is an amazingly simple image manipulation library.
The Python Standard Library is very vast.
Known as the “batteries included” philosophy of Python ;It can help do various things involving regular expressions, documentation generation, unit testing, threading, databases, web browsers, CGI, email, XML, HTML, WAV files, cryptography, GUI and many more.
Besides the standard library, there are various other high-quality libraries such as the Python Imaging Library which is an amazingly simple image manipulation library.
Python vs JAVA
Python
Java
Dynamically Typed 
No need to declare anything. An assignment statement binds a name to an object, and the object can be of any type.
No type casting is  required when using container objects
Statically Typed
All variable names (along with their types) must be explicitly declared. Attempting to assign an object of the wrong type to a variable name triggers a type exception.
Type casting is required when using container objects.
The classical Hello World program illustrating the relative verbosity of a Java Program and Python ProgramJava Code
public class HelloWorld{   public static void main (String[] args)   {      System.out.println("Hello, world!");   }}
Python Code
print("Hello, world!")
Similarity with Java
Require some form of runtime on your system (JVM/Python runtime)
Can probably be compiled to executables without the runtime (this is situational, none of them are designed to work this way)
LOOK and FEEL of the Python
GUI
Command Line interface
Softwares making use of Python
Python has been successfully embedded in a number of software products as a scripting language.
GNU Debugger uses Python as a pretty printer to show complex structures such as C++ containers.Python has also been used in artificial intelligencePython is often used for natural language processing tasks.
GNU Debugger uses Python as a pretty printer to show complex structures such as C++ containers.
Python has also been used in artificial intelligence
Python is often used for natural language processing tasks.
Current Applications of Python
A number of Linux distributions use installers written in Python example in Ubuntu we have the UbiquityPython has seen extensive use in the information security industry, including in exploit development.Raspberry Pi– single board computer uses Python as its principal user-programming language.Python is now being used Game Development areas also.
A number of Linux distributions use installers written in Python example in Ubuntu we have the Ubiquity
Python has seen extensive use in the information security industry, including in exploit development.
Raspberry Pi– single board computer uses Python as its principal user-programming language.
Python is now being used Game Development areas also.
Pros:
Ease of useMulti-paradigm Approach
Ease of use
Multi-paradigm Approach
Cons:
Slow speed of execution compared to C,C++Absence from mobile computing and browsersFor the C,C++ programmers switching to python can be irritating as the language requires proper indentation of code. Certain variable names commonly used like sum are functions in python. So C, C++ programmers have to look out for these.
Slow speed of execution compared to C,C++
Absence from mobile computing and browsers
For the C,C++ programmers switching to python can be irritating as the language requires proper indentation of code. Certain variable names commonly used like sum are functions in python. So C, C++ programmers have to look out for these.
Industrial Importance
Most of the companies are now looking for candidates who know about Python Programming. Those having the knowledge of python may have more chances of impressing the interviewing panel. So I would suggest that beginners should start learning python and excel in it.
Python is a high-level, interpreted, and general-purpose dynamic programming language that focuses on code readability. It has fewer steps when compared to Java and C. It was founded in 1991 by developer Guido Van Rossum. Python ranks among the most popular and fastest-growing languages in the world. Python is a powerful, flexible, and easy-to-use language. In addition, the community is very active there. It is used in many organizations as it supports multiple programming paradigms. It also performs automatic memory management. 
Presence of third-party modules Extensive support libraries(NumPy for numerical calculations, Pandas for data analytics etc) Open source and community development Versatile, Easy to read, learn and writeUser-friendly data structures High-level language Dynamically typed language(No need to mention data type based on the value assigned, it takes data type) Object-oriented language Portable and InteractiveIdeal for prototypes – provide more functionality with less codingHighly Efficient(Python’s clean object-oriented design provides enhanced process control, and the language is equipped with excellent text processing and integration capabilities, as well as its own unit testing framework, which makes it more efficient.)(IoT)Internet of Things OpportunitiesInterpreted LanguagePortable across Operating systems 
Presence of third-party modules 
Extensive support libraries(NumPy for numerical calculations, Pandas for data analytics etc) 
Open source and community development 
Versatile, Easy to read, learn and write
User-friendly data structures 
High-level language 
Dynamically typed language(No need to mention data type based on the value assigned, it takes data type) 
Object-oriented language 
Portable and Interactive
Ideal for prototypes – provide more functionality with less coding
Highly Efficient(Python’s clean object-oriented design provides enhanced process control, and the language is equipped with excellent text processing and integration capabilities, as well as its own unit testing framework, which makes it more efficient.)
(IoT)Internet of Things Opportunities
Interpreted Language
Portable across Operating systems 
 
GUI based desktop applicationsGraphic design, image processing applications, Games, and Scientific/ computational ApplicationsWeb frameworks and applications  Enterprise and Business applications  Operating Systems EducationDatabase AccessLanguage Development  Prototyping Software Development 
GUI based desktop applications
Graphic design, image processing applications, Games, and Scientific/ computational Applications
Web frameworks and applications 
 Enterprise and Business applications 
 Operating Systems 
Education
Database Access
Language Development 
 Prototyping 
Software Development 
Organizations using Python : 
Google(Components of Google spider and Search Engine) Yahoo(Maps) YouTube Mozilla Dropbox Microsoft Cisco Spotify Quora  
Google(Components of Google spider and Search Engine) 
Yahoo(Maps) 
YouTube 
Mozilla 
Dropbox 
Microsoft 
Cisco 
Spotify 
Quora  
 
So before moving on further.. let’s do the most popular ‘HelloWorld’ tradition  and hence compare Python’s Syntax with C, C++, Java ( I have taken these 3 because they are most famous and mostly used languages).
# Python code for "Hello World"# nothing else to type...see how simple is the syntax.  print("Hello World")      
Note: Please note that Python for its scope doesn’t depend on the braces ( { } ), instead it uses indentation for its scope.Now moving on further Lets start our basics of Python . I will be covering the basics in some small sections. Just go through them and trust me you’ll learn the basics of Python very easily.
Introduction and Setup
If you are on Windows OS download Python by Clicking here and now install from the setup and in the start menu type IDLE.IDLE, you can think it as an Python’s IDE to run the Python Scripts.It will look somehow this :If you are on Linux/Unix-like just open the terminal and on 99% linux OS Python comes preinstalled with the OS.Just type ‘python3’ in terminal and you are ready to go.It will look like this :The ” >>> ” represents the python shell and its ready to take python commands and code.Variables and Data StructuresIn other programming languages like C, C++, and Java, you will need to declare the type of variables but in Python you don’t need to do that. Just type in the variable and when values will be given to it, then it will automatically know whether the value given would be an int, float, or char or even a String.# Python program to declare variablesmyNumber = 3print(myNumber)  myNumber2 = 4.5print(myNumber2)  myNumber ="helloworld"print(myNumber)Output:3
4.5
helloworld
See, how simple is it, just create a variable and assign it any value you want and then use the print function to print it. Python have 4 types of built in Data Structures namely List, Dictionary, Tuple and Set.List is the most basic Data Structure in python. List is a mutable data structure i.e items can be added to list later after the list creation. It’s like you are going to shop at the local market and made a list of some items and later on you can add more and more items to the list.append() function is used to add data to the list.# Python program to illustrate a list   # creates a empty listnums = []   # appending data in listnums.append(21)nums.append(40.5)nums.append("String")  print(nums)Output:[21, 40.5, String]Comments:# is used for single line comment in Python
""" this is a comment """ is used for multi line commentsInput and OutputIn this section, we will learn how to take input from the user and hence manipulate it or simply display it. input() function is used to take input from the user.# Python program to illustrate# getting input from username = input("Enter your name: ")   # user entered the name 'harssh'print("hello", name)Output:hello harssh   # Python3 program to get input from user  # accepting integer from the user# the return type of input() function is string ,# so we need to convert the input to integernum1 = int(input("Enter num1: "))num2 = int(input("Enter num2: "))  num3 = num1 * num2print("Product is: ", num3)Output:Enter num1: 8 Enter num2: 6 ('Product is: ', 48)
SelectionSelection in Python is made using the two keywords ‘if’ and ‘elif’ and else (elseif)# Python program to illustrate# selection statement  num1 = 34if(num1>12):    print("Num1 is good")elif(num1>35):    print("Num2 is not gooooo....")else:    print("Num2 is great")Output:Num1 is goodFunctionsYou can think of functions like a bunch of code that is intended to do a particular task in the whole Python script. Python used the keyword ‘def’ to define a function.Syntax:def function-name(arguments):
            #function body# Python program to illustrate# functionsdef hello():    print("hello")    print("hello again")hello()  # calling functionhello()               Output:hello
hello again
hello
hello again
Now as we know any program starts from a ‘main’ function...lets create a main function like in many other programming languages.# Python program to illustrate # function with maindef getInteger():    result = int(input("Enter integer: "))    return result  def Main():    print("Started")      # calling the getInteger function and     # storing its returned value in the output variable    output = getInteger()         print(output)  # now we are required to tell Python # for 'Main' function existenceif __name__=="__main__":    Main()Output:Started
Enter integer: 5
Iteration (Looping)As the name suggests it calls repeating things again and again. We will use the most popular ‘for’ loop here.# Python program to illustrate# a simple for loop  for step in range(5):        print(step)Output:0
1
2
3
4
ModulesPython has a very rich module library that has several functions to do many tasks. You can read more about Python’s standard library by Clicking here‘import’ keyword is used to import a particular module into your python code. For instance consider the following program.# Python program to illustrate# math moduleimport math  def Main():    num = -85      # fabs is used to get the absolute     # value of a decimal    num = math.fabs(num)     print(num)            if __name__=="__main__":    Main()Output:85.0Related CoursesPython Programming Foundation -Self Paced CourseNew to the programming world, don’t know where to start? Start with beginner-friendly Python Programming Foundation -Self Paced Course designed for absolute beginners who wish to kickstart and build their foundations in Python programming language. Learn Python basics, Variables & Data types, Operators etc and learn how to solve coding problems efficiently in Python. Don’t wait, sign up now and kickstart your Python journey today.DS Using Python Programming – Self Paced CourseIf you’re curious to upgrade your Python skills, you’ve come to the right platform! In this DS Using Python Programming – Self Paced Course, designed for Python enthusiasts where you’ll be guided by the leading industry experts who will explain in-depth, and efficient methods to implement data structures such as heaps, stacks, and linked lists etc. So, what are you waiting for? Advance your Python skills today.My Personal Notes
arrow_drop_upSave
If you are on Windows OS download Python by Clicking here and now install from the setup and in the start menu type IDLE.IDLE, you can think it as an Python’s IDE to run the Python Scripts.It will look somehow this :
It will look somehow this :
If you are on Linux/Unix-like just open the terminal and on 99% linux OS Python comes preinstalled with the OS.Just type ‘python3’ in terminal and you are ready to go.It will look like this :
The ” >>> ” represents the python shell and its ready to take python commands and code.
Variables and Data Structures
In other programming languages like C, C++, and Java, you will need to declare the type of variables but in Python you don’t need to do that. Just type in the variable and when values will be given to it, then it will automatically know whether the value given would be an int, float, or char or even a String.
# Python program to declare variablesmyNumber = 3print(myNumber)  myNumber2 = 4.5print(myNumber2)  myNumber ="helloworld"print(myNumber)
Output:
3
4.5
helloworld

See, how simple is it, just create a variable and assign it any value you want and then use the print function to print it. Python have 4 types of built in Data Structures namely List, Dictionary, Tuple and Set.
List is the most basic Data Structure in python. List is a mutable data structure i.e items can be added to list later after the list creation. It’s like you are going to shop at the local market and made a list of some items and later on you can add more and more items to the list.append() function is used to add data to the list.
# Python program to illustrate a list   # creates a empty listnums = []   # appending data in listnums.append(21)nums.append(40.5)nums.append("String")  print(nums)
Output:
[21, 40.5, String]
Comments:
# is used for single line comment in Python
""" this is a comment """ is used for multi line comments
Input and Output
In this section, we will learn how to take input from the user and hence manipulate it or simply display it. input() function is used to take input from the user.
# Python program to illustrate# getting input from username = input("Enter your name: ")   # user entered the name 'harssh'print("hello", name)
Output:
hello harssh   
# Python3 program to get input from user  # accepting integer from the user# the return type of input() function is string ,# so we need to convert the input to integernum1 = int(input("Enter num1: "))num2 = int(input("Enter num2: "))  num3 = num1 * num2print("Product is: ", num3)
Output:
Enter num1: 8 Enter num2: 6 ('Product is: ', 48)

Selection
Selection in Python is made using the two keywords ‘if’ and ‘elif’ and else (elseif)
# Python program to illustrate# selection statement  num1 = 34if(num1>12):    print("Num1 is good")elif(num1>35):    print("Num2 is not gooooo....")else:    print("Num2 is great")
Output:
Num1 is good
Functions
You can think of functions like a bunch of code that is intended to do a particular task in the whole Python script. Python used the keyword ‘def’ to define a function.Syntax:
def function-name(arguments):
            #function body
# Python program to illustrate# functionsdef hello():    print("hello")    print("hello again")hello()  # calling functionhello()               
Output:
hello
hello again
hello
hello again

Now as we know any program starts from a ‘main’ function...lets create a main function like in many other programming languages.
# Python program to illustrate # function with maindef getInteger():    result = int(input("Enter integer: "))    return result  def Main():    print("Started")      # calling the getInteger function and     # storing its returned value in the output variable    output = getInteger()         print(output)  # now we are required to tell Python # for 'Main' function existenceif __name__=="__main__":    Main()
Output:
Started
Enter integer: 5

Iteration (Looping)
As the name suggests it calls repeating things again and again. We will use the most popular ‘for’ loop here.
# Python program to illustrate# a simple for loop  for step in range(5):        print(step)
Output:
0
1
2
3
4

Modules
Python has a very rich module library that has several functions to do many tasks. You can read more about Python’s standard library by Clicking here‘import’ keyword is used to import a particular module into your python code. For instance consider the following program.
# Python program to illustrate# math moduleimport math  def Main():    num = -85      # fabs is used to get the absolute     # value of a decimal    num = math.fabs(num)     print(num)            if __name__=="__main__":    Main()
Output:
85.0
New to the programming world, don’t know where to start? Start with beginner-friendly Python Programming Foundation -Self Paced Course designed for absolute beginners who wish to kickstart and build their foundations in Python programming language. Learn Python basics, Variables & Data types, Operators etc and learn how to solve coding problems efficiently in Python. Don’t wait, sign up now and kickstart your Python journey today.
If you’re curious to upgrade your Python skills, you’ve come to the right platform! In this DS Using Python Programming – Self Paced Course, designed for Python enthusiasts where you’ll be guided by the leading industry experts who will explain in-depth, and efficient methods to implement data structures such as heaps, stacks, and linked lists etc. So, what are you waiting for? Advance your Python skills today.
shivamsaraswat
lalitshankarch
sarajadhav12052009
Python
School Programming
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Read JSON file using Python
Adding new column to existing DataFrame in Pandas
Python map() function
How to get column names in Pandas dataframe
Different ways to create Pandas Dataframe
Reverse a string in Java
Arrays in C/C++
Interfaces in Java
Inheritance in C++
C++ Classes and Objects