Python is a general-purpose high-level programming language and is widely used among the developers’ community. Python was mainly developed for emphasis on code readability, and its syntax allows programmers to express concepts in fewer lines of code. This Python tutorial provides learners [either beginner or experienced developers] with topics from Python basics to advanced topics with examples.
Nội dung chính
- Key features of Python
- Application Areas
- Getting started with Python Tutorial –
- What if Python already exists? Let’s check
- Download and Installation
- How to run a Python program
- Fundamentals of Python
- Python Indentation
- Basics of Input/Output
- Taking input from user –
- Printing output to console –
- Sequence Type
- Decision Making
- Control flow [Loops]
- Loop control statements
- Function with arguments
- Lambda functions
- Object Oriented Programming
- Classes and Objects
- Constructors and Destructors
- Inheritance
- Encapsulation
- Polymorphism
- File Handling
- Modules and Packages
- Regular expressions[RegEx]
- Exception handling
Key features of Python
Python has many reasons for being popular and in demand. A few of the reasons are mentioned below.
- 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.
- It provides extensive support libraries[Django for web development, Pandas for data analytics etc]
- Dynamically typed language[Data type is based on value assigned]
- Philosophy is “Simplicity is the best”.
Application Areas
Getting started with Python Tutorial –
Python is a lot easier to code and learn. Python programs can be written on any plain text editor like notepad, notepad++, or anything of that sort. One can also use an online IDE for
writing Python codes or can even install one on their system to make it more feasible to write these codes because IDEs provide a lot of features like intuitive code editor, debugger, compiler, etc.
To begin with, writing Python Codes and performing various intriguing and useful operations, one must have Python installed on their System. This can be done by following the step by step instructions provided below:
What if Python already exists? Let’s check
Windows don’t come with Python preinstalled, it needs to be installed explicitly. But unlike windows, most of the Linux OS have Python pre-installed, also macOS comes with Python pre-installed.
To check if your device is pre-installed with Python or not, just go to Command Line[For Windows, search for cmd in the Run dialog[ + R], for Linux open the terminal using
Ctrl+Alt+T
, for macOS use control+Option+Shift+T
.
Now run the following command:
For Python2
python --version
For Python3
python3 --version
If Python is already installed, it will generate a message with the Python version available.
Download and Installation
Before starting with the installation process, you need to download it. For that all versions of Python for Windows, Linux, and MacOS are available on python.org.
Windows
Linux
MacOS
Download the Python and follow the further instructions for the installation of Python.
Beginning the installation.
Windows
Linux
For almost every Linux system, the following commands would work definitely.
$ sudo add-apt-repository ppa:deadsnakes/ppa $ sudo apt-get update $ sudo apt-get install python3.8
To verify the installation enter following commands in your Terminal.
python3
MacOS
- Download and install Homebrew Package Manager
Enter following command in macOS terminal./usr/bin/ruby -e "$[curl -fsSL //raw.githubusercontent.com/Homebrew/install/master/install]"
Enter system password if prompted. This will install the Homebrew package Manager on your OS.
After you see a message called “Installation Successful”. You are ready to install python version 3 on your macOS. - Install Python Latest Version on macOS / macOS X
Open Terminal and enter the following command.
brew install python3
After command processing is complete, Python’s version 3 would be installed on your mac.
To verify the installation enter following commands in your Terminal app
pythona fa-hand-o-right
pip3
How to run a Python program
Let’s consider a simple Hello World Program.
# Python program to print # Hello World print["Hello World"]
Generally, there are two ways to run a Python program.
- Using IDEs: You can use various IDEs[Pycharm, Jupyter Notebook, etc.] which can be used to run Python programs.
- Using Command-Line: You can also use command line options to run a Python program. Below steps demonstrate how to run a Python program on Command line in Windows/Unix Operating System:
Windows
Open Commandline and then to compile the code type python HelloWorld.py. If your code has no error then it will execute properly and output will be displayed.
Unix/Linux
Open Terminal of your Unix/Linux OS and then to compile the code type python HelloWorld.py. If your code has no error then it will execute properly and output will be displayed.
Fundamentals of Python
Python Indentation
Python uses indentation to highlight the blocks of code. Whitespace is used for indentation in Python. All statements with the same distance to the right belong to the same block of code. If a block has to be more deeply nested, it is simply indented further to the right. You can understand it better by looking at the following lines of code.
# Python program showing # indentation site = 'gfg' if site == 'gfg': print['Logging on to geeksforgeeks...'] else: print['retype the URL.'] print['All set !']
Output:
Logging on to geeksforgeeks... All set !
The lines print[‘Logging on to geeksforgeeks…’]
and print[‘retype the URL.’]
are two separate code blocks. The two blocks of code in our example if-statement are both indented four spaces. The final print[‘All set!’]
is not indented, and so it does not belong to the else-block.
Note: For more information, refer 👉🏽 Indentation in Python.
Comments are useful information that the developers provide to make the reader understand the source code. It explains the logic or a part of it used in the code. There are two types of comment in Python:
- Single line comments: Python single line comment starts with hashtag symbol with no white spaces.
# This is a comment # Print “GeeksforGeeks !” to console print["GeeksforGeeks"]
- Multi-line string as comment: Python multi-line comment is a piece of text enclosed in a delimiter [“””] on each end of the comment.
""" This would be a multiline comment in Python that spans several lines and describes geeksforgeeks. A Computer Science portal for geeks. It contains well written, well thought and well-explained computer science and programming articles, quizzes and more. … """ print["GeeksForGeeks"]
Note: For more information, refer 👉🏽 Comments in Python.
Variables
Variables in Python are not “statically typed”. We do not need to declare variables before using them or declare their type. A variable is created the moment we first assign a value to it.
#!/usr/bin/python # An integer assignment age = 45 # A floating point salary = 1456.8 # A string name = "John" print[age] print[salary] print[name]
Output:
45 1456.8 John
Note: For more information, refer 👉🏽 Python Variables.
Operators
Operators are the main building block of any programming language. Operators allow the programmer to perform different kinds of operations on operands. These operators can be categorized based upon their different functionality:
- Arithmetic operators: Arithmetic operators are used to perform mathematical operations like addition, subtraction, multiplication and division.
# Examples of Arithmetic Operator a = 9 b = 4 # Addition of numbers add = a + b # Subtraction of numbers sub = a - b # Multiplication of number mul = a * b # Division[float] of number div1 = a / b # Division[floor] of number div2 = a // b # Modulo of both number mod = a % b # print results print[add] print[sub] print[mul] print[div1] print[div2] print[mod]
Output:
13 5 36 2.25 2 1
- Relational Operators: Relational operators compares the values. It either
returns True or False according to the condition.
# Examples of Relational Operators a = 13 b = 33 # a > b is False print[a > b] # a < b is True print[a < b] # a == b is False print[a == b] # a != b is True print[a != b] # a >= b is False print[a >= b] # a 2] # print bitwise left shift operation print[a