top

Search

Python Tutorial

.

UpGrad

Python Tutorial

How to Run Python Program

Introduction

In this tutorial, you'll uncover the core techniques of how to run Python program. Ideal for professionals aiming to reskill or upskill, we unravel Python's execution methods, offering a systematic approach suitable for diverse environments, from terminals to integrated development environments (IDEs).

Overview

Python, renowned for its adaptability, offers multiple avenues to execute code. This tutorial steers professionals through the nuances of running Python scripts, illuminating the execution paths and best practices on how to run Python program.

What is a Python Program?

A Python program is a precisely ordered collection of instructions, composed using the language's distinct syntax, formulated to carry out a specific operation or set of operations. The beauty of Python lies in its ability to create a myriad of program types, each with its unique functionality and purpose. At the foundation, Python programs consist of integral components, such as variables, which act as repositories for data; functions, which are reusable chunks of code designed for specific tasks; control structures that dictate the flow of the program; and modules, organized units of related functions and variables that improve efficiency and structure. 

Depending on the objectives and scale, Python programs can manifest as scripts, applications, web apps, or specialized tools for data analysis. A pivotal component in the Python execution mechanism is the interpreter, with CPython emerging as the standard and most widely used version.

Component

Brief Description

Definition

An ordered set of Python-syntax instructions aimed at a defined task.

Variables

Data containers that adjust and store values as the program operates.

Functions

Designated code sections that can be invoked multiple times, each serving a distinct purpose.

Control Structures

Architectural code elements, like loops and conditions, which guide the program’s sequence and behavior.

Modules

Collections of correlated variables and functions; they act as organizational tools and foster reusability.

Types of Programs

Classifications based on purpose and scale: scripts (small tasks), applications (large tasks), web apps, data tools.

Execution Process

The role of interpreters, primarily CPython, in translating and running Python code.

Ways to Run Python Scripts

The Operating System Command-Line or Terminal

One of the most common ways to run Python scripts is by using the command-line or terminal on your operating system. Open a command-line or terminal window, navigate to the directory where your Python script is located, and use the Python command followed by the script's filename to execute it.

Here is the command for executing a script named my_script.py:

python my_script.py

The Python Interactive Mode

Python provides an interactive mode where you can enter Python code directly and see the results immediately. To start the Python interactive shell, open the command-line or terminal and type python. You can then enter Python commands one by one and see the output instantly.

Example:

python
>>> print("Hello, World!")

The Integrated Development Environment (IDE) or Text Editor

Many developers prefer using integrated development environments (IDEs) like PyCharm, Visual Studio Code, or text editors like Sublime Text or Notepad++ to write and run Python scripts. You can create Python scripts within these environments, write code with syntax highlighting and code completion, and run the scripts directly from the IDE or text editor.

Here is an example of using an online IDE to run a Python program:

Code:

# Function to add two numbers
def add(x, y):
    return x + y

# Function to subtract two numbers
def subtract(x, y):
    return x - y

# Function to multiply two numbers
def multiply(x, y):
    return x * y

# Function to divide two numbers
def divide(x, y):
    if y == 0:
        return "Cannot divide by zero"
    return x / y

# Main calculator program
while True:
    print("Options:")
    print("Enter 'add' for addition")
    print("Enter 'subtract' for subtraction")
    print("Enter 'multiply' for multiplication")
    print("Enter 'divide' for division")
    print("Enter 'quit' to end the program")

    user_input = input(": ")

    if user_input == "quit":
        break
    elif user_input in ["add", "subtract", "multiply", "divide"]:
        num1 = float(input("Enter first number: "))
        num2 = float(input("Enter second number: "))

        if user_input == "add":
            print("Result:", add(num1, num2))
        elif user_input == "subtract":
            print("Result:", subtract(num1, num2))
        elif user_input == "multiply":
            print("Result:", multiply(num1, num2))
        elif user_input == "divide":
            print("Result:", divide(num1, num2))
    else:
        print("Invalid input")

You can copy and paste this code into a Python environment or script and run it. It will prompt you to choose an operation and input two numbers. Then, it will perform the selected operation and display the result until you choose to quit the program by typing "quit."

The File Manager of the System

On some systems, you can double-click a Python script file (with a .py extension), and it will be executed using the default Python interpreter associated with your system. This method is convenient for running scripts without needing to open a command-line interface, especially for simple scripts.

Applications of Python

Python, with its expansive ecosystem and an extensive set of libraries, has been instrumental in reshaping the technological landscape. Its applications span across numerous domains, solidifying its position as a sought-after programming language. Let's delve deeper into some of these applications:

  1. Web Development: The digital era is propelled by web platforms, and Python has been a cornerstone in this realm.

  • Django: This high-level framework has revolutionized the creation of web applications, offering a systematic and efficient approach. Django promotes reusable code, thus speeding up the development process while ensuring robust and scalable applications.

  • Flask: Tailored for developers seeking simplicity, Flask provides the foundation to craft web applications swiftly. Its micro framework status makes it the go-to choice for straightforward projects that don't require a full-fledged framework's overhead.

  1. Data Analysis: Data has become the new oil, and Python is the refinery.

  • Pandas: An essential in the data analyst's toolkit, Pandas offers comprehensive functionalities for data manipulation. From reshaping to aggregating data, its capabilities are vast, making it indispensable for data wrangling.

  • NumPy: A marvel in numerical computing, NumPy excels in managing complex mathematical operations, especially over extensive datasets, making it a darling of researchers and analysts alike.

  1. Artificial Intelligence (AI): AI's surge can be attributed significantly to Python's prowess.

  • TensorFlow: Pioneering the domain of deep learning, TensorFlow facilitates the creation of neural networks and AI models. Its flexibility and scalability make it suitable for both research and production.

  • scikit-learn: A jewel in machine learning, scikit-learn offers a rich suite of algorithms for regression, classification, clustering, and more. Its intuitive API and efficiency make it an essential tool for data scientists.

  1. Automation: Efficiency in the digital era revolves around automation, and Python is a catalyst.

  • Selenium: Catering to web automation, Selenium simulates browser activities, aiding in testing web applications for performance and consistency.

  • PyAutoGUI: Venturing beyond the web, PyAutoGUI offers capabilities to automate GUI tasks, scripting repetitive tasks, and ensuring smooth workflows.

  1. Game Development: The realm of entertainment has seen Python's influence as well.

  • Pygame: Serving as an entry point into game development, Pygame provides the essentials to craft interactive video games, making game creation accessible and engaging.

  • Panda3D: Merging Python's simplicity with C++'s performance, Panda3D specializes in 3D rendering, allowing developers to create visually rich games and simulations.

Domain

Tool/Library

Application Description

Web Development

Django

High-level framework for web application creation. 

Flask

Micro framework tailored for simplicity. 

Data Analysis 

Pandas

Essential tool for data manipulation with functionalities ranging from reshaping to aggregating data. Indispensable for data wrangling.

NumPy

Preferred by researchers and analysts for numerical computing and handling complex mathematical operations over extensive datasets. 

Artificial Intelligence

TensorFlow

Enables the creation of neural networks and AI models. Flexible and scalable for both research and production.

scikit-learn

Its intuitive API and efficiency make it essential for data scientists.

Automation

Selenium

Web automation tool that simulates browser activities. Assists in testing web applications.

PyAutoGUI

Automates GUI tasks, scripting repetitive tasks for smoother workflows.

Game Development

Pygame

Entry point into game development, offering essentials for interactive video games.

Panda3D

Merges Python's simplicity with C++'s performance. Specializes in 3D rendering, enabling visually rich game and simulation creation.

Advantages of Python

Python stands as a powerhouse in the programming realm, offering a plethora of advantages that render it a preferred choice for many developers. Let's take a look at a few of them:

  • Readability: One of Python's hallmarks is its immaculate syntax, which prioritizes clarity and simplicity, allowing for rapid comprehension and modification.

  • Scalability: Equally adept at powering bite-sized scripts and mammoth applications, Python scales with your needs.

  • Versatile Libraries: Python boasts a rich ecosystem, accommodating diverse project requirements, from data science to web development.

  • Cross-platform Operability: Python scripts can traverse multiple operating systems without requiring alterations.

  • Dynamic Typing: Variables in Python automatically assume the type of the assigned value, eliminating the need for explicit declarations.

  • Stellar Community Support: A vast, active community ensures that resources, tutorials, and solutions are perpetually available.

  • Integration Potential: Python offers effortless integration with other languages and tools, further extending its utility and versatility.

Conclusion

Navigating the Python landscape requires an intimate understanding of its execution mechanics. With its sprawling applications and undeniable advantages, mastering how to run Python programs is imperative for any professional in the tech realm. As our digital horizon continues to expand, the role of Python becomes increasingly salient. For those seeking to further hone their skills and delve deeper into Python's intricacies, upGrad offers meticulously curated courses designed to propel your expertise to new heights.

FAQS

1. How to run Python script from Python shell?

To run Python script from Python shell, initiate the Python shell, then employ the exec(open("filename.py").read()) command to run the script.

2. Where to write Python code in Windows?

Options abound: consider utilizing IDLE, PyCharm, or even Visual Studio Code as your primary editor.

3. How to run Python file in terminal windows?

Navigate to your script's directory in the terminal, then deploy the Python filename.py command.

4. How to run Python file in terminal Ubuntu?

After locating your script's directory in the terminal, invoke it using the Python3 filename.py command.

5. How to write code in Python for beginners?

Initiate with foundational concepts, leverage tutorials, and immerse in practical projects. Explore upGrad's beginner-centric courses for structured insights.

Leave a Reply

Your email address will not be published. Required fields are marked *