Python Scripting Tutorial for Beginners

python-scripting-tutorial-for-beginners

If you are planning to learn Python then I will recommend you to start with scripting. There is a little bit of confusion (or difference) between scripting, coding, and programming which I will also explain later in this article. In this tutorial, I will guide you on what is scripting and how you can learn it for Python.

What is scripting?

Basically, scripting is a small piece of code which you can write fast and test quickly. Let’s say you are working on a project where lots of functionality and codes need to be written. All of those codes, you will not be able to write at the same time right? In this case, you may get lots of errors and end up spending lots of time. So this is not the proper way.

Instead of that, we should write small pieces of code for each functionality and test it separately. If it works fine then we can add this small piece of to the main project code. We call this small
piece of code a script.

Note that in scripting we generally keep our code simple. We do not add many functions and classes. Scripting is just for testing your concept. However sometimes we use scripting in some of our projects if the team size is small.

Key Characteristics of Scripting

As I mentioned earlier, the main feature of scripting is easy to learn and easy to implement without any complexity. Let’s now see some areas where we mostly use scripting.

  • Automation: Scripts can automate tasks such as file manipulation, program execution, web scraping, and routine system administration.
  • Ease of Use: Scripting languages are usually easier to learn and use compared to full-fledged programming languages.
  • Rapid Development: They allow for quick development and testing of code snippets without the need for compilation.
  • Flexibility: Scripts can be easily modified and are often used for ad-hoc tasks.

Difference Between Scripting, Coding and Programming

We often use scripting, coding, and programming terms for similar kinds of tasks. Theoretically, also there is no difference between those terms. But as you gain experience in the development field, you can observe that there is a slight difference between these terms in terms of the way we write our code.

Coding is the most general term. It refers to the act of writing code in any programming language. Coding is the process of translating requirements and logic into a language (programming language) that a computer can understand.

As I said earlier scripting usually refers to writing small programs, known as scripts, that are meant to be run in real-time by an interpreter. It is often used to automate tasks and can be written in scripting languages like Python or JavaScript. Scripting languages are typically interpreted, meaning they don’t require a compilation step before execution.

Programming is a more comprehensive term that is not only writing code but also involves problem-solving, designing algorithms, and understanding data structures.

We mostly use term programming while we write complex and huge codes. For example, let’s say you are developing an application or software. Here you need to write a huge amount of codes for separate modules. Here we can say we are writing programs to make an application.

So we can say while all scripting is coding, not all coding is scripting. Similarly, programming includes coding as part of the process of creating software, but coding can also be done for smaller tasks (scripting).

Is Python good for scripting?

The answer is Yes. Currently, Python is the most popular scripting language on the internet. The interesting part is that you can use Python for both scripting, coding, and programming.

In short, you can do small to large all kinds of development with Python. It has extensive support of libraries which you can use to perform all types of tasks.

This is the reason Python is gaining popularity day by day. Whether you are a beginner or an experienced developer, Python can definitely ease your development process.

Now to make it clear, the question is Java a scripting language or not? I would say no. Because to run a simple code in Jave you need to connect several dots (components and classes).

But in case you Python, you just need to install this language. Type your code and hit enter to see the output in the console. But you can also write complex object-oriented codes in Python.

Common Scripting Languages

Python: Known for its readability and wide range of applications, from web development, desktop application development, to data analysis.

JavaScript: Primarily used for client-side web development to create interactive web pages.

Bash: Used in Unix-based systems for command-line scripting and automating system tasks.

Ruby: A dynamic, object-oriented language often used for web development. Scripting can be done on both the client side (in the user’s web browser) and the server side (on a backend web server).

What is Python scripting used for?

Python scripting is used for a wide range of tasks across various fields due to its versatility and ease of use. Here are some common uses:

Data Analysis and Machine Learning

Python is extensively used in data science for statistical calculations, data visualization, and building machine learning models. This is one of the reasons for its popularity. Machine learning is gaining popularity nowadays. So Python is also gaining popularity.

I started my career in Data Science with R language but after some years I had to move to Python and currently, I do Python scripting almost every day.

Web Development

Currently, Python is also gaining popularity for developing websites and web applications also. It has frameworks like Django and Flask which will help you to develop any complex and secure website easily.

Desktop Development

You can also use Python to develop desktop applications using libraries like TkInter. Once you make the application, you can easily convert that application’s Python code to an exe file.

Automation and Scripting

Python scripts can automate repetitive tasks, such as file management or system administration. One example of this automation is web scrapping.

I love doing web scraping using Python. It is so powerful and flexible. Whether you want to crawl data from a simple or complex dynamic website, you can easily do it using Python.

Data Engineering

Python helps in the processing and movement of large amounts of data. It has libraries to connect all possible databases. Once you import that data to Python you can perform any kind of data engineering using a library like Pandas, numpy, etc.

Also Read:  Measure Function Execution Time in R

Python Scripting Tutorial

Before jumping into the Python scripting tutorial, some basics you need to know. Basics like: how to install Python, how to run Python script, how to install libraries, etc. If you already know this you can skip this part and move on to the tutorial part.

Install Python

There are mainly three ways to install Python. They are:

1. Install standard Python

If you want lightweight Python then you should install standard Python. First, go to the Official Python website and download Python. I will recommend you to download Python 3 and above. There is no point in using Python 2.x currently.

After downloading, I think I don’t need to tell you how to install it right? But one point I want to mention. During installation, make sure to check the option to add Python to the PATH when prompted.

add-python-to-path-while-installing-python-or-anaconda

2. Install Anaconda

If you are planning to use Python for data science, then I will recommend you to install Anaconda. It is a free and open-source distribution of the programming languages Python and R. Anaconda is designed specifically for data science, machine learning, and scientific computing.

I personally use it for my day-to-day data science tasks. You can easily create virtual environments here. In standard Python sometimes for complex machine learning libraries, you may get error, but there is less chance of that in Anaconda.

To download anaconda vistit their archive from this link. Download the required version as per your system configuration. During installation, make sure to check the option to add Python to the PATH when prompted.

3. Install Miniconda

One disadvantage of using anaconda is its size. If you want the same flavor of Anaconda and also want to keep the installation size small, you can install Miniconda for Python.

I will not guide you in this Python scripting tutorial, I have an article for this installation which you can refer to: Install Miniconda for Machine Learning.

How to Run Python Script

There are various ways to run a Python script on your computer. Below are some popular one:

Using IDE

If you are a serious Python developer then you should use a IDE to write your Python script. There are various IDEs available to write Python scripts. I personally like Jupyter Notebook for writing Python scripts.

For larger code (programming) I use PyCharm. But this is not the end. There are some other IDEs you can also try, let me list some popular of them: Jupyter Notebook, Pycharm, VS Code, Spyder, etc.

Using .py Script file

First, write a Python script using any text editor like Notepad++. Save that script as a .py file inside some folder directory. Then On Windows, press Win + R, type cmd, and hit Enter to open a command prompt.

Now use cd command to navigate to the directory where your Python script is located (cd path/to/your/script). Once you’re in the correct directory, run the script by typing: python script_name.py (Replace script_name.py with the name of your Python script).

change-working-directoy-to-start-multiple-python-scripts-at-once

After running the command, the output of your script will be displayed in the command line window. If your script requires arguments, you can pass them right after the script name. For example: python script_name.py arg1 arg2. Not only one Python script. In the similar way you can run multiple Python scripts simultaneously from a single command prompt.

Using command Line

In your Command line type “python” and press enter. Once you do that a Python interpreter will open in that command prompt. Type your Python code and hit enter to see the output.

run-python-script-in-command-prompt

If your code is less size (2-3 lines) then only try this method else I will not recommend you to do this. Once you are done with your Python script execution, type “quit()” and hit enter to come out from the Python interpreter.

Install Python libraries

To install Python libraries you need to type below command in your command prompt:

pip install library_name

Replace library_name with the actual name of the library you want to install.

To install a specific version of a library, use below command:

pip install library_name==version_number

For a minimum version, use:

pip install "library_name>=version_number

If you need to upgrade a library to the latest version, use:

pip install --upgrade library_name

If you want to install multiple libraries with a single command read this article: pip install multiple packages in Python. I am not including that in this Python scripting tutorial.

What is Virtual Environment ?

Once you become a Python developer you will be doing lots of projects. Now for each project you may use different versions of Python and different virsions of libraries.

So before srating each project will not re install your Python and libraries right. In that case you can use virtual environment to keep each of your project separate.

If you want to learn more about virtual environment, you can read this article: Conda Virtual environment Cheatsheet.

Basics of Python Scripting

Okay, let me now start the Python scripting tutorial. In this tutorial, I will share some basic and simple examples to get you started with Python scripting.

Hello World

Let’s start with a basic script that prints “Hello, World!” to the console. This is a traditional first step in learning any programming language.

Note: In Python scripting, the character # is used to make a comment. This means if # is there at the beginning of any line, that line will not be executed.

# This is a comment in Python. It's not executed as code, so you can use it to explain what your code does.

# The 'print' function outputs text to the console.
print("Hello, World!")
Output:
Hello, World!

Variables

A variable is a name that refers to a value. It’s like a label you can attach to something, so you can refer to it later.

To create a variable, you just assign it a value with the = operator. Python is dynamically typed, which means you don’t need to declare the type of the variable when you create one.

x = 5
name = "Sonia"
print(name)    # Output: Sonia

You can update a variable anytime by reassigning it to a new value. We use variables to hold data that our program can manipulate.

Also Read:  What is the difference between ' ' and " " in python?

Data Types

Data types are an essential concept in Python as they tell the interpreter how to handle the data stored in a variable. Below is an overview of the basic data types in Python:

Integers (int): These are whole numbers, positive or negative, without decimals. Examples: -1042.

Floating-Point Numbers (float): These are numbers with a decimal point or in exponential (E) form. Examples include 3.14-0.0012e2 (which is 200).

Strings (str): These are sequences of characters enclosed in quotes. They can be single quote ('...'), double quote ("..."), or triple quotes ('''...''' or """..."""). Examples "Hello"'Python3.8'.

Booleans (bool): This data type has two possible values: True or False. It’s often used in conditions and loops.

Lists (list): A list is an ordered collection of items which can be of different data types. Lists are mutable, meaning their elements can be changed. Example: [1, "a", 3.14].

Tuples (tuple): A tuple is similar to a list but it is immutable, meaning once created, its elements cannot be changed. Example: (1, "a", 3.14).

Dictionaries (dict): Dictionaries are unordered collections of key-value pairs. Keys must be unique and immutable. Example: {"name": "Alice", "age": 25}.

Sets (set): A set is an unordered collection of unique items. Example: {1, 2, 3}.

Below is a simple example Python script that demonstrates some of these data types:

# Integer
my_int = 10

# Float
my_float = 20.5

# String
my_string = "Hello, Python!"

# Boolean
my_bool = True

# List
my_list = [1, 2, 3, "Python", my_bool]

# Tuple
my_tuple = (my_int, my_float)

# Dictionary
my_dict = {"language": "Python", "version": 3.8}

# Set
my_set = {1, 2, 3, 4, 5}

# Printing the types
print(type(my_int))    # Output: <class 'int'>
print(type(my_float))  # Output: <class 'float'>
print(type(my_string)) # Output: <class 'str'>
print(type(my_bool))   # Output: <class 'bool'>
print(type(my_list))   # Output: <class 'list'>
print(type(my_tuple))  # Output: <class 'tuple'>
print(type(my_dict))   # Output: <class 'dict'>
print(type(my_set))    # Output: <class 'set'>

In this Python scripting tutorial, I gave you the concept of all data types. However, I did not use all data types in the above code to keep it small. You can try those on your own.

Operators

Operators in Python are special symbols that carry out arithmetic or logical computation. The value that the operator operates on is called the operand. Below is a brief overview of different types of operators in Python:

Arithmetic Operators

We use these type of operators to perform mathematical operations like addition, subtraction, multiplication, etc.

  • + Addition: Adds two operands. E.g: x + y
  • - Subtraction: Subtracts the second operand from the first. E.g: x - y
  • * Multiplication: Multiplies both operands. E.g: x * y
  • / Division: Divides the first operand by the second. E.g: x / y
  • % Modulus: Returns the remainder when the first operand is divided by the second. E.g: x % y
  • ** Exponentiation: Raises the first operand to the power of the second. E.g: x ** y
  • // Floor Division: Divides and returns the integer part of the quotient. E.g: x // y

Comparison (Relational) Operators

We use this type of operators to compare values. They return either True or False according to the condition.

  • == Equal to: True if both operands are equal
  • != Not equal to: True if operands are not equal
  • > Greater than: True if the left operand is greater than the right
  • < Less than: True if the left operand is less than the right
  • >= Greater than or equal to: True if the left operand is greater or equal to the right
  • <= Less than or equal to: True if the left operand is less or equal to the right

Logical Operators

Logical operators to combine conditional statements.

  • and Logical AND: True if both the operands are true
  • or Logical OR: True if at least one of the operands is true
  • not Logical NOT: True if the operand is false

Assignment Operators

These are used to assign values to variables.

  • = Simple assignment: Assigns a value to the variable
  • += Add AND: Adds the right operand to the left operand and assigns the result to the left operand
  • -= Subtract AND: Subtracts the right operand from the left operand and assigns the result to the left operand
  • *= Multiply AND: Multiplies the right operand with the left operand and assigns the result to the left operand
  • /= Divide AND: Divides the left operand by the right operand and assigns the result to the left operand
  • %= Modulus AND: Takes modulus using two operands and assigns the result to the left operand
  • **= Exponent AND: Performs exponential calculation on operators and assigns value to the left operand
  • //= Floor Division AND: Performs floor division on operators and assigns value to the left operand

Bitwise Operators

These are used to perform bitwise calculations on integers.

  • & Bitwise AND
  • | Bitwise OR
  • ^ Bitwise XOR
  • ~ Bitwise NOT
  • << Bitwise left shift
  • >> Bitwise right shift

Example Code to use Operators

Below is an example Python script that uses some of these operators:

# Arithmetic operators
addition = 5 + 3
subtraction = 5 - 3
multiplication = 5 * 3
division = 5 / 3

# Comparison operators
is_equal = (5 == 3)
is_not_equal = (5 != 3)

# Logical operators
logical_and = (5 < 3 and 5 > 3)
logical_or = (5 < 3 or 5 > 3)
logical_not = not(5 < 3)

# Assignment operators
x = 5
x += 3  # x is now 8
x -= 2  # x is now 6

# Output results
print("Addition:", addition)
print("Subtraction:", subtraction)
print("Multiplication:", multiplication)
print("Division:", division)
print("Is 5 equal to 3?:", is_equal)
print("Is 5 not equal to 3?:", is_not_equal)
print("Logical AND (5 < 3 and 5 > 3):", logical_and)
print("Logical OR (5 < 3 or 5 > 3):", logical_or)
print("Logical NOT (not(5 < 3)):", logical_not)
print("Value of x after += and -= :", x)
Output:
Addition: 8
Subtraction: 2
Multiplication: 15
Division: 1.6666666666666667
Is 5 equal to 3?: False
Is 5 not equal to 3?: True
Logical AND (5 < 3 and 5 > 3): False
Logical OR (5 < 3 or 5 > 3): True
Logical NOT (not(5 < 3)): True
Value of x after += and -= : 6

Note: In this Pytho scripting tutorial, I tried to give you concept of all oparators. But to keep the code small, I did not use all of them.

Operators are the building blocks of any programming language. They allow you to perform operations on data and variables. As you practice, you will become more familiar with how and when to use each operator.

Control Structures

Control structures are fundamental elements in programming that allow you to control the flow of execution of the code based on certain conditions or the occurrence of specific events. In Python, the primary control structures are if statementsfor loops, and while loops.

if Statement

We use the if statement to execute a block of code only if a specified condition is true.

# if statement
x = 10
if x > 5:
    print("x is greater than 5")
Output:
x is greater than 5

else and elif Statements

We can combine the else statement with an if statement to run a block of code when the condition is false. The elif (short for else if) statement allows you to check multiple expressions for True and execute a block of code as soon as one of the conditions evaluates to True.

# if-elif-else statement
age = 18
if age < 13:
    print("Child")
elif age < 20:
    print("Teenager")
else:
    print("Adult")
Output:
Teenager

for Loops

We use for loop in Python to iterate over a sequence (like a list, tuple, dictionary, set, or string) with the ability to execute a block of code for each item in the sequence.

# for loop
fruits = ["apple", "banana", "cherry"]
for fruit in fruits:
    print(fruit)
Output:
apple
banana
cherry

while Loops

The while loop enables you to execute a set of statements as long as a condition is true.

# while loop
i = 1
while i < 6:
    print(i)
    i += 1
Output:
1
2
3
4
5

break and continue Statements

The break statement can be used to stop the loop before it has looped through all the items. The continue statement can be used to stop the current iteration of the loop and continue with the next.

# break and continue
for i in range(1, 10):
    if i == 5:
        break  # Exit the loop when i is 5
    if i % 2 == 0:
        continue  # Skip the rest of the loop if i is even
    print(i)
Output:
1
3

These control structures are the building blocks for creating complex logic in your programs. By combining them in various ways, you can solve a wide range of programming problems. Practice using these structures to become more familiar with how they work and what you can do with them.

Also Read:  5 Best Book for Learning Python

Functions

In Python, a function is a block of organized, reusable code that is used to perform a single, related action. Functions provide better modularity for your application and a high degree of code reusing.

You can define a function using the def keyword, followed by a function name with parentheses and a colon. The indented block of code following the colon is the body of the function.

# Defining a function
def greet():
    print("Hello, welcome to Python functions!")

After defining a function, you can call it by using the function name followed by parentheses.

# Calling a function
greet()  # This will output: Hello, welcome to Python functions!

Functions can take parameters, which are variables that act as placeholders for the values that are passed into the function. When you call the function, you provide arguments, which are the actual values. A function can return a value back to the caller using the return statement.

# Function returning a value
def add(x, y):
    return x + y

# Calling function and storing the returned value
result = add(5, 3)
print(result)  # This will output: 8

Input Output

Let’s now try something a bit more interactive. We’ll write a script that asks for your name and then greets you.

# Ask the user for their name
name = input("What is your name? ")

# Greet the user
print("Hello, " + name + "!")

Once you run the above Python script, you will be asked to enter (or type) a string (in this case name). input() is a function that allows you to take user input.

Whatever the user types are then stored in the variable name, which we concatenate with the greeting in the print() function. Once you type the string and hit enter below output will be displayed.

Output:
What is your name? Anindya
Hello, Anindya!

Libraries

I do not want to make this Python scripting tutorial long. So this is the last concept I will share with you.

In all the above examples, I did not use any libraries. Only used basic Python scripting. So thought of sharing this too.

Basically, a library is group of functions. You can import a single function or multiple functions from a library which you want to use in your Python script.

Advantage of using libraries is that you can easily use any complex function just from the library. Someone spend lots of time to write huge amount of codes for all functions of that library. You can utilize those very easily.

Below is an example of using library in Python script.

import math
print(math.sqrt(16))  # Prints 4.0

Now you can achieve same result by using below code:

# Calculate the square root of 16 without using the math library
sqrt_value = 16 ** 0.5
print(sqrt_value)  # This will print 4.0

Note: This is a simple example just for demonstration. In real world there are more complex works where you must use libraries.

Examples of Python Script

There are n numbers of examples of Python scripting. Listing some of them which is currently poking my mind.

  • Simple Calculator
  • Webscraping in Python
  • Send SMS using Python
  • Update Google Sheet from Python Script
  • Generate Synthetic Tabular Test Data in Python

Python Scripting Resources

There are various places where you can find tutorials to learn Python scripting. The medium can vary from person to person. Some like YouTube videos, and some prefer to learn from courses.

Someone likes to learn from books and a person like me prefers learning from blogs. Because in blogs all codes are easily accessible and I can test it instantly while learning something.

If you want to learn from books then you should read this article: 5 Best Book for Learning Python. If you like to learn Python from courses then I will recommend you to take this Udemy course: Learn Python in 100 days of coding.

Conclusion

In this tutorial, I explained everything about Python scripting. The difference between programming and coding. Different ways to execute Python script.

Also, I gave you tutorials to learn the basics of Python scripting like: variables, Data types, operators, Pythonic loops, and functions. These are the main and most important things you should consider first
while learning Python scripting.

This is it for this article. If you have any questions or suggestions regarding this Python scripting tutorial article, please let me know in the comment section below.

Leave a comment