Python: Force a Variable to be a Certain Data Type

Python: Force a Variable to be a Certain Data Type

Overview

This article will explain how to create a variable in Python that can be specified, to take a certain data type. This tutorial showcases one scenario where the variable will always accept an integer and another where it will accept a string.

Materials

  • Computer

  • Python

  • IDE

Procedure: Create a Function How to Always Accept an Integer

First, declare a function and within it, a while loop by stating "while True:"

#!/usr/bin/env python3

def declare_variable():
    while True:

While statements always execute a set of commands within the block if it is true. In this case, it will always execute the code if it is set to "True".

Within the while statement, implement a try and except statement. In the try block, specify the variable to take an integer and the keyword "break". If a number is successfully passed and the "break" is not in the code, it will still ask for a number. "break" exits the block if it receives a successful output.

"except" is added to Python scripts to print out code if it receives a certain error. If an integer is not received, usually it would be a ValueError and exit the program. By implementing "except ValueError" and writing code within the block, will execute the code and continue the program.

#!/usr/bin/env python3

def declare_variable():
    while True:
        try:
            pass_a_number = int(input("Please enter a number:"))
            break
        except ValueError:
            print("Invalid input. ", end="")

Afterward, an, if and else statement is implemented to check if the variable passed, is an integer. If an integer is not passed, then the if statement will re-execute the function again to ask for an integer.

#!/usr/bin/env python3
# Completed Script

def declare_variable():

    while True:
        try:
            pass_a_number = int(input("Please enter a number: "))
            break
        except ValueError:
            print("Invalid input. ", end="")

    if pass_a_number != int(pass_a_number):
        print(declare_variable())
    else:
        return "The integer " + str(pass_a_number) + " was passed."

print(declare_variable())

Procedure: Create a Function How to Always Accept a String

First, declare a function and a variable that accepts a string data type:

#!/usr/bin/env python3

def check_for_string():
    validate_string = input("Enter a word: ")

Next, write an if and else statement to check if the variable "validate_string" is a string by using the built-in function ".isalpha()". ".isalpha()" checks if any variable contains a string data type only. If "validate_string" is a string data type, then the else statement executes the "check_for_string()" function again to accept a string data type.

#!/usr/bin/env python3
# Completed Script

def check_for_string():
    validate_string = input("Enter a word: ")

    if validate_string.isalpha() == True:
        return print(validate_string)
    else:
        print("Not a valid word.")
        check_for_string()

check_for_string()

Source Code

https://github.com/AndrewDass1/SCRIPTS/tree/main/Python/Check_For_Data_Types