Internal working of Python - GeeksforGeeks (2024)

Skip to content

Internal working of Python - GeeksforGeeks (1)

Last Updated : 10 Aug, 2023

Summarize

Comments

Improve

Suggest changes

Like Article

Like

Save

Report

Python is an object-oriented programming language like Java. Python is called an interpreted language. Python uses code modules that are interchangeable instead of a single long list of instructions that was standard for functional programming languages. The standard implementation of Python is called “cpython”. It is the default and widely used implementation of Python.

Internal working of Python

Python doesn’t convert its code into machine code, something that hardware can understand. It converts it into something called byte code. So within Python, compilation happens, but it’s just not in a machine language. It is into byte code (.pyc or .pyo) and this byte code can’t be understood by the CPU. So we need an interpreter called the Python virtual machine to execute the byte codes.

Internal working of Python - GeeksforGeeks (3)

Internal Working of Python

How is Python Source Code Converted into Executable Code

The Python source code goes through the following to generate an executable code

  • Step 1: The Python compiler reads a Python source code or instruction in the code editor. In this first stage, the execution of the code starts.
  • Step 2: After writing Python code it is then saved as a .py file in our system. In this, there are instructions written by a Python script for the system.
  • Step 3: In this the compilation stage comes in which source code is converted into a byte code. Python compiler also checks the syntax error in this step and generates a .pyc file.
  • Step 4: Byte code that is .pyc file is then sent to the Python Virtual Machine(PVM) which is the Python interpreter. PVM converts the Python byte code into machine-executable code and in this interpreter reads and executes the given file line by line. If an error occurs during this interpretation then the conversion is halted with an error message.
  • Step 5: Within the PVM the bytecode is converted into machine code that is the binary language consisting of 0’s and 1’s. This binary language is only understandable by the CPU of the system as it is highly optimized for the machine code.
  • Step 6: In the last step, the final execution occurs where the CPU executes the machine code and the final desired output will come as according to your program.

How Python Internally Works?

  • Code Editor: Code Editor is the first stage of programs where we write our source code. This is human-readable code written according to Python’s syntax rules. It is where the execution of the program starts first.
  • Source code: The code written by a programmer in the code editor is then saved as a .py file in a system. This file of Python is written in human-readable language that contains the instructions for the computer.
  • Compilation Stage: The compilation stage of Python is different from any other programming language. Rather than compiling a source code directly into machine code. python compiles a source code into a byte code. In the compilation stage python compiler also checks for syntax errors. after checking all the syntax errors, if no such error is found then it generates a .pyc file that contains bytecode.
  • Python Virtual Machine(PVM): The bytecode then goes into the main part of the conversion is the Python Virtual Machine(PVM). The PVM is the main runtime engine of Python. It is an interpreter that reads and executes the bytecode file, line by line. Here In the Python Virtual Machine translate the byte code into machine code which is the binary language consisting of 0s and 1s. The machine code is highly optimized for the machine it is running on. This binary language is only understandable by the CPU of a system.
  • Running Program: At last, the CPU executes the given machine code and the main outcome of the program comes as performing task and computation you scripted at the beginning of the stage in your code editor.

Python Libraries/Modules

When you import libraries or modules in your Python program. Firstly python checks if the given module is built-in, and executes the corresponding C code. If the module is not built-in then the list of directories is defined in sys. path. the directory of the input script, and directories listed in the PYTHONPATH. if a .py file corresponds to the modules imported, Python creates a new module object, On executing the code in the .py file within the object’s namespace. Then Python compiles source code into byte code( the .pyc file), allowing for quicker execution

Compiler Vs Interpreter

In the system both the compiler and interpreter are the same they convert high-level code to machine code. The interpreter converts source code into the machine when the program runs in a system while a compiler converts the source code into machine code before the program runs in our system.

Compiler

Interpreter

The compiler is faster, as conversion occurs before the program executes.

The interpreter runs slower as the execution occurs simultaneously.

Errors are detected during the compilation phase and displayed before the execution of a program.

Errors are identified and reported during the given actual runtime.

Compile code needs to be recompiled to run on different machines.

Interpreted code is more portable as it can run on any machine with the appropriate interpreter.

It requires more memory to translate the whole source code at once.

It requires less memory than compiled ones.

Debugging is more complex due to batch processing of the code.

Debugging is easier due to the line-by-line execution of a code.



Please Login to comment...

Similar Reads

Internal working of list in Python

Introduction to Python lists : Python lists are internally represented as arrays. The idea used is similar to implementation of vectors in C++ or ArrayList in Java. The costly operations are inserting and deleting items near the beginning (as everything has to be moved). Insert at the end also becomes costly if preallocated space becomes full.We ca

3 min read

Internal Working of the len() Function in Python

The len() function in Python has a very peculiar characteristic that one had often wondered about. It takes absolutely no time, and equal time, in calculating the lengths of iterable data structures(string, array, tuple, etc.), irrespective of the size or type of data. This obviously implies O(1) time complexity. But have you wondered How? Python f

2 min read

Internal working of Set in Python

Sets and their working Set in Python can be defined as the collection of items. In Python, these are basically used to include membership testing and eliminating duplicate entries. The data structure used in this is Hashing, a popular technique to perform insertion, deletion and traversal in O(1) on average. The operations on Hash Table are some wh

3 min read

Internal Structure of Python Dictionary

Dictionary in Python is an unordered collection of data values, used to store data values like a map, which unlike other Data Types that hold only a single value as an element, Dictionary holds key:value pair. Key-value is provided in the dictionary to make it more optimized The dictionary consists of a number of buckets. Each of these buckets cont

3 min read

Internal implementation of Data Structures in Python

Python provides a variety of built-in data structures, each with its own characteristics and internal implementations optimized for specific use cases. In this article we are going to discuss about the most commonly used Data structures in Python and a brief overview of their internal implementations: Data Structure Internal Implementation Static o

3 min read

marshal — Internal Python object serialization

Serializing a data means converting it into a string of bytes and later reconstructing it from such a string. If the data is composed entirely of fundamental Python objects, the fastest way to serialize the data is by using marshal module (For user defined classes, Pickle should be preferred). Marshal module contains functions that can read and wri

2 min read

Working with Datetime Objects and Timezones in Python

In this article, we are going to work with Datetime objects and learn about their behavior when Time zones are introduced. We are going to be working with the Python datetime module. Getting a Datetime objectMethod 1: Using now() method A very easy way to get a Datetime object is to use the datetime.now() method. A DateTime object is an instance/ob

5 min read

Python | Working with Pandas and XlsxWriter | Set - 1

Python Pandas is a data analysis library. It can read, filter and re-arrange small and large datasets and output them in a range of formats including Excel. Pandas writes Excel files using the XlsxWriter modules. XlsxWriter is a Python module for writing files in the XLSX file format. It can be used to write text, numbers, and formulas to multiple

3 min read

Python | Working with Pandas and XlsxWriter | Set – 2

Prerequisite: : Python working with pandas and xlsxwriter | set-1 Python Pandas is a data analysis library. It can read, filter and re-arrange small and large datasets and output them in a range of formats including Excel. Pandas writes Excel files using the XlsxWriter modules. XlsxWriter is a Python module for writing files in the XLSX file format

4 min read

Python | Working with Pandas and XlsxWriter | Set – 3

Prerequisite: : Python working with pandas and xlsxwriter | set-1 Python Pandas is a data analysis library. It can read, filter and re-arrange small and large datasets and output them in a range of formats including Excel. Pandas writes Excel files using the XlsxWriter modules. XlsxWriter is a Python module for writing files in the XLSX file format

5 min read

Working With JSON Data in Python

JSON is JavaScript Object Notation. It means that a script (executable) file which is made of text in a programming language, is used to store and transfer the data. Python supports JSON through a built-in package called JSON. To use this feature, we import the JSON package in Python script. The text in JSON is done through quoted-string which cont

6 min read

Python | Working with PNG Images using Matplotlib

Matplotlib is an amazing visualization library in Python for 2D plots of arrays. Matplotlib is a multi-platform data visualization library built on NumPy arrays and designed to work with the broader SciPy stack. It was introduced by John Hunter in the year 2002. One of the greatest benefits of visualization is that it allows us visual access to hug

3 min read

Python | Working with buttons in Kivy with .kv file

Kivy is a platform independent GUI tool in Python. As it can be run on Android, IOS, linux and Windows etc. It is basically used to develop the Android application, but it does not mean that it can not be used on Desktops applications. Button: The Button is a Label with associated actions that are triggered when the button is pressed (or released a

4 min read

Python | Working with the Image Data Type in pillow

In this article, we will look into some attributes of an Image object that will give information about the image and the file it was loaded from. For this, we will need to import image module from pillow. Image we will be working on : size() method - It helps to get the dimensions of an image. IMG = Image.open(Image_path) croppedIm = IMG.size # imp

2 min read

Change current working directory with Python

The OS module in Python is used for interacting with the operating system. This module comes under Python's standard utility module so there is no need to install it externally. All functions in OS module raise OSError in the case of invalid or inaccessible file names and paths, or other arguments that have the correct type but are not accepted by

2 min read

Working with Images in Python using Matplotlib

Matplotlib is an amazing visualization library in Python for 2D plots of arrays. Matplotlib is a multi-platform data visualization library built on NumPy arrays and designed to work with the broader SciPy stack. Working with Images in Python using Matplotlib The image module in matplotlib library is used for working with images in Python. The image

3 min read

Working with the Python Debugger

Python Debugger may be a new word for the beginner developers . In this post , we will try to explain the meaning of Debugging and Debugging with Python . What is Debugging? Debugging means the complete control over the program execution. Developers use debugging to overcome program from any bad issues. So debugging is a healthier process for the p

3 min read

Working with Binary Data in Python

Alright, lets get this out of the way! The basics are pretty standard: There are 8 bits in a byteBits either consist of a 0 or a 1A byte can be interpreted in different ways, like binary octal or hexadecimal Note: These are not character encodings, those come later. This is just a way to look at a set of 1's and 0's and see it in three different wa

5 min read

Working with Strings in Python 3

In Python, sequences of characters are referred to as Strings. It used in Python to record text information, such as names. Python strings are "immutable" which means they cannot be changed after they are created. Creating a StringStrings can be created using single quotes, double quotes, or even triple quotes. Python treats single quotes the same

6 min read

Working with IP Addresses in Python

IP (Internet Protocol) -Address is the basic fundamental concept of computer networks which provides the address assigning capabilities to a network. Python provides ipaddress module which is used to validate and categorize the IP address according to their types(IPv4 or IPv6). This module is also used for performing wide range of operation like ar

3 min read

Working with the pycricbuzz library in Python

Pycricbuzz is a python library that can be used to get live scores, commentary and full scorecard for recent and live matches. In case you want to know how the library was developed, you can watch the video: https://youtu.be/OQqYbC1BKxw Installation: Run the following pip command in the terminal. pip install pycricbuzz First of all, we need to crea

3 min read

Working with Page Orientations and Pagination Properties - Python .docx Module

Prerequisite: Working with .docx module Word documents contain formatted text wrapped within three object levels. The Lowest level- run objects, middle level- paragraph objects, and highest level- document object. So, we cannot work with these documents using normal text editors. But, we can manipulate these word documents in python using the pytho

4 min read

Working with Lists - Python .docx Module

Prerequisite: Working with .docx module Word documents contain formatted text wrapped within three object levels. The Lowest level- run objects, middle level- paragraph objects, and highest level- document object. So, we cannot work with these documents using normal text editors. But, we can manipulate these word documents in python using the pytho

4 min read

Working With Text In Python .docx Module

Prerequisite: Working with .docx module Word documents contain formatted text wrapped within three object levels. The Lowest level-run objects, middle level-paragraph objects, and highest level-document object. So, we cannot work with these documents using normal text editors. But, we can manipulate these word documents in python using the python-d

8 min read

Working with Headers And Footers in Python .docx Module

Prerequisite: Working with .docx module Word documents contain formatted text wrapped within three object levels. The Lowest level-run objects, middle level-paragraph objects, and highest level-document objects. So, we cannot work with these documents using normal text editors. But, we can manipulate these word documents in python using the python-

6 min read

Working with Documents - Python .docx Module

Prerequisite: Working with .docx module Word documents contain formatted text wrapped within three object levels. The lowest level- run objects, middle level- paragraph objects, and highest level- document object. So, we cannot work with these documents using normal text editors. But, we can manipulate these word documents in python using the pytho

2 min read

Working with Titles and Heading - Python docx Module

Prerequisites: docx Word documents contain formatted text wrapped within three object levels. The Lowest level- run objects, middle level- paragraph objects and highest level- document object. So, we cannot work with these documents using normal text editors. But, we can manipulate these word documents in python using the python-docx module. Python

2 min read

Working with Images - Python .docx Module

Prerequisites: docx Word documents contain formatted text wrapped within three object levels. Lowest level- run objects, middle level- paragraph objects and highest level- document object. So, we cannot work with these documents using normal text editors. But, we can manipulate these word documents in python using the python-docx module. Python doc

2 min read

Working with Page Break - Python .docx Module

Prerequisites: docx Word documents contain formatted text wrapped within three object levels. Lowest level- run objects, middle level- paragraph objects and highest level- document object. So, we cannot work with these documents using normal text editors. But, we can manipulate these word documents in python using the python-docx module. Python doc

2 min read

Working with Tables - Python .docx Module

Prerequisites: docx Word documents contain formatted text wrapped within three object levels. Lowest level- run objects, middle level- paragraph objects and highest level- document object. So, we cannot work with these documents using normal text editors. But, we can manipulate these word documents in python using the python-docx module. Python doc

3 min read

Article Tags :

Practice Tags :

We use cookies to ensure you have the best browsing experience on our website. By using our site, you acknowledge that you have read and understood our Cookie Policy & Privacy Policy

Internal working of Python - GeeksforGeeks (5)

'); $('.spinner-loading-overlay').show(); jQuery.ajax({ url: writeApiUrl + 'create-improvement-post/?v=1', type: "POST", contentType: 'application/json; charset=utf-8', dataType: 'json', xhrFields: { withCredentials: true }, data: JSON.stringify({ gfg_id: post_id, check: true }), success:function(result) { jQuery.ajax({ url: writeApiUrl + 'suggestions/auth/' + `${post_id}/`, type: "GET", dataType: 'json', xhrFields: { withCredentials: true }, success: function (result) { $('.spinner-loading-overlay:eq(0)').remove(); var commentArray = result; if(commentArray === null || commentArray.length === 0) { // when no reason is availaible then user will redirected directly make the improvment. // call to api create-improvement-post $('body').append('

'); $('.spinner-loading-overlay').show(); jQuery.ajax({ url: writeApiUrl + 'create-improvement-post/?v=1', type: "POST", contentType: 'application/json; charset=utf-8', dataType: 'json', xhrFields: { withCredentials: true }, data: JSON.stringify({ gfg_id: post_id, }), success:function(result) { $('.spinner-loading-overlay:eq(0)').remove(); $('.improve-modal--overlay').hide(); $('.unlocked-status--improve-modal-content').css("display","none"); $('.create-improvement-redirection-to-write').attr('href',writeUrl + 'improve-post/' + `${result.id}` + '/', '_blank'); $('.create-improvement-redirection-to-write')[0].click(); }, error:function(e) { $('.spinner-loading-overlay:eq(0)').remove(); var result = e.responseJSON; if(result.detail.non_field_errors.length){ $('.improve-modal--improve-content .improve-modal--improve-content-modified').text(`${result.detail.non_field_errors}.`); jQuery('.improve-modal--overlay').show(); jQuery('.improve-modal--improvement').show(); $('.locked-status--impove-modal').css("display","block"); $('.unlocked-status--improve-modal-content').css("display","none"); $('.improve-modal--improvement').attr("status","locked"); $('.improvement-reason-modal').hide(); } }, }); return; } var improvement_reason_html = ""; for(var comment of commentArray) { // loop creating improvement reason list markup var comment_id = comment['id']; var comment_text = comment['suggestion']; improvement_reason_html += `

${comment_text}

`; } $('.improvement-reasons_wrapper').html(improvement_reason_html); $('.improvement-bottom-btn').html("Create Improvement"); $('.improve-modal--improvement').hide(); $('.improvement-reason-modal').show(); }, error: function(e){ $('.spinner-loading-overlay:eq(0)').remove(); // stop loader when ajax failed; }, }); }, error:function(e) { $('.spinner-loading-overlay:eq(0)').remove(); var result = e.responseJSON; if(result.detail.non_field_errors.length){ $('.improve-modal--improve-content .improve-modal--improve-content-modified').text(`${result.detail.non_field_errors}.`); jQuery('.improve-modal--overlay').show(); jQuery('.improve-modal--improvement').show(); $('.locked-status--impove-modal').css("display","block"); $('.unlocked-status--improve-modal-content').css("display","none"); $('.improve-modal--improvement').attr("status","locked"); $('.improvement-reason-modal').hide(); } }, }); } else { if(loginData && !loginData.isLoggedIn) { $('.improve-modal--overlay').hide(); if ($('.header-main__wrapper').find('.header-main__signup.login-modal-btn').length) { $('.header-main__wrapper').find('.header-main__signup.login-modal-btn').click(); } return; } } }); $('.left-arrow-icon_wrapper').on('click',function(){ if($('.improve-modal--suggestion').is(":visible")) $('.improve-modal--suggestion').hide(); else{ $('.improvement-reason-modal').hide(); } $('.improve-modal--improvement').show(); }); function loadScript(src, callback) { var script = document.createElement('script'); script.src = src; script.onload = callback; document.head.appendChild(script); } function suggestionCall() { var suggest_val = $.trim($("#suggestion-section-textarea").val()); var array_String= suggest_val.split(" ") var gCaptchaToken = $("#g-recaptcha-response-suggestion-form").val(); var error_msg = false; if(suggest_val != "" && array_String.length >=4){ if(suggest_val.length <= 2000){ var payload = { "gfg_post_id" : `${post_id}`, "suggestion" : `

${suggest_val}

`, } if(!loginData || !loginData.isLoggedIn) // User is not logged in payload["g-recaptcha-token"] = gCaptchaToken jQuery.ajax({ type:'post', url: "https://apiwrite.geeksforgeeks.org/suggestions/auth/create/", xhrFields: { withCredentials: true }, crossDomain: true, contentType:'application/json', data: JSON.stringify(payload), success:function(data) { jQuery('.spinner-loading-overlay:eq(0)').remove(); jQuery('#suggestion-section-textarea').val(""); jQuery('.suggest-bottom-btn').css("display","none"); // Update the modal content const modalSection = document.querySelector('.suggestion-modal-section'); modalSection.innerHTML = `

Thank You!

Your suggestions are valuable to us.

You can now also contribute to the GeeksforGeeks community by creating improvement and help your fellow geeks.

`; }, error:function(data) { jQuery('.spinner-loading-overlay:eq(0)').remove(); jQuery('#suggestion-modal-alert').html("Something went wrong."); jQuery('#suggestion-modal-alert').show(); error_msg = true; } }); } else{ jQuery('.spinner-loading-overlay:eq(0)').remove(); jQuery('#suggestion-modal-alert').html("Minimum 5 Words and Maximum Character limit is 2000."); jQuery('#suggestion-modal-alert').show(); jQuery('#suggestion-section-textarea').focus(); error_msg = true; } } else{ jQuery('.spinner-loading-overlay:eq(0)').remove(); jQuery('#suggestion-modal-alert').html("Enter atleast four words !"); jQuery('#suggestion-modal-alert').show(); jQuery('#suggestion-section-textarea').focus(); error_msg = true; } if(error_msg){ setTimeout(() => { jQuery('#suggestion-section-textarea').focus(); jQuery('#suggestion-modal-alert').hide(); }, 3000); } } document.querySelector('.suggest-bottom-btn').addEventListener('click', function(){ jQuery('body').append('

'); jQuery('.spinner-loading-overlay').show(); if(loginData && loginData.isLoggedIn) { suggestionCall(); return; } // load the captcha script and set the token loadScript('https://www.google.com/recaptcha/api.js?render=6LdMFNUZAAAAAIuRtzg0piOT-qXCbDF-iQiUi9KY',[], function() { setGoogleRecaptcha(); }); }); $('.improvement-bottom-btn.create-improvement-btn').click(function() { //create improvement button is clicked $('body').append('

'); $('.spinner-loading-overlay').show(); // send this option via create-improvement-post api jQuery.ajax({ url: writeApiUrl + 'create-improvement-post/?v=1', type: "POST", contentType: 'application/json; charset=utf-8', dataType: 'json', xhrFields: { withCredentials: true }, data: JSON.stringify({ gfg_id: post_id }), success:function(result) { $('.spinner-loading-overlay:eq(0)').remove(); $('.improve-modal--overlay').hide(); $('.improvement-reason-modal').hide(); $('.create-improvement-redirection-to-write').attr('href',writeUrl + 'improve-post/' + `${result.id}` + '/', '_blank'); $('.create-improvement-redirection-to-write')[0].click(); }, error:function(e) { $('.spinner-loading-overlay:eq(0)').remove(); var result = e.responseJSON; if(result.detail.non_field_errors.length){ $('.improve-modal--improve-content .improve-modal--improve-content-modified').text(`${result.detail.non_field_errors}.`); jQuery('.improve-modal--overlay').show(); jQuery('.improve-modal--improvement').show(); $('.locked-status--impove-modal').css("display","block"); $('.unlocked-status--improve-modal-content').css("display","none"); $('.improve-modal--improvement').attr("status","locked"); $('.improvement-reason-modal').hide(); } }, }); });

Internal working of Python - GeeksforGeeks (2024)
Top Articles
EH - Ehang Holdings Stock Dividend Date & History 2024
Live Chat Jobs Review-Navigating the Future of Remote Work [Updated]
Sdn Md 2023-2024
My Arkansas Copa
Maria Dolores Franziska Kolowrat Krakowská
Craigslist Mpls Mn Apartments
DL1678 (DAL1678) Delta Historial y rastreo de vuelos - FlightAware
United Dual Complete Providers
True Statement About A Crown Dependency Crossword
Craigslist Pets Longview Tx
I Wanna Dance with Somebody : séances à Paris et en Île-de-France - L'Officiel des spectacles
Chic Lash Boutique Highland Village
Tcu Jaggaer
Ess.compass Associate Login
Lcwc 911 Live Incident List Live Status
Craigslist West Valley
Earl David Worden Military Service
Full Standard Operating Guideline Manual | Springfield, MO
Cvs El Salido
Craigslist Personals Jonesboro
Is Windbound Multiplayer
Craigslist Houses For Rent In Milan Tennessee
St Clair County Mi Mugshots
Okc Body Rub
Buying Cars from Craigslist: Tips for a Safe and Smart Purchase
Sandals Travel Agent Login
Geico Car Insurance Review 2024
Ihs Hockey Systems
Cvs Sport Physicals
Imagetrend Elite Delaware
3473372961
Ghid depunere declarație unică
Home Auctions - Real Estate Auctions
Jambus - Definition, Beispiele, Merkmale, Wirkung
Nsu Occupational Therapy Prerequisites
The Complete Guide To The Infamous "imskirby Incident"
Aurora Il Back Pages
Conan Exiles Armor Flexibility Kit
Mississippi weather man flees studio during tornado - video
Memberweb Bw
Craigslist Minneapolis Com
Lyons Hr Prism Login
Theater X Orange Heights Florida
Argus Leader Obits Today
Arginina - co to jest, właściwości, zastosowanie oraz przeciwwskazania
Model Center Jasmin
Craiglist.nj
Used Auto Parts in Houston 77013 | LKQ Pick Your Part
Diamond Desires Nyc
Arnold Swansinger Family
Coors Field Seats In The Shade
Latest Posts
Article information

Author: Lakeisha Bayer VM

Last Updated:

Views: 5706

Rating: 4.9 / 5 (49 voted)

Reviews: 88% of readers found this page helpful

Author information

Name: Lakeisha Bayer VM

Birthday: 1997-10-17

Address: Suite 835 34136 Adrian Mountains, Floydton, UT 81036

Phone: +3571527672278

Job: Manufacturing Agent

Hobby: Skimboarding, Photography, Roller skating, Knife making, Paintball, Embroidery, Gunsmithing

Introduction: My name is Lakeisha Bayer VM, I am a brainy, kind, enchanting, healthy, lovely, clean, witty person who loves writing and wants to share my knowledge and understanding with you.