Statement of Completion#01972841
Python Basics
medium
Data Types and Variables Guide
Resolution
Activities
Project.ipynb
Introduction to Python Data Types and Variables¶
In [ ]:
# Initialise an integer variable with a value of 10
x = 10
print(x)
In [ ]:
# Initialise a float variable with a value of 10
y = 10.0
print(y)
In [ ]:
# Initialise a string variable with a value of "10"
z = "10"
print(z)
In [ ]:
# Initialise a boolean variable with a value of True
a = True
print(a)
In [ ]:
# Initialise a complex variable with a value of real part 10 and imaginary part 20
b = 10 + 20j
print(b)
Numeric Data Types¶
In [ ]:
a = 10 # int
b = 3.14 # float
c = 2 + 3j # complex
print(type(a))
print(type(b))
print(type(c))
Boolean Data Type¶
In [ ]:
is_adult = True
is_child = False
print(type(is_adult))
print(type(is_child))
String Data Type¶
In [ ]:
# single and double quote
name = "Alice"
greeting = 'Hello, world!'
# multi line string is declared in tripple quote
multiline_string = '''This is
a multi-line
string.'''
print(type(name))
print(type(greeting))
In [ ]:
In [ ]:
authors.ipynb
Python Basic Data Type And Variable¶
Introduction to Python Data Types¶
Today, we're going to dive into one of the most important concepts in Python: Data Types and Variables. Understanding how data is stored and manipulated in Python is the foundation of writing efficient programs. So, let’s explore Python's built-in data types, variables and how they help us in coding.
What are Data Types?¶
In Python, data types define the kind of value a variable can hold. A variable is just a name that refers to a value stored in memory. The type of data a variable stores is crucial because it determines what operations you can perform on it.
Here are some rules for naming a variable:
- Character set: Variable names can contain uppercase and lowercase letters, digits, and the underscore character, but the first character must be a letter or underscore.
- Case sensitivity: Variable names are case-sensitive, so "age", "Age", and "AGE" are all different variables.
- Reserved keywords: Avoid using Python's reserved keywords, like "if", "for", "while", "def", and "class", as variable names. Using these keywords can cause syntax errors and unexpected behavior.
- Spaces: Variable names cannot contain spaces.
- Special characters: Variable names cannot contain special characters.
The Basic Python Data Types¶
Let’s start with some basic data types in Python:
1. Numeric Types:¶
Python has three types of numeric data types:
- int: Integer numbers (whole numbers), Example: x = 5
- float: Floating-point numbers (decimals), Example: y = 3.14
- complex: Complex numbers with real and imaginary parts, Example: z = 2 + 3j
Lets do practical:
a = 10 # int
b = 3.14 # float
c = 2 + 3j # complex
print(type(a)) # Output: <class 'int'>
print(type(b)) # Output: <class 'float'>
print(type(c)) # Output: <class 'complex'>
2. Boolean Values:¶
A boolean can only be one of two values: True or False. These are essential for logical operations and control flow (like if-else statements).
Example: is_raining = True
Example: is_sunny = False
is_adult = True
is_child = False
print(type(is_adult)) # Output: <class 'bool'>
print(type(is_child)) # Output: <class 'bool'>
Booleans are often the result of comparison or logical operations:
For Example,
x = 5
y = 10
print(x > y) # Outputs: False
3. Strings:¶
Strings are sequences of characters surrounded by quotes. Python allows you to use single quotes ('), double quotes ("), or triple quotes (''' or """).
Example: 'Hello', "World", '''Python is fun'''
You can even include special characters like newline (\n) or tabs (\t).
# single and double quote
name = "Alice"
greeting = 'Hello, world!'
# multi line string is declared in tripple quote
multiline_string = '''This is
a multi-line
string.'''
print(type(name)) # Output: <class 'str'>
print(type(greeting)) # Output: <class 'str'>
Lets test our learning¶
Activity 1. What is the output of the following code?¶
x = 10
y = 3.14
z = x + y
print(type(z))
- <class 'int'>
- <class 'float'>
- <class 'str'>
- <class 'complex'>
Sol: The correct solution is <class 'float'>
Activity 3. Which is the correct way of defining a string variable¶
- age = TRUE
- age = "Ten"
- age = 10
- string age = 10
Sol: The correct solution is age = "Ten"
Type Conversion or Type Casting¶
Type conversion refers to the process of converting a value from one data type to another. Python provides two types of type conversion:
Implicit Type Conversion¶
Python automatically converts one data type to another when it is safe to do so. This process is known as implicit type conversion or type coercion.
x = 10 # int
y = 3.14 # float
result = x + y # x is implicitly converted to float
print(result) # Outputs: 13.14
print(type(result)) # Outputs: <class 'float'>
Explicit Type Conversion¶
Explicit type conversion, also called type casting, is done manually by using functions like int(), float(), str(), etc. Python provides built-in functions for this purpose.
Example
- Convert integer to float
x = 5
y = float(x) # y becomes 5.0
- Convert float to integer:
z = int(3.14) # z becomes 3
- Convert to string
num = 42
text = str(num) # text becomes '42'
Activity 4. What will int('10.5') return?¶
- 10
- 10.5
- Error
- 0
Sol: Error. Since, 10.5 is a decimal number written in single quote, it is treated as string. And explicit conversion of float as string gives error. The int() function can only convert strings that represent whole numbers (like '42'), and it cannot handle decimal point.
Activity 5. Which is a valid variable name?¶
- 2variable
- _variable
- break
- class
Sol: _variable
is correct option. A variable name must start with either alphabet or underscore(_). Keywords can not be variable.
Checking Data Types¶
Python’s type()
function allows you to check the data type of a variable.
Activity 6. What will be the output of the given python code?¶
x = 10
y = "20"
print(x + int(y))
- Error
- 10
- 30
- 1020
Sol: 30
Activity 7. Which function is used to check the type of a variable?¶
- typeof()
- checktype()
- type()
- isType()
Sol: type()
Activity 8. Which of the following is NOT a valid string declaration?¶
- greeting = 'Hello'
- greeting = "Hello"
- greeting = '''Hello'''
- greeting = Hello
Sol: greeting = Hello
is the correct answer.
Activity 9. What is the result of (0.1 + 0.2 == 0.3)?¶
- True
- False
- None
- Error
Sol: False. In computers, floating point numbers are represented using binary fraction, which can not exactly represent same decimal number.
Activity 10. What will print(5+True)
result in?¶
- 6
- 5
- TypeError
- ValueError
Sol: 6. Here boolean True
is treated an int 1
.
Activity 11. What will be output of following python code?¶
print('2' * 3)
- 6
- '6'
- '222'
- TypeError
Sol: '222' is the correct answer.
Activity 12. What will the given python code evaluate to?¶
x = True
y = False
print(x + y)
- 1
- 0
- True
- 2
Sol: 1 is the correct output.
ISINSTANCE() FUNCTION¶
The isinstance() function in Python is used to check if an object is an instance of a specific class or a tuple of classes.
It returns True
if the object is an instance of the specified class or any of its subclasses; otherwise, it returns False
.
Syntax:
isinstance(object, classinfo)
Where:
object: The object you want to test.
classinfo: A class, type, or a tuple of classes and types to check against.
For Example:
x = 5
print(isinstance(x, int)) # Output: True
Let's do some activities to understand the concept better.
Activity 13. What will be the output of the given python code?¶
z = 10
print(isinstance(z, int))
- True
- False
- Error
- 10
type()
and isinstance()
Functions¶
The isinstance()
and type()
functions in Python both check the type of an object, but they have important differences in their behavior and usage.
Here are some key differences between the two functions:
Return Values¶
isinstance(): Returns a boolean value (True or False
type(): Returns the actual class/type of the object
score = 42
print(isinstance(score, int)) # Output: True
print(type(score)) # Output: <class 'int'>
Multiple Types Check¶
isinstance(): The isinstance() function can check if an object is an instance of multiple classes.
type(): The type() function can only check if an object is an instance of a single class.
Subclass Checking¶
isinstance(): The isinstance() function can check if an object is an instance of a class or any of its subclasses.
type(): The type() function can only check if an object is an instance of a specific class.
Note: The isinstance()
function is mostly used with data structures and classes, thus it will be more useful in the future.
Activity 14. What does the isinstance() function return?¶
- An integer (0 or 1)
- An object type
- A boolean (True or False)
- None
Sol: A boolean (True or False)
Activity 15. What will be print(isinstance(str(42), str))
return?¶
- True
- False
- Error
- None
Sol: True. The str(42)
returns a string '42' and it is an instance of string class.