Browse Courses

Types

This document introduces Python data types, including integers, floats strings, booleans, and typecasting. It explains how Python represents and converts data types, with practical examples and key concepts for beginners.

This document explains Python's core data types—integers, floats, strings, and booleans—along with typecasting and practical usage. Readers will learn how Python represents, converts, and manipulates different types of data for programming and analysis.


Introduction

Python uses data types to represent different kinds of values. Understanding these types is essential for effective programming and data analysis.


Common Data Types in Python

Python supports several fundamental data types:

ExpressionData Type
11int
21.213float
“words”str
  • int: Represents integers, which can be positive or negative. The range is finite but very large.
  • float: Represents real numbers, including values between integers. Floats allow precise selection of numbers between any two values, though there is a practical limit.
  • str: Represents sequences of characters, such as words or sentences.

Type Checking and Typecasting

Python provides tools to check and convert data types:

Checking Types

Use the type() command to determine the type of a value.

1# Example usage
2print(type(11))      # int
3print(type(21.213))  # float
4print(type("words")) # str

Typecasting

Typecasting changes the type of a value:

  • Convert int to float: float(2) yields 2.0.
  • Convert float to int: int(1.1) yields 1 (information may be lost).
  • Convert string to int: Only works if the string contains an integer value.
  • Convert int or float to string: str(2) or str(2.0).

Boolean Type in Python

Booleans represent logical values:

  • True (uppercase T)
  • False (uppercase F)

Use type(True) or type(False) to check the type, which returns bool.

Boolean Typecasting

  • Casting True to int or float yields 1.
  • Casting False to int or float yields 0.
  • Casting 1 to bool yields True.
  • Casting 0 to bool yields False.

Practical Considerations

Typecasting can result in loss of information, especially when converting floats to integers. Attempting to convert a string that does not contain an integer value to int will result in an error.

For more examples, refer to Python documentation or lab exercises.


Python Language Fundamentals

Understanding Python’s fundamental concepts and building blocks helps in writing clear and effective code.

TermDefinitionExample
LiteralsFixed values assigned to variables or directly used in expressions.5 (integer), 3.14 (float), "Hello" (string), True (boolean), [1, 2, 3] (list)
AxiomsFoundational, universally accepted principles or rules that form the basis of the language semantics.- “Indentation defines blocks of code.”
- “Everything in Python is an object.”
KeywordsReserved words that have special meanings and cannot be used as identifiers.if, else, for, while, def, class, import, return, with, etc.
OperatorsSymbols or words that perform operations on variables or values.+ (addition), - (subtraction), * (multiplication), and, or, not
Data TypesTypes of data Python can manipulate, like numbers, strings, lists, etc.int, float, str, list, tuple, dict, set, bool
IdentifiersNames used to identify variables, functions, classes, etc.x, y, function_name, MyClass
ExpressionsCombinations of values, variables, and operators that Python evaluates to produce a result.x + 5, len(my_list), True and False
StatementsInstructions that Python executes, like assignments or function calls.x = 5, print("Hello"), if x > 0:
FunctionsReusable blocks of code designed to perform specific tasks.python<br>def add(a, b):<br> return a + b
ClassesBlueprints for creating objects, encapsulating data and behavior.python<br>class Dog:<br> def __init__(self, name):<br> self.name = name
ObjectsInstances of classes that hold data and methods defined by the class.python<br>dog = Dog("Buddy")

Literals are the simplest building blocks of a programming language, representing constant values.

Type of LiteralDescriptionExamples
Numeric LiteralsNumbers (integers, floats, complex).42 (int), 3.14 (float), 1+2j (complex)
String LiteralsText enclosed in quotes."Hello", 'Python'
Boolean LiteralsLogical values.True, False
Special LiteralsDenote the absence of value.None
Collection LiteralsRepresent collections such as lists, tuples, sets, and dictionaries.[1, 2, 3], (1, 2), {1, 2, 3}, {"key": "value"}

Axioms are foundational principles or “rules of the game” for Python.

Python AxiomExplanation
Indentation defines code blocks.Unlike braces {} in many languages, Python uses indentation to denote code hierarchy.
Everything is an object.Python treats everything (e.g., numbers, strings, functions) as objects with properties.
Dynamic typing.Variable types are determined at runtime, not explicitly declared by the programmer.
Strong typing.Python enforces type correctness and won’t automatically convert incompatible types.
Readability counts (The Zen of Python).Python emphasizes code readability and simple syntax as a guiding design philosophy.

ConceptExample
Expressionx + y evaluates to the sum of x and y.
Statementx = 5 assigns the value 5 to the variable x.
Looping Constructfor i in range(3): print(i) outputs 0, 1, 2.
Conditionalif x > 0: print("Positive") else: print("Non-positive")

Data TypeDescriptionExample
intInteger values like 42 or -10.42, -10
floatFloating-point numbers with decimal points.3.14, 2.718
strSequence of characters enclosed in quotes."Hello", 'Python'
boolBoolean values representing True or False.True, False
listOrdered collection of items.[1, 2, 3], ["a", "b", "c"]
tupleImmutable ordered collection of items.(1, 2, 3), ("a", "b", "c")
dictUnordered collection of key-value pairs.{"key1": "value1", "key2": "value2"}
setUnordered collection of unique items.{1, 2, 3}, {"apple", "banana", "cherry"}

Conclusion

Python’s data types—int, float, str, and bool—form the foundation for programming and analysis. Understanding typecasting and type checking helps prevent errors and enables flexible data manipulation.


FAQ

Data types in Python define how different kinds of values are represented and manipulated, such as integers, floats, strings, and booleans.

Information after the decimal point is lost, and only the integer part is retained.

  1. Casting True to int yields 1
  2. Casting False to float yields 0.0
  3. Casting the string “hello” to int yields 0
  4. Casting 1 to bool yields True
(3) Casting a non-integer string to int results in an error, not 0.

Casting 0 to a Boolean yields False.

TypeDescription
A. int1. Sequence of characters
B. float2. Logical value, True or False
C. str3. Whole number, positive or negative
D. bool4. Real number, includes decimals
A-3, B-4, C-1, D-2.

Typecasting a float to an integer in Python may result in loss of information.

True. Only the integer part is retained, and the fractional part is discarded.

Ensure the string contains a valid integer value to avoid errors during conversion.

The type() command is used to check the type of a value in Python.

Boolean values can be cast to integers or floats, with True becoming 1 and False becoming 0.

The string “21.213” can be cast to a float, resulting in the value 21.213 as a float type.