Home Python Python Scripts Beginner’s Guide

Python Scripts Beginner’s Guide

Python is not just a popular language for programming. It is also in in-demand because it can be used to create applications ranging from simple to complicated. If you’re new to Python programming and want to learn it quickly, this article is for you. This post explains python script examples using straightforward illustrations to help you understand Python basics.

Putting two threads together

In Python, there are numerous techniques to combine string values. The ‘+’ operator is the simplest way to combine two string values in Python. To learn how to merge two strings, create any Python script with the following. Two string values are allocated to two variables, with a third variable used to store the joined values, which will be printed later.

string1 = "Code"
string2 = "Underscored"
joined_string = string1 + string2
print(joined_string)

After running the script from the editor, the following output will show. The words “Code” and “Underscored” are combined here, and the result is “CodeUnderscored.”

Format floating point in the string

In programming, a floating-point number is necessary to generate fractional values, and formatting the floating-point integer for programming reasons is sometimes required. There are numerous ways to format a floating-point number in Python.
The following script formats a floating-point value using string formatting and string interpolation. The format() function with format width is used in string formatting, and string interpolation uses the percent ” symbol with the format with width.
According to the formatting width, five digits are set before the decimal point, and two digits are set after.

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

# Use of String Interpolation
float_var_two = 863.2378
print("%5.2f" % float_var_two)

Raising a number to a power

There are numerous ways to calculate a_var^n_var in Python. Three techniques to calculate a_var^n_var in Python are shown in the script below. The a_var^n_var is calculated using the double ‘‘ operator, the pow() method, and the math.pow() method. Numeric values are used to initialize the values of a_var and n_var. The techniques double ‘‘ and pow() are used to calculate the power of integer values. math.pow() can be used to calculate the power of fractional values, as seen in the script’s last section.

import math
#values assignment to a_var and n_var
a_var = 4
n_var = 3

# Method One
power_var = a_var ** n_var
print("%d to the power_var %d is %d" % (a_var,n_var,power_var))

# Method Two
power_var = pow(a_var,n_var)
print("Value of %d to the power %d : %d" % (x_var,n_var,power_var))

# Method Three
Power_var = math.pow(2,6.5)
print("Value is %d to the power of %d :%5.2f" % (x_var,n_var,power_var))

Using boolean data types

The following script illustrates the various applications of Boolean types. The first output will report val1’s value, the Boolean value true. Only zero yields false as a Boolean value, while all positive and negative numbers return true.
Both the second and third outputs prints true for positive and negative numbers. Because the comparison operator returns false, the fourth output will display false for 0, and the fifth output will also print false.

# Boolean value
val_one = True
print(val_one)

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

num_var = -5
print(bool(num_var))

num_var = 0
print(bool(num_var))

# Boolean from comparison operator
val_1 = 6
val_2 = 3
print(val_1 < val_2)

Use of the If else clause

The following Python script demonstrates how to utilize a conditional statement. The if-else statement is declared slightly differently than in other languages in Python. In Python, unlike other languages, curly brackets are not required to define the if-else block, but the indentation block must be utilized appropriately, or the script will fail. The script uses a simple if-else statement to check whether the value of the number variable is more than or equal to 70 or not. After the ‘if’ and ‘otherwise’ blocks, a colon(:) is used to mark the beginning of the block.

# Assigning a numeric value
num_var = 85

# Check the is more than 80 or not
if (num_val >= 80):
  print("You are successful ")
else:
  print("You have failed")

Using the AND and OR operators

The following script demonstrates the AND and OR operators in the conditional statement. If both criteria are true, the AND operator returns true, and the OR operator returns true if any of the two conditions are true. As Computer and theory marks, two floating-point numbers will be used. The ‘if’ statement employs both AND and OR operators. According to the condition, the ‘if’ statement will return true if the Computer marks are greater than 40 and the theory marks are greater than or equal to 30, or if the total of Computer and theory marks is greater than or equal to 80.

# Take Computer marks
computer_marks = float(input("Enter students Computer marks: "))

# Input the students theory marks
theory_marks = float(input("Enter the Students Theory marks: "))

# Using the AND and OR operators, determine whether the condition is met.
if (computer_marks >= 40 and theory_marks >= 30) or (computer_marks + theory_marks) >=80:
  print("\nYou are successful")
else:
  print("\nYou have failed")

switch case statement

Python does not have a switch-case statement like other programming languages, but a custom function can be used to create one. The employee_details() function is built to mimic the switch-case expression in the following script. The function has only one parameter and a switcher dictionary. Each dictionary index is checked for the value of the function parameter.
If a match is detected, the function will return the corresponding value of the index; otherwise, the info_dic’s second parameter value. The return value of the info_dic.get() function.

# Switcher for implementing switch case options

def student_info(ID):
  info_dic = {
  "S001": "Student Name: Ken White",
  "S002": "Student Name: Sky Smith",
  "S003": "Student Name: Rob Joy",
  }
'''The initial arguments are returned if the match is found, and
nothing will be returned if no match is found. '''
return info_dic.get(ID, "nothing")

# Take the Student ID
ID = input("Enter the Student ID: ")
#Print the output
print(student_info(ID))

Using a While Loop

The following shows utilizing a while loop in Python. The colon(:) is used to establish the loop’s starting block, and all loop statements must be indented appropriately; otherwise, an indentation error would show. The counter value is set to 1 in the following script, which is utilized in the loop. The loop will iterate five times, printing the counter numbers each time. To reach the loop’s termination condition, the counter value is incremented by one in each iteration.

# Initialize counter
count= 1

# Iterate the loop 7 times
while count < 8:
  # Print the count value
  print ("The current count value: %d" % counter)
  # Increment the count
  count = count + 1

Using the “for Loop”

In Python, the for loop is used for a variety of applications. The starting block of this loop must be declared with a colon(:), and the statements must be indented properly. A list of laptop names is defined in the following script. Further, a for loop is vital in iterating and outputting each item on the list. The len() method is used to count the total number of items in the list and to set the range() function’s limit.

# Initialize the list
laptops = ["HP", "DELL", "Chromebook","Lenovo", "IBM","Apple", "Toshiba"]
print("The Trendiest Laptops in the market are:\n")

# Iterating through the list above using a for loop
for lap in range(len(laptops)):
  print(laptops[lap])

From another Python script, run a Python script

It is occasionally necessary to use the script of one Python file in another Python file. It’s simple to accomplish, just like importing any module with the import keyword. Two variables are initialized with string values in the tour.py file.

This file is imported with the alias ‘t’ in the implementation.py file. It is where you’ll find a list of month names. The flag variable is used to print the value of the local_tourism variable for June and July only once. The overseas_tourism variable’s value will be printed for the month of ‘December.’ When the else section of the if-else if-else sentence is completed, the other nine-month names will be printed.

# tour.py
# Initialize values

local_tourism = "Summer Vacation"
overseas_tourism = "Winter Vacation"

 

# implementation.py
# Another Python script should be imported.
import tour as t

# months' list initialization
months_var = ["Jan", "Feb", "March", "April", "May", "June",
"July", "Aug", "Sept", "Oct", "Nov", "Dec"]

# One-time printing of the summer vacation flag variable
flag = 0

# Iterating a list using a for loop
for m in months_var:
  if m == "June" or m == "July":
    if flag == 0:
      print("Now",t.local_tourism)
    flag = 1
  elif month == "Dec":
    print("Now",t.overseas_vacation)
  else:
    print("The month currently is",m)

Using Regex

In Python, a regular expression, or regex, is used to match or search for and replace any part of a string based on a pattern.
In Python, there’s the module used to use a regular expression. The script below demonstrates how to use regex in Python. The script’s pattern will match strings with a capital letter as the first character. The pattern will be matched with a string value using the match() method.

A success message will be printed if the method returns true; else, an instructional message will be printed.

# Importing the re module

import re

# Taking any data string.
string = input("Entering a string value: ")

# Create a search pattern.
pattern = '^[A-Z]'

# match the pattern to the value input
result_var = re.match(pattern, string)

# Print message based on the return value
if result_var:
  print("The capital letter is used to begin the input value. ")
else:
  print("You must begin typing string with a capital letter. ")

In the following output, the script is run twice. The match() method returns false for the first execution, and the second execution returns true.

Using Regex
Using Regex

Application of getpass

getpass is a handy Python package for gathering password input from the user. The getpass module is demonstrated in the following script. The getpass() method is used to take the input and convert it to a password, and the ‘if’ statement is used to compare the input value to the defined password. If the password matches, the message “you are authenticated” will appear; otherwise, “you are not authenticated” will appear.

# import getpass module
import getpass

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

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

When using the terminal to run the script, the input value is not displayed like it is with other Linux passwords. As seen in the output, the script is run twice from the terminal. Once with an invalid password and once with a valid password.

Application of the date format

In Python, the date value can be formatted in various ways. The following script uses the datetime module to set the current and future dates. The current system date and time are read using the today() function. The formatted date value is then printed using the date object’s various property names. The next section of the script demonstrates how to assign and print a custom date value.

from datetime import date

# Check the time and date.
date_today = date.today()

# The formatted date should be printed.
print("Today is :%d-%d-%d" % (date_today.day, date_today.month, date_today.year))

# Creation of a custom date.
custom_date = date(2022, 5, 10)
print("The specified date is:",custom_date)

After running the script, the following output will show.

date format
date format

Adding or removing an item from a list

Python’s list object is used to solve a variety of problems. Python includes several built-in functions to work with the list object. The following example demonstrates how to add and remove new items from a list. The script declares a list of four elements. The Insert() method adds a new item to the list’s second place. The remove() method is used to find and delete a specific item from a list. Following the insertion and deletion, the list is printed.

# Declaration of computer companies
comp_companies = ["Apple","Google","Uber","IBM"]

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

# Displaying list after inserting
print("The Computer Companies list after insert:")
print(comp_companies)

# Removing an item from the list
comp_companies.remove("Google")

# Print the list after delete
print("The Computer Companies list after delete:")
print(comp_companies)

After running the script, the following output will show.

Adding or removing an item from a list
Adding or removing an item from a list

List comprehension

In Python, list comprehension builds a new list from text, tuple, or other lists. The for loop and lambda function can be used to accomplish the same goal. The script below demonstrates two different applications of list comprehension. List comprehension is used to turn a string value into a list of characters. A tuple is then turned into a list in the same manner.

# Using list comprehension, make a character list.
code_char_list = [ char for char in "codeunderscored" ]
print(code_char_list )

# Define a tuple of websites
comp_companies = ("Apple","Google","Uber","IBM")

# Using list comprehension, create a list from a tuple.
companies_list = [ site for site in comp_companies ]
print(companies_list)

Adding and Search data in a dictionary

Like the associative array in other programming languages, the dictionary object is used in Python to store numerous data. The subsequent script is responsible for adding a new item to the dictionary and searching for any item.
The script declares a dictionary of customer information, with the index containing the Students ID and the value containing the customer name. After that, a new customer record is added to the dictionary’s end. A Students ID is used to do a dictionary search. The ‘for’ loop and the ‘if’ condition traverse the dictionary’s indexes and look for the input value.

# Define a dictionary
student_info = {'67':'Tom Keen','35':' Ali Flex',
'16':'Sam Mike','23':'Ann White', '69':' Joy Brown'}

# Append a new data
student_info['16'] = 'Ferdous Smiles'

print("The Student names are:")

# Print the values of the dictionary
for stu in student_info:
  print(student_info[stu])
# Take Students ID as input to search
name = input("Enter Students's ID:")
# Search the ID in the dictionary

for stu in student_info:
  if stu == name:
    print(student_info[stu])
break

Conclusion

The example scripts we have looked at in this article are must-know for any beginner who intends to excel in Python. We hope the examples on this page will help you quickly accelerate your Python learning.

You may also like

Leave a Comment