Skip to main content

Python type() Function

When learning Python, you will work with different types of data, such as numbers, text, decimal values, and Boolean values. Python provides several built-in functions to help you work with these data types. One of the most useful functions is the type() function . The type() function tells you the data type of a value or variable. It helps you understand what kind of data Python is working with and can make debugging your programs easier. For example, consider these variables: age = 20 price = 99.50 name = "Rahul" is_student = True Although all four variables store data, their data types are different. Python allows us to check these types using type() . Let's understand how it works with simple examples. 1. What Is the type() Function in Python? The type() function is a built-in Python function that returns information about the type of an object. In beginner-level programming, you can use it to check whether a value is an integer, a floating-point number, a string,...

Python Keywords

When you start learning Python, you will come across words such as if, else, for, while, True, and False.

These words have special meanings in Python. They are called keywords.

Keywords are an important part of Python programming because they help us write instructions, make decisions, repeat tasks, define functions, and control how a program works.

In this article, we will learn what Python keywords are, see examples of commonly used keywords, understand why they are reserved, and discover how keywords differ from variable names.

1. What Are Keywords in Python?

Keywords are reserved words in Python that have predefined meanings and special purposes in the language.

We use them to write the structure and logic of a program.

For example:

age = 18

if age >= 18:
    print("You are eligible to vote.")

In this program, if is a keyword. It checks whether a condition is true before executing the indented statement.

Here:

  • if is a keyword.

  • age is a variable.

  • 18 is an integer literal.

  • print is a built-in function.

Python keywords cannot be used as ordinary variable names because they already have special meanings in the language.

2. Why Are Keywords Important?

Keywords help Python understand what you want your program to do.

For example, consider these keywords:

  • if helps make decisions.

  • else provides an alternative when an if condition is false.

  • for is used to create a loop.

  • while repeats statements while a condition remains true.

  • def is used to define a function.

  • return sends a result back from a function.

  • import allows you to bring a module into your program.

  • class is used to define a class.

Without these special words, it would be difficult to express program logic in a clear and consistent way.

3. Common Python Keywords

Let's look at some commonly used Python keywords and their purposes.

KeywordPurpose
ifChecks a condition
elseProvides an alternative branch
elifChecks another condition
forCreates a loop
whileRepeats statements while a condition is true
breakTerminates the nearest enclosing loop
continueSkips to the next iteration of a loop
passActs as a placeholder statement
defDefines a function
returnReturns a value from a function
classDefines a class
importImports a module
fromImports specified names from a module
asCreates an alias in supported statements
tryBegins a block for exception handling
exceptHandles specified exceptions
finallyDefines code that runs during the cleanup phase of exception handling
raiseRaises an exception
inTests membership or appears in certain loop statements
isTests object identity
andPerforms logical AND
orPerforms logical OR
notPerforms logical negation
TrueRepresents the Boolean value true
FalseRepresents the Boolean value false
NoneRepresents the absence of a value
globalDeclares that a name refers to a global variable
nonlocalRefers to a variable in an enclosing, non-global scope
withManages a context, such as working with a file
assertChecks a condition and raises an error if it fails
delDeletes a name or removes an item or attribute
lambdaCreates a small anonymous function
yieldProduces a value from a generator function
asyncDefines asynchronous code in supported contexts
awaitWaits for an awaitable result in asynchronous code

Note: Python's keyword list can vary between versions. Some words, such as match and case, have special roles in structural pattern matching, while certain other words are treated as soft keywords rather than reserved keywords in every context.

You do not need to memorize every keyword on your first day. Learn them gradually as you study each topic.

4. Understanding Keywords with Examples

The easiest way to understand keywords is to see how they work in programs.

Example 1: The if Keyword

The if keyword allows a program to make a decision.

age = 20

if age >= 18:
    print("Adult")

Output:

Adult

The condition age >= 18 is true, so Python executes the indented statement.

Example 2: The if, elif, and else Keywords

These keywords allow a program to choose between different possibilities.

marks = 75

if marks >= 90:
    print("Grade A")
elif marks >= 60:
    print("Grade B")
else:
    print("Grade C")

Output:

Grade B

Python checks the conditions in order. The first condition is false, but the second is true, so it displays Grade B.

Example 3: The for Keyword

The for keyword is used to repeat a block of code.

for i in range(1, 6):
    print(i)

Output:

1
2
3
4
5

Here, for creates the loop, while in is used to iterate through the values produced by range(1, 6).

Example 4: The while Keyword

The while keyword repeats a block of code while its condition is true.

count = 1

while count <= 3:
    print(count)
    count += 1

Output:

1
2
3

The loop stops when count <= 3 becomes false.

Example 5: The def Keyword

The def keyword is used to define a function.

def greet():
    print("Welcome to Python!")

greet()

Output:

Welcome to Python!

Here, def defines the function named greet.

Example 6: The return Keyword

The return keyword sends a result back from a function.

def add(a, b):
    return a + b

result = add(10, 20)

print(result)

Output:

30

The function returns the sum of the two numbers.

Example 7: The import Keyword

The import keyword allows us to use functionality from a module.

import math

print(math.sqrt(25))

Output:

5.0

Here, import makes the math module available to the program.

5. Can We Use Keywords as Variable Names?

No. Python keywords cannot be used as ordinary variable names.

For example, this code is invalid:

if = 10

Python will report a syntax error because if is a reserved keyword.

Another invalid example is:

for = 20

The word for already has a special purpose in Python.

How Can We Fix This?

Choose a different variable name.

Instead of:

if = 10

Write:

number = 10

Similarly, instead of:

for = 20

Write:

count = 20

Remember: A variable name should describe the value it represents and must not be a reserved keyword.

6. Keywords vs Identifiers

Keywords and identifiers are two different concepts.

An identifier is a name given to a variable, function, class, or another named object in Python.

Consider this program:

student_name = "Rahul"

if student_name:
    print(student_name)

Let's identify the different parts:

  • if is a keyword.

  • student_name is an identifier.

  • "Rahul" is a string literal.

  • print() is a built-in function.

Here is a quick comparison:

KeywordsIdentifiers
Reserved words with special meaningsNames created for program elements
Have predefined purposesAre chosen by the programmer, subject to naming rules
Cannot be used as ordinary variable namesCan be used as variable or function names when valid
Examples: if, for, whileExamples: age, student_name, calculate_sum

For example:

age = 20

Here, age is an identifier, while 20 is a literal.

7. Are Python Keywords Case-Sensitive?

Yes. Python is case-sensitive.

For example:

if age >= 18:
    print("Eligible")

The keyword must be written as if, using lowercase letters.

Writing IF instead of if does not create the same keyword.

Similarly, Python's Boolean literals are written as True and False, with the first letter capitalized.

Example:

is_student = True

print(is_student)

Output:

True

Writing true instead of True will not refer to Python's Boolean literal.

8. How to Check Python Keywords

Python provides a module named keyword that can help you examine the keywords recognized by your Python interpreter.

Example:

import keyword

print(keyword.kwlist)

This displays the list of hard keywords for the Python version you are using.

You can also check whether a word is a keyword:

import keyword

word = "while"

print(keyword.iskeyword(word))

Output:

True

Try changing the value of word:

word = "student"

The result will be:

False

The word student is not a Python keyword.

Important: The exact list of keywords depends on the Python version installed on your computer.

9. Common Mistakes Beginners Should Avoid

Mistake 1: Using a keyword as a variable name

Incorrect:

while = 10

Correct:

count = 10

Mistake 2: Using the wrong capitalization

Incorrect:

IF age >= 18:
    print("Eligible")

Correct:

if age >= 18:
    print("Eligible")

Mistake 3: Trying to memorize every keyword immediately

You do not need to memorize the entire keyword list before writing your first Python program.

Start with the keywords you use frequently, such as if, else, for, while, and def. Learn the remaining ones as you progress through the course.

Mistake 4: Confusing keywords with built-in functions

Consider:

print("Hello")

Here, print is a built-in function, not a keyword.

Similarly, input(), len(), and type() are built-in functions.

This distinction is useful when learning Python fundamentals.

10. Practice Questions

Test your understanding with the following questions.

Question 1: What is a keyword in Python?

Question 2: Why can we not use if as an ordinary variable name?

Question 3: Identify the keyword in this program:

age = 21

if age >= 18:
    print("Eligible")

Question 4: Are Python keywords case-sensitive?

Question 5: What is the difference between a keyword and an identifier?

Question 6: Which keyword is used to define a function?

Question 7: Which keyword is used to import a module?

Question 8: What is the purpose of the break keyword?

Question 9: Is print a keyword or a built-in function?

Question 10: Write a Python program using if and else to check whether a number is positive or not.

Practice Program: Check a Number

Try this example after answering the questions:

number = int(input("Enter a number: "))

if number > 0:
    print("The number is positive.")
else:
    print("The number is zero or negative.")

Example output:

Enter a number: 5
The number is positive.

This simple program demonstrates how keywords help control the flow of a Python program.

Final Thoughts

Python keywords are the reserved words that give structure and meaning to your programs. They help you make decisions, repeat tasks, define functions, import modules, and perform many other programming operations.

As a beginner, focus on understanding how keywords work rather than memorizing their entire list. With regular practice, you will become familiar with them naturally.

Keep experimenting with small programs, read the error messages Python provides, and try changing the examples to see what happens.

Comments

Popular posts from this blog

Understanding Comments in Java: A Beginner’s Guide

When learning Java programming, one of the first concepts you’ll come across is comments . Comments may not affect how a program runs, but they play a crucial role in making code more understandable, readable, and maintainable. Let’s dive deeper into what comments are, why they’re important, and the different types of comments in Java. What are Comments in Java? A comment in Java is a piece of text written within a program that is ignored by the compiler . In other words, comments are notes for humans, not instructions for machines. They help developers explain the purpose of code, describe logic, or temporarily disable certain lines of code without deleting them. Why are Comments Important? 📌 Readability – Comments make code easier to understand for you and others. 📌 Maintenance – When you revisit your code after months, comments remind you what you were doing. 📌 Collaboration – In team projects, comments explain code to fellow developers. 📌 Debugging – You c...

Java Program to Check Voting Eligibility

In this program, we’ll take the user’s age as input and check whether the person is eligible to vote or not. In India, the minimum age required to vote is 18 years . 💻 Program Code // Java Program to Check Voting Eligibility import java.util.Scanner; public class VotingEligibility { public static void main(String[] args) { // Create Scanner object to take input from user Scanner sc = new Scanner(System.in); // Ask user to enter age System.out.print("Enter your age: "); int age = sc.nextInt(); // Check eligibility if (age >= 18) { System.out.println("You are eligible to vote."); } else { System.out.println("You are not eligible to vote yet."); System.out.println("You can vote after " + (18 - age) + " year(s)."); } sc.close(); // Close the scanner } } 🧠 Explanation import java.util.Scanner; → Imp...

Java Program to Calculate Total Marks and Average of Five Subjects

💡 Program Explanation In this program: The user will input marks of five subjects . The program will calculate the total marks and average . It will then display both results clearly. 🧑‍💻 Java Code: // Java Program to Calculate Total Marks and Average of Five Subjects import java.util.Scanner; // Importing Scanner class for user input public class TotalAndAverage { public static void main(String[] args) { // Creating Scanner object to take input from user Scanner sc = new Scanner(System.in); // Declaring variables for five subjects double subject1, subject2, subject3, subject4, subject5; // Taking marks input for each subject System.out.print("Enter marks of Subject 1: "); subject1 = sc.nextDouble(); System.out.print("Enter marks of Subject 2: "); subject2 = sc.nextDouble(); System.out.print("Enter marks of Subject 3: "); subject3 = sc.nextDo...