Python

30 python scripts examples


Python is a very popular and demanding programming language now because it is suitable for developing very simple to complex applications. If you are new in python programming and want to learn the python from the basics in a short time, then this article is for you. 30 python scripts examples are explained in this article by using very simple examples to know the basics of the python.The list of topics that covered in this article are mentioned below. We recommend buying our Python Language Cheat Sheet from Amazon to have on your desk as you are learning.

01. Hello World
02. Join two strings
03. Format floating point in the string
04. Raise a number to a power
05. Working with Boolean types
06. If else statement
07. Using AND and OR operators
08. Switch case statement
09. While Loop
10. For Loop
11. Run one Python script from another
12. Use of a command-line argument
13. Use of regex
14. Use of getpass
15. Use of date format
16. Add and remove the item from a list
17. List comprehension
18. Slice data
19. Add and search data in the dictionary
20. Add and search data in the set
21. Count items in the list
22. Define and call a function
23. Use of throw and catch exception
24. Read and Write File
25. List files in a directory
26. Read and write using pickle
27. Define class and method
28. Use of range function
29. Use of map function
30. Use of filter function

Create and execute the first python script:

You can write and execute a simple python script from the terminal without creating any python file. If the script is large, then it requires writing and saves the script in any python file by using any editor. You can use any text editor or any code editor like sublime, Visual Studio Code, or any IDE software developed for python only like PyCharm or Spyder to write the script. The extension of the python file is .py. The python version 3.8 and the spyder3 IDE of python are used in this article to write the python script. You have to install spyder IDE in your system to use it.

If you want to execute any script from the terminal, then run the ‘python’ or ‘python3’ command to open python in interaction mode. The following python script will print the text “Hello World” as output.

>>> print("Hello World")


Now, save the script in a file named c1.py. You have to run the following command from the terminal to execute c1.py.

$ python3 c1.py

If you want to run the file from spyder3 IDE, then you have to click on the run button

of the editor. The following output will show in the editor after executing the code.

Top

Joining two strings:

There are many ways to join string values in python. The most simple way to combine two string values in python is to use the ‘+’ operator. Create any python with the following script to know the way to join two strings. Here, two string values are assigned in two variables, and another variable is used to store the joined values that are printed later.

c2.py

string1 = "Linux"
string2 = "Hint"
joined_string = string1 + string2
print(joined_string)

The following output will appear after running the script from the editor. Here, two words, “Linux” and “Hint” are joined, and “LinuxHint” is printed as output.

If you want to know more about the other joining option in python, then you can check the tutorial, Python String Concatenation.

Top

Format floating point in the string:

Floating point number is required in programming for generating fractional numbers, and sometimes it requires formatting the floating-point number for programming purposes. There are many ways to exist in python to format the floating-point number. String formatting and string interpolation are used in the following script to format a floating-point number. format() method with format width is used in string formatting, and ‘%” symbol with the format with width is used in string interpolation. According to the formatting width, 5 digits are set before the decimal point, and 2 digits are set after the decimal point.

c3.py

# Use of String Formatting
float1 = 563.78453
print("{:5.2f}".format(float1))

# Use of String Interpolation
float2 = 563.78453
print("%5.2f" % float2)

The following output will appear after running the script from the editor.

If you want to know more about string formatting in python, then you can check the tutorial, Python String Formatting.

Top

Raise a number to a power:

Many ways exist in python to calculate the xn in Python. In the following script, three ways are shown to calculate the xn in Python. Double ‘*’ operator, pow() method, and math.pow() method are used for calculating the xn. The values of x and n are initialized with numeric values. Double ‘*’ and pow() methods are used for calculating the power of integer values. math.pow() can calculate the power of fractional numbers; also, that is shown in the last part of the script.

c4.py

import math
# Assign values to x and n
x = 4
n = 3

# Method 1
power = x ** n
print("%d to the power %d is %d" % (x, n, power))

# Method 2
power = pow(x, n)
print("%d to the power %d is %d" % (x, n, power))

# Method 3
power = math.pow(2, 6.5)
print("%d to the power %d is %5.2f" % (x, n, power))

The following output will appear after running the script. The first two outputs show the result of 43, and the third output shows the result of 26.5.

Top

Working with Boolean types:

The different uses of Boolean types are shown in the following script. The first output will print the value of val1 that contains the Boolean value, true. All positive are negative numbers return true as Boolean value and only zero returns false as a Boolean value. So, the second and third outputs will print true for positive and negative numbers. The fourth output will print false for 0, and the fifth output will print false because the comparison operator returns false.

c5.py

# Boolean value
val1 = True
print(val1)

# Number to Boolean
number = 10
print(bool(number))

number = -5
print(bool(number))

number = 0
print(bool(number))

# Boolean from comparison operator
val1 = 6
val2 = 3
print(val1 < val2)

The following output will appear after running the script.

Top

Use of If else statement:

The following script shows the use of a conditional statement in python. The declaration of the if-else statement in python is a little bit different than other languages. No curly brackets are required to define the if-else block in python like other languages, but the indentation block must be used properly other the script will show an error. Here, a very simple if-else statement is used in the script that will check the value of the number variable is more than or equal to 70or not. A colon(:) is used after the ‘if’ and ‘else’ block to define the starting of the block.

c6.py

# Assign a numeric value
number = 70

# Check the is more than 70 or not
if (number >= 70):
    print("You have passed")
else:
    print("You have not passed")

The following output will appear after running the script.

Top

Use of AND and OR operators:

The following script shows the uses of AND and OR operators in the conditional statement. AND operator returns true when the two conditions return true, and OR operator returns true when any condition of two conditions returns true. Two floating-point numbers will be taken as MCQ and theory marks. Both AND and OR operators are used in the ‘if’ statement. According to the condition, if the MCQ marks are more than equal to 40 and theory marks is more than or equal to 30 then the ‘if’ statement will return true or if the total of MCQ and theory is more than or equal to 70 then the ‘if’ statement will also return true.

c7.py

# Take MCQ marks
mcq_marks = float(input("Enter the MCQ marks: "))
# Take theory marks
theory_marks = float(input("Enter the Theory marks: "))

# Check the passing condition using AND and OR operator
if (mcq_marks >= 40 and theory_marks >= 30) or (mcq_marks + theory_marks) >= 70:
    print("\nYou have passed")
else:
    print("\nYou have failed")

According to the following output, if statement returns false for the input values 30 and 35, and returns true for the input values 40 and 45.

Top

switch case statement:

Python does not support a switch-case statement like other standard programming languages, but this type of statement can be implemented in python by using a custom function. employee_details() function is created in the following script to work like the switch-case statement. The function contains one parameter and a dictionary named switcher. The value of the function parameter is checked with each index of the dictionary. If any match found, then the corresponding value of the index will be returned from the function; otherwise, the second parameter value of the switcher.get() method will be returned.

c8.py

# Switcher for implementing switch case options
def employee_details(ID):
    switcher = {
        "1004": "Employee Name: MD. Mehrab",
        "1009": "Employee Name: Mita Rahman",
        "1010": "Employee Name: Sakib Al Hasan",
    }
    '''The first argument will be returned if the match found and
        nothing will be returned if no match found'''

    return switcher.get(ID, "nothing")

# Take the employee ID
ID = input("Enter the employee ID: ")
# Print the output
print(employee_details(ID))

According to the following output, the script is executed two times, and two employee names are printed based on the ID values.

Top

Use of while Loop:

The use of a while loop in python is shown in the following example. The colon(:) is used to define the starting block of the loop, and all statements of the loop must be defined using proper indentation; otherwise, indentation error will appear. In the following script, the counter value is initialized to 1 that is used in the loop. The loop will iterate 5 times and print the values of the counter in each iteration. The counter value is incremented by 1 in each iteration to reach the termination condition of the loop.

c9.py

# Initialize counter
counter = 1
# Iterate the loop 5 times
while counter < 6:
    # Print the counter value
    print("The current counter value: %d" % counter)
    # Increment the counter
    counter = counter + 1

The following output will appear after running the script.

Top

Use of for Loop:

for loop is used for many purposes in python. The starting block of this loop is required to define by a colon(:), and the statements are defined by using proper indentation. In the following script, a list of weekday names is defined, and a for loop is used to iterate and print each item of the list. Here, len() method is used to count the total items of the list and define the limit of the range() function.

c10.py

# Initialize the list
weekdays = ["Sunday", "Monday", "Tuesday",
            "Wednesday", "Thursday", "Friday", "Saturday"]
print("Seven Weekdays are:\n")
# Iterate the list using for loop
for day in range(len(weekdays)):
    print(weekdays[day])

The following output will appear after running the script.

Top

Run one Python script from another:

Sometimes it is required to use the script of a python file from another python file. It can be done easily, like importing any module by using the import keyword. Here, vacations.py file contains two variables initialized by string values. This file is imported in c11.py file with the alias name ‘v’. A list of month names is defined here. The flag variable is used here to print the value of vacation1 variable for one time for the months ‘June’ and ‘July’. The value of the vacation2 variable will print for the month ‘December’. The other nine-month names will be printed when the else part of the if-elseif-else statement will be executed.

vacations.py

# Initialize values
vacation1 = "Summer Vacation"
vacation2 = "Winter Vacation"

c11.py

# Import another python script
import vacations as v

# Initialize the month list
months = ["January", "February", "March", "April", "May", "June",
          "July", "August", "September", "October", "November", "December"]
# Initial flag variable to print summer vacation one time
flag = 0

# Iterate the list using for loop
for month in months:
    if month == "June" or month == "July":
        if flag == 0:
            print("Now", v.vacation1)
            flag = 1
    elif month == "December":
        print("Now", v.vacation2)
    else:
        print("The current month is", month)

The following output will appear after running the script.

Top

Use of command-line argument:

The following script shows the use of command-line arguments in python. Many modules exist in python to parse the command-line arguments ‘sys’ module is imported here to parse the command-line arguments. len() method is used to count the total arguments, including the script file name. Next, the argument values will be printed.

c12.py

# Import sys module
import sys

# Total number of arguments
print('Total arguments:', len(sys.argv))

print("Argument values are:")
# Iterate command-line arguments using for loop
for i in sys.argv:
    print(i)

If the script is executed without any command-line arguments, then the following output will appear that is showing the script filename.

The command-line argument values can be set in spyder editor by opening the Run configuration per file dialog box by clicking on the Run menu. Set the values with space by clicking the Command line options of General settings part of the dialog box.

If the script is executed after setting the values shown above, then the following output will appear.


The command-line argument values can be passed in the python script easily from the terminal. The following output will appear if the script is executed from the terminal.


If you want to know more about command-line arguments in python, then you can check the tutorial, How to parse arguments on command-line in Python.

Top

Use of regex:

Regular expression or regex is used in python to match or search and replace any particular portion of a string based on the particular pattern. ‘re’ module is used in python to use a regular expression. The following script shows the use of regex in python. The pattern used in the script will match those string where the first character of the string is a capital letter. A string value will be taken and match the pattern using match() method. If the method returns true, then a success message will print otherwise an instructional message will print.

c13.py

# Import re module
import re

# Take any string data
string = input("Enter a string value: ")
# Define the searching pattern
pattern = '^[A-Z]'

# match the pattern with input value
found = re.match(pattern, string)

# Print message based on the return value
if found:
    print("The input value is started with the capital letter")
else:
    print("You have to type string start with the capital letter")

The script is executed two times in the following output. match() function returns false for the first execution and returns true for the second execution.

Top

Use of getpass:

getpass is a useful module of python that is used to take password input from the user. The following script shows the use of the getpass module. getpass() method is used here to take the input as password and ‘if’ statement is used here to compare the input value with the defined password. “you are authenticated” message will print if the password matches otherwise it will print “You are not authenticated” message.

c14.py

# import getpass module
import getpass

# Take password from the user
passwd = getpass.getpass('Password:')

# Check the password
if passwd == "fahmida":
    print("You are authenticated")
else:
    print("You are not authenticated")

If the script runs from the spyder editor, then the input value will be shown because the editor console doesn’t support password mode. So, the following output shows the input password in the following output.

If the script executes from the terminal, then input value will not be shown like other Linux password. The script is executed two times from the terminal with an invalid and valid password that is shown in the following output.

Top

Use of date format:

The date value can be formatted in python in various ways. The following script uses the datetime module to set the current and the custom date value. today() method is used here to read the current system date and time. Next, the formatted value of the date is printed by using different property names of the date object. How a custom date value can be assigned and printed is shown in the next part of the script.

c15.py

from datetime import date

# Read the current date
current_date = date.today()

# Print the formatted date
print("Today is :%d-%d-%d" %
      (current_date.day, current_date.month, current_date.year))

# Set the custom date
custom_date = date(2020, 12, 16)
print("The date is:", custom_date)

The following output will appear after executing the script.

Top

Add and remove the item from a list:

list object is used in python for solving various types of problems. Python has many built-in functions to work with the list object. How a new item can be inserted and removed from a list is shown in the following example. A list of four items is declared in the script. Insert() method is used to insert a new item in the second position of the list. remove() method is used to search and remove the particular item from the list. The list is printed after the insertion and deletion.

c16.py

# Declare a fruit list
fruits = ["Mango", "Orange", "Guava", "Banana"]

# Insert an item in the 2nd position
fruits.insert(1, "Grape")

# Displaying list after inserting
print("The fruit list after insert:")
print(fruits)

# Remove an item
fruits.remove("Guava")

# Print the list after delete
print("The fruit list after delete:")
print(fruits)

The following output will appear after executing the script.


If you want to know more details about the insertion and deletion of the python script, then you can check the tutorial, “How to add and remove items from a list in Python”.

Top

List comprehension:

List comprehension is used in python to create a new list based on any string or tuple or another list. The same task can be done using for loop and lambda function. The following script shows two different uses of list comprehension. A string value is converted into a list of characters using list comprehension. Next, a tuple is converted into a list in the same way.

c17.py

# Create a list of characters using list comprehension
char_list = [char for char in "linuxhint"]
print(char_list)

# Define a tuple of websites
websites = ("google.com", "yahoo.com", "ask.com", "bing.com")

# Create a list from tuple using list comprehension
site_list = [site for site in websites]
print(site_list)

Top

Slice data:

slice() method is used in python to cut the particular portion of a string. This method has three parameters. These parameters are start, stop, and step. The stop is the mandatory parameter, and the other two parameters are optional. The following script shows the uses of the slice() method with one, two, and three parameters. When one parameter is used in the slice() method, then it will use the mandatory parameter, stop. When the two parameters are used in the slice() method, then start and stop parameters are used. When all three parameters are used, then start, stop, and step parameters are used.

c18.py

# Assign string value
text = "Learn Python Programming"

# Slice using one parameter
sliceObj = slice(5)
print(text[sliceObj])

# Slice using two parameter
sliceObj = slice(6, 12)
print(text[sliceObj])

# Slice using three parameter
sliceObj = slice(6, 25, 5)
print(text[sliceObj])

The following output will appear after running the script. In the first slice() method, 5 is used as the argument value. It sliced the five characters of text variables that are printed as output. In the second slice() method, 6 and 12 are used as arguments. The slicing is started from position 6 and stopped after 12 characters. In the third slice() method, 6, 25, and 5 are used as arguments. The slicing is started from position 6, and the slicing stopped after 25 characters by omitting 5 characters in each step.

Top

Add and search data in the dictionary:

dictionary object is used in python to store multiple data like the associative array of other programming languages. The following script shows how a new item can be inserted, and any item can be searched in the dictionary. A dictionary of customer information is declared in the script where the index contains the customer ID, and the value contains the customer name. Next, one new customer information is inserted at the end of the dictionary. A customer ID is taken as input to search in the dictionary. ‘for’ loop and ‘if’ condition is used to iterate the indexes of the dictionary and search the input value in the dictionary.

c19.py

# Define a dictionary
customers = {'06753': 'Mehzabin Afroze', '02457': 'Md. Ali',
             '02834': 'Mosarof Ahmed', '05623': 'Mila Hasan', '07895': 'Yaqub Ali'}

# Append a new data
customers['05634'] = 'Mehboba Ferdous'

print("The customer names are:")
# Print the values of the dictionary
for customer in customers:
    print(customers[customer])

# Take customer ID as input to search
name = input("Enter customer ID:")

# Search the ID in the dictionary
for customer in customers:
    if customer == name:
        print(customers[customer])
        break

The following output will appear after executing the script and taking ‘02457’ as ID value.


If you want to know more about the other useful methods of the dictionary, then you can check the tutorial, “10 most useful Python Dictionary Methods”.

Top

Add and search data in set:

The following script shows the ways to add and search data in a python set. A set of integer data is declared in the script. add() method is used to insert new data in the set. Next, an integer value will be taken as input to search the value in the set by using for loop and if condition.

c20.py

# Define the number set
numbers = {23, 90, 56, 78, 12, 34, 67}

# Add a new data
numbers.add(50)
# Print the set values
print(numbers)

message = "Number is not found"

# Take a number value for search
search_number = int(input("Enter a number:"))
# Search the number in the set
for val in numbers:
    if val == search_number:
        message = "Number is found"
        break

print(message)

The script is executed two times with the integer value 89 and 67. 89 does not exist in the set, and “Number is not found” is printed. 67 exists in the set, and “Number is found” is printed.

If you want to know about the union operation in the set, then you can check the tutorial, “How to use union on python set”.

Top

Count items in the list:

count() method is used in python to count how many times a particular string appears in other string. It can take three arguments. The first argument is mandatory, and it searches the particular string in the whole part of another string. The other two arguments of this method are used to limit the search by defining the searching positions. In the following script, the count() method is used with one argument that will search and count the word ‘Python’ in the string variable.

c21.py

# Define the string
string = 'Python Bash Java Python PHP PERL'
# Define the search string
search = 'Python'
# Store the count value
count = string.count(search)
# Print the formatted output
print("%s appears %d times" % (search, count))

The following output will appear after executing the script.

If you want to know more details about the count() method, then you can check the tutorial, How to use count() method in python.

Top

Define and call a function:

How user-defined function can be declared and called in python is shown in the following script. Here, two functions are declared. addition() function contains two arguments to calculate the sum of two numbers and print the value. area() function contains one argument to calculate the area of a circle and return the result to the caller by using the return statement.

c22.py

# Define addition function
def addition(number1, number2):
    result = number1 + number2
    print("Addition result:", result)

# Define area function with return statement
def area(radius):
    result = 3.14 * radius * radius
    return result

# Call addition function
addition(400, 300)
# Call area function
print("Area of the circle is", area(4))

The following output will appear after executing the script.


If you want to know details about the return values from a python function, then you can check the tutorial, Return Multiple Values from A Python Function.

Top

Use of throw and catch exception:

try and catch block are used to throw and catch the exception. The following script shows the use of a try-catch block in python. In the try block, a number value will be taken as input and checked the number is even or odd. If any non-numeric value is provided as input, then a ValueError will be generated, and an exception will be thrown to the catch block to print the error message.

c23.py

# Try block
try:
    # Take a number
    number = int(input("Enter a number: "))
    if number % 2 == 0:
        print("Number is even")
    else:
        print("Number is odd")

# Exception block
except (ValueError):
    # Print error message
    print("Enter a numeric value")

The following output will appear after executing the script.


If you want to know more details about the exception handling in python, then you can check the tutorial, “Exception Handling in Python”.

Top

Read and Write File:

The following script shows the way to read from and write into a file in python. The filename is defined in the variable, filename. The file is opened for writing using the open() method at the beginning of the script. Three lines are written in the file using the write() method. Next, the same file is opened for reading using the open() method, and each line of the file is read and printed using for loop.

c24.py

#Assign the filename
filename = "languages.txt"
# Open file for writing
fileHandler = open(filename, "w")

# Add some text
fileHandler.write("Bash\n")
fileHandler.write("Python\n")
fileHandler.write("PHP\n")

# Close the file
fileHandler.close()

# Open file for reading
fileHandler = open(filename, "r")

# Read a file line by line
for line in fileHandler:
  print(line)

# Close the file
fileHandler.close()

The following output will appear after executing the script.

If you want to know more details about reading and writing files in python, then you can check the tutorial, How to read and write to files in Python.

Top

List files in a directory:

The content of any directory can be read by using the os module of python. The following script shows how to get the list of a specific directory in python using the os module. listdir() method is used in the script to find out the list of files and folders of a directory. for loop is used to print the directory content.

c25.py

# Import os module to read directory
import os

# Set the directory path
path = '/home/fahmida/projects/bin'

# Read the content of the file
files = os.listdir(path)

# Print the content of the directory
for file in files:
    print(file)

The content of the directory will appear after executing the script if the defined path of the directory exists.

Top

Read and write using pickle:

The following script shows the ways to write and read data using the pickle module of python. In the script, an object is declared and initialized with five numeric values. The data of this object is written into a file using the dump() method. Next, the load() method is used to read the data from the same file and store it in an object.

c26.py

# Import pickle module
import pickle

# Declare the object to store data
dataObject = []
# Iterate the for loop for 5 times
for num in range(10, 15):
    dataObject.append(num)

# Open a file for writing data
file_handler = open('languages', 'wb')

# Dump the data of the object into the file
pickle.dump(dataObject, file_handler)

# close the file handler
file_handler.close()

# Open a file for reading the file
file_handler = open('languages', 'rb')

# Load the data from the file after deserialization
dataObject = pickle.load(file_handler)

# Iterate the loop to print the data
for val in dataObject:
    print('The data value : ', val)

# close the file handler
file_handler.close()

The following output will appear after executing the script.

If you want to know more details about reading and writing using pickle, then you can check the tutorial, How to pickle objects in Python.

Top

Define class and method:

The following script shows how a class and method can be declared and accessed in Python. Here, a class is declared with a class variable and a method. Next, an object of the class is declared to access the class variable and class method.

c27.py

# Define the class
class Employee:
    name = "Mostak Mahmud"
    # Define the method

    def details(self):
        print("Post: Marketing Officer")
        print("Department: Sales")
        print("Salary: $1000")

# Create the employee object
emp = Employee()

# Print the class variable
print("Name:", emp.name)

# Call the class method
emp.details()

The following output will appear after executing the script.

Top

Use of range function:

The following script shows the different uses of range function in python. This function can take three arguments. These are start, stop, and step. The stop argument is mandatory. When one argument is used, then the default value of the start is 0. range() function with one argument, two arguments, and three arguments are used in the three for loops here.

c28.py

# range() with one parameter
for val in range(6):
    print(val, end='  ')
print('\n')

# range() with two parameter
for val in range(5, 10):
    print(val, end='  ')
print('\n')

# range() with three parameter
for val in range(0, 8, 2):
    print(val, end='  ')
print('\n')

The following output will appear after executing the script.

Top

Use of map function:

map() function is used in python to return a list by using any user-defined function and any iterable object. In the following script, cal_power() function is defined to calculate the xn, and the function is used in the first argument of the map() function. A list named numbers is used in the second argument of the map() function. The value of x will be taken from the user, and the map() function will return a list of power values of x, based on the item values of the numbers list.

c29.py

# Define the function to calculate power
def cal_power(n):
    return x ** n

# Take the value of x
x = int(input("Enter the value of x:"))
# Define a tuple of numbers
numbers = [2, 3, 4]

# Calculate the x to the power n using map()
result = map(cal_power, numbers)
print(list(result))

The following output will appear after executing the script.

Top

Use of filter function:

filter() function of python uses a custom function to filter data from an iterable object and create a list with the items for those the function returns true. In the following script, SelectedPerson() function is used in the script to create a list of the filtered data based on the items of selectedList.

c30.py

# Define a list of participant
participant = ['Monalisa', 'Akbar Hossain',
               'Jakir Hasan', 'Zahadur Rahman', 'Zenifer Lopez']

# Define the function to filters selected candidates
def SelectedPerson(participant):
    selected = ['Akbar Hossain', 'Zillur Rahman', 'Monalisa']
    if (participant in selected):
        return True

selectedList = filter(SelectedPerson, participant)
print('The selected candidates are:')
for candidate in selectedList:
    print(candidate)

The following output will appear after executing the script.

Top

Conclusion:

The python programming basics are discussed using 30 different topics in this article. I hope the examples of this article will help the readers to learn python easily from the beginning.

About the author

Fahmida Yesmin

I am a trainer of web programming courses. I like to write article or tutorial on various IT topics. I have a YouTube channel where many types of tutorials based on Ubuntu, Windows, Word, Excel, WordPress, Magento, Laravel etc. are published: Tutorials4u Help.