Python Keywords, Type Conversion, Input/Output, and Comments – A Complete Beginner's Guide
Python Keywords, Type Conversion, Input/Output, and Comments – A Complete Beginner's Guide
Before writing real Python programs, there are four fundamental concepts every beginner must understand — keywords, type conversion, input/output functions, and comments. These form the core building blocks of every Python program you will ever write. In this guide, all four are explained clearly with syntax, examples, outputs, and real-life use cases.
Table of Contents
- Python Keywords – What They Are and Why They Matter
- Categories of Keywords
- Value Keywords – True, False, and None
- Keywords vs Identifiers
- Type Conversion in Python
- Implicit Type Conversion
- Explicit Type Conversion (Type Casting)
- All Conversion Examples – Numeric, String, Boolean, Sequence
- Input Function – input()
- Output Function – print()
- Comments in Python
- FAQ
1. Python Keywords – What They Are and Why They Matter
Keywords are reserved words in Python that already have a fixed, predefined meaning. Python uses these words to understand the structure and logic of your program. You cannot change their meaning, and you cannot use them as variable names, function names, or class names.
Think of keywords as the grammar rules of Python — just like you cannot use grammar words as names in a sentence, you cannot use Python keywords as identifiers.
class = 10 for = "hello" if = True
class_name = 10 for_loop = "hello" is_valid = True
How to check all keywords in Python
import keyword print(keyword.kwlist)
['False', 'None', 'True', 'and', 'as', 'assert', 'async', 'await', 'break', 'class', 'continue', 'def', 'del', 'elif', 'else', 'except', 'finally', 'for', 'from', 'global', 'if', 'import', 'in', 'is', 'lambda', 'nonlocal', 'not', 'or', 'pass', 'raise', 'return', 'try', 'while', 'with', 'yield']
keyword.kwlist to see the exact list for your installed version.Full keyword list at a glance
Blue = conditional | Green = looping | Amber = boolean | Purple = function/class | Coral = exception
2. Categories of Keywords
Conditional keywords
Used for decision-making — telling Python which block to run based on a condition.
age = 20 if age >= 18: print("Eligible to vote") elif age >= 16: print("Almost there") else: print("Not eligible")
Eligible to vote
Looping keywords
Used to repeat blocks of code — controlling how and when a loop runs or stops.
for i in range(1, 6): if i == 3: continue # skip 3 if i == 5: break # stop at 5 print(i)
1 2 4
Function and class keywords
def add(a, b): return a + b print(add(3, 7))
10
Exception handling keywords
try: result = 10 / 0 except ZeroDivisionError: print("Cannot divide by zero") finally: print("This always runs")
Cannot divide by zero This always runs
3. Value Keywords – True, False, and None
Three keywords in Python represent specific built-in values. They are called value keywords because they already hold a meaning by themselves.
True and False
True and False are Boolean values — the only two possible results of any comparison or logical operation. They must always be written with a capital first letter.
is_logged_in = True is_paid = False print(10 > 5) # True print(3 == 7) # False print(type(True)) # <class 'bool'>
True False <class 'bool'>
x = true y = false
x = True y = False
None keyword
None represents the absence of a value — it means "nothing is stored here". It is not the same as zero or an empty string. It is its own type in Python called NoneType.
result = None print(result) # None print(type(result)) # <class 'NoneType'> # Check if a variable has no value if result is None: print("No value assigned yet") result = 42 print(result) # 42
None <class 'NoneType'> No value assigned yet 42
None vs 0 vs "" — 0 is the integer zero (has a value). "" is an empty string (has a type but no content). None means no value at all — the variable exists but holds nothing.4. Keywords vs Identifiers
| Feature | Keyword | Identifier |
|---|---|---|
| Definition | Reserved word with fixed meaning | User-defined name for variables/functions |
| Can be changed? | No — meaning is fixed | Yes — you define the name |
| Case sensitive? | Yes — if not If | Yes — age and Age are different |
| Example | if, for, True | age, student_name, total |
| Can start with digit? | No | No |
5. Type Conversion in Python
Type conversion is the process of changing a value from one data type to another. Python is a dynamically-typed language, which means variables can hold different types of data. But when you mix types in operations, Python needs guidance on how to handle them.
User input is always a string. If you want to do math with it, you must convert it first — otherwise Python will throw a TypeError.
a = "10" b = 5 print(a + b) # This causes a TypeError
TypeError: can only concatenate str (not "int") to str
a = "10" b = 5 print(int(a) + b) # Correct – convert first
15
Python supports two types of conversion:
Implicit conversion
Python converts the type automatically — no manual code needed. Happens when mixing int and float in the same expression.
Explicit conversion (type casting)
You manually convert using built-in functions like int(), float(), str(), bool(), etc.
6. Implicit Type Conversion
Python automatically converts a lower data type to a higher one to avoid data loss. This happens silently — you do not need to write any conversion code.
a = 10 # int b = 2.5 # float c = a + b # Python converts int to float automatically print(c) print(type(c))
12.5 <class 'float'>
7. Explicit Type Conversion (Type Casting)
In explicit conversion, you manually convert the data type using Python's built-in functions.
| Function | Converts to | Example |
|---|---|---|
int() | Integer | int("10") → 10 |
float() | Float | float(5) → 5.0 |
str() | String | str(100) → "100" |
bool() | Boolean | bool(0) → False |
list() | List | list((1,2,3)) → [1,2,3] |
tuple() | Tuple | tuple([1,2,3]) → (1,2,3) |
set() | Set (removes duplicates) | set([1,2,2,3]) → {1,2,3} |
8. All Conversion Examples
Numeric conversions
# int to float print(float(10)) # 10.0 # float to int (decimal is dropped, not rounded) print(int(10.9)) # 10 print(int(10.1)) # 10 # int to complex print(complex(5)) # (5+0j)
10.0 10 10 (5+0j)
int(10.9) gives 10, not 11. Python does not round — it simply removes the decimal part. Use round() if you need rounding.String conversions
# number to string print(str(100)) # "100" print(str(10.5)) # "10.5" # string to number (only numeric strings) print(int("20")) # 20 print(float("10.5")) # 10.5
"100" "10.5" 20 10.5
int("abc") will raise a ValueError. You can only convert strings that contain valid numbers. Always validate user input before converting.Boolean conversions
# Numbers to bool print(bool(1)) # True print(bool(0)) # False print(bool(0.0)) # False print(bool(2.5)) # True # Strings to bool print(bool("")) # False (empty) print(bool("Python")) # True (non-empty) # Lists to bool print(bool([])) # False (empty list) print(bool([1, 2])) # True (non-empty list)
True False False True False True False True
Sequence conversions
my_list = [1, 2, 2, 3] print(tuple(my_list)) # list → tuple print(set(my_list)) # list → set (removes duplicates) my_range = range(5) print(list(my_range)) # range → list print(tuple(my_range)) # range → tuple
(1, 2, 2, 3)
{1, 2, 3}
[0, 1, 2, 3, 4]
(0, 1, 2, 3, 4)9. Input Function – input()
The input() function lets your program accept data from the user while it is running. Whatever the user types is stored in a variable. The most important thing to remember is that input() always returns a string — even if the user types a number.
Basic syntax
variable = input("Message to show user: ")
name = input("Enter your name: ") print(f"Hello, {name}!")
Enter your name: Rohan Hello, Rohan!
age = input("Enter your age: ") print(type(age)) # Always str, even if user types 21
Enter your age: 21 <class 'str'>
Input with type conversion
To perform math on user input, convert it immediately using int() or float().
age = int(input("Enter your age: ")) next_year = age + 1 print(f"Next year you will be {next_year}")
Enter your age: 20 Next year you will be 21
num1 = float(input("Enter first number: ")) num2 = float(input("Enter second number: ")) print(f"Sum: {num1 + num2}") print(f"Difference: {num1 - num2}") print(f"Product: {num1 * num2}") print(f"Quotient: {num1 / num2:.2f}")
Enter first number: 12 Enter second number: 4 Sum: 16.0 Difference: 8.0 Product: 48.0 Quotient: 3.00
10. Output Function – print()
The print() function displays data to the screen. It is the most commonly used function in Python and supports several useful parameters to control the format of output.
Basic print examples
print("Welcome to Code with Py") print(42) print(3.14) print(True)
Welcome to Code with Py 42 3.14 True
Printing multiple values
name = "Rohan" age = 21 print(name, age) print("Name:", name, "Age:", age)
Rohan 21 Name: Rohan Age: 21
sep parameter – custom separator
The sep parameter controls what goes between values when printing multiple items. Default is a space.
print("Python", "Java", "C++", sep=" | ") print(2024, 1, 15, sep="-") print("a", "b", "c", sep="")
Python | Java | C++ 2024-1-15 abc
end parameter – control line ending
By default, print() adds a newline at the end. Use end to change this.
print("Hello", end=" ") print("World") print("Loading", end="...") print("Done")
Hello World Loading...Done
f-strings – the best way to format output
name = "Priya" score = 95.5 print(f"Student: {name} | Score: {score:.1f}%")
Student: Priya | Score: 95.5%
11. Comments in Python
Comments are lines in your code that Python completely ignores when running the program. They are written for humans — to explain what the code does, why a decision was made, or to leave notes for future edits. Good comments make code much easier to read, debug, and maintain.
Single-line comments
Start with the # symbol. Everything after # on that line is ignored by Python.
# This is a standalone comment age = 21 # Storing the user's age # Calculate area of a rectangle length = 10 width = 5 area = length * width print(f"Area: {area}")
Area: 50
Multi-line comments
Python does not have a dedicated multi-line comment syntax. The common approach is to use triple quotes """...""" — usually placed at the start of a function or file to describe its purpose. These are technically strings but act as documentation.
""" This program calculates the area of a rectangle. Author: Code with Py Date: 2026 """ def calculate_area(length, width): """Returns the area of a rectangle.""" return length * width print(calculate_area(10, 5))
50
# comments for explaining individual lines. Use triple-quote """...""" for describing functions, classes, and modules — this is called a docstring.- Keywords are reserved words — they cannot be used as variable or function names
- Python 3 has 35 keywords — use
keyword.kwlistto see them all TrueandFalsemust be capitalized —trueis not a keywordNonemeans no value — it is different from 0 or an empty string- Implicit conversion happens automatically (int + float = float)
- Explicit conversion uses
int(),float(),str(),bool()etc. input()always returns a string — convert it before doing mathprint()supportssepandendfor output formatting- Use
#for single-line comments and"""..."""for multi-line docs
Frequently Asked Questions (FAQ)
Q1. Can I use a keyword as part of a variable name in Python?
You cannot use a keyword exactly as a variable name (e.g. for = 5 causes a SyntaxError). But you can use a keyword as part of a longer name, like for_loop or class_name.
Q2. What is the difference between None, 0, and an empty string?
0 is the integer value zero — it has a numeric value. "" is an empty string — it has a type but no content. None means no value has been assigned at all. All three are falsy in boolean context, but they are different types.
Q3. Why does input() always return a string?
Python cannot know in advance whether the user will type a number, a name, or a sentence. So it stores everything as a string for safety. You must manually convert using int() or float() when you need to do calculations.
Q4. What happens when you do int() on a float like int(10.9)?
Python does not round — it truncates (removes the decimal part). So int(10.9) gives 10, not 11. If you need proper rounding, use the round() function instead.
Q5. What is the difference between sep and end in print()?
sep controls what goes between multiple values being printed (default is a space). end controls what is printed at the very end of the line (default is a newline \n). Both can be set to any string you want.
Q6. Are multi-line triple-quote strings real comments in Python?
Technically, they are string literals — Python does create them, but immediately discards them if they are not assigned to a variable. In practice, they behave like comments and are widely used as docstrings to document functions and modules.
Found this post helpful? Share it with a friend learning Python. Drop your questions in the comments — happy to help!
"Every Python expert once struggled with basics like keywords and input. Master these fundamentals today — advanced Python will feel simple tomorrow."
Nice explanation
ReplyDeleteNice explanation
ReplyDelete