Python Data Types
1. Built-in Data Types
- Data types are essential as they define the kind of operations variables can perform.
- Categories of Python Data Types:
- Text Type:
str
- Numeric Types:
int
,float
,complex
- Sequence Types:
list
,tuple
,range
- Mapping Type:
dict
- Set Types:
set
,frozenset
- Boolean Type:
bool
- Binary Types:
bytes
,bytearray
,memoryview
- None Type:
NoneType
- Text Type:
2. Getting the Data Type
- Use the
type()
function to determine the type of any object.x = 5 print(type(x)) # Output: <class 'int'>
3. Setting the Data Type
-
Data type is assigned based on the value assigned to a variable.
Examples:
x = "Hello World"
→str
x = 20
→int
x = 20.5
→float
x = 1j
→complex
x = ["apple", "banana", "cherry"]
→list
x = ("apple", "banana", "cherry")
→tuple
x = range(6)
→range
x = {"name": "John", "age": 36}
→dict
x = {"apple", "banana", "cherry"}
→set
x = frozenset({"apple", "banana", "cherry"})
→frozenset
x = True
→bool
x = b"Hello"
→bytes
x = bytearray(5)
→bytearray
x = memoryview(bytes(5))
→memoryview
x = None
→NoneType
4. Setting Specific Data Types
-
Use constructor functions to specify the data type.
Examples:
x = str("Hello World")
→str
x = int(20)
→int
x = float(20.5)
→float
x = complex(1j)
→complex
x = list(("apple", "banana", "cherry"))
→list
x = tuple(("apple", "banana", "cherry"))
→tuple
x = range(6)
→range
x = dict(name="John", age=36)
→dict
x = set(("apple", "banana", "cherry"))
→set
x = frozenset(("apple", "banana", "cherry"))
→frozenset
x = bool(5)
→bool
x = bytes(5)
→bytes
x = bytearray(5)
→bytearray
x = memoryview(bytes(5))
→memoryview
5. Quiz/Exercise
- Question: If
x = 5
, what is the correct syntax for printing the data type ofx
?- Correct Answer:
print(type(x))
- Correct Answer:
💥 YouTube https://www.youtube.com/channel/UCJojbxGV0sfU1QPWhRxx4-A
💥 Blog https://localedxcelcambridgeictcomputerclass.blogspot.com/
Python Numbers
-
Three Numeric Types in Python:
int
: Integer (whole numbers, positive or negative, without decimals, unlimited length).float
: Floating-point number (numbers with decimals or in scientific notation).complex
: Complex number (with a real and imaginary part, written asa + bj
).
-
Creating Numeric Variables:
x = 1 # int y = 2.8 # float z = 1j # complex
-
Verifying the Type of an Object: Use the
type()
function.print(type(x)) print(type(y)) print(type(z))
Details of Numeric Types
1. Int (Integer):
- Whole numbers without decimals.
- Positive, negative, or zero.
- Unlimited length.
x = 1
y = 35656222554887711
z = -3255522
print(type(x))
print(type(y))
print(type(z))
2. Float (Floating-Point Numbers):
- Numbers containing one or more decimals.
- Can also represent scientific numbers using
e
for powers of 10.
x = 1.10
y = 1.0
z = -35.59
x = 35e3
y = 12E4
z = -87.7e100
print(type(x))
print(type(y))
print(type(z))
3. Complex Numbers:
- Written with a "j" to represent the imaginary part.
x = 3+5j
y = 5j
z = -5j
print(type(x))
print(type(y))
print(type(z))
Type Conversion
- Convert between numeric types using
int()
,float()
, andcomplex()
.x = 1 # int y = 2.8 # float z = 1j # complex a = float(x) # Convert int to float b = int(y) # Convert float to int c = complex(x) # Convert int to complex print(a) print(b) print(c) print(type(a)) print(type(b)) print(type(c))
- Note: Complex numbers cannot be converted to other numeric types.
Random Numbers
- Python does not have a built-in
random()
function but includes arandom
module. - Use the
random.randrange(start, stop)
function to generate a random number.import random print(random.randrange(1, 10))
Quiz/Exercise:
Question: Which is NOT a legal numeric data type in Python?
int
long
(Correct Answer:long
is not valid; it was part of Python 2.)float
💥 WordPress https://computerclassinsrilanka.wordpress.com
💥 Facebook https://web.facebook.com/itclasssrilanka
Here are the key points extracted from the content:
Python Casting
1. Purpose of Casting
- Casting is used to specify the data type of a variable explicitly.
- Python, being an object-oriented language, uses classes to define data types.
2. Constructor Functions for Casting
-
int()
Constructs an integer:- From an integer literal.
- From a float literal (removing decimals).
- From a string literal (if the string represents a whole number).
- Examples:
x = int(1) # x will be 1 y = int(2.8) # y will be 2 (decimals are removed) z = int("3") # z will be 3
-
float()
Constructs a floating-point number:- From an integer literal.
- From a float literal.
- From a string literal (if the string represents a number).
- Examples:
x = float(1) # x will be 1.0 y = float(2.8) # y will be 2.8 z = float("3") # z will be 3.0 w = float("4.2") # w will be 4.2
-
str()
Constructs a string:- From strings.
- From integers.
- From floats.
- Examples:
x = str("s1") # x will be 's1' y = str(2) # y will be '2' z = str(3.0) # z will be '3.0'
3. Quiz/Exercise
- Question: What will be the result of the following code?
print(int(35.88))
- Correct Answer:
35
(The decimals are truncated when casting a float to an integer.)
- Correct Answer:
💥 Wix https://itclasssl.wixsite.com/icttraining
💥 Web https://itclasssl.github.io/eTeacher/
Here are all the key points from the content about Python Booleans:
Python Booleans
1. Boolean Representation
- Booleans represent one of two values:
True
orFalse
.
2. Boolean Values
- Any expression in Python can be evaluated to
True
orFalse
. - Comparison Examples:
print(10 > 9) # True print(10 == 9) # False print(10 < 9) # False
3. Booleans in Conditional Statements
- When used in an
if
statement, Python evaluates the condition and returnsTrue
orFalse
.- Example:
a = 200 b = 33 if b > a: print("b is greater than a") else: print("b is not greater than a")
- Example:
4. The bool()
Function
- Purpose: Evaluates any value and returns
True
orFalse
. - Examples:
print(bool("Hello")) # True print(bool(15)) # True x = "Hello" y = 15 print(bool(x)) # True print(bool(y)) # True
5. Most Values are True
- Non-empty strings, numbers (non-zero), and collections (non-empty lists, tuples, sets, dictionaries) evaluate to
True
.- Examples:
print(bool("abc")) # True print(bool(123)) # True print(bool(["apple", "cherry", "banana"])) # True
- Examples:
6. Some Values are False
- Values that evaluate to
False
include:- Empty values:
()
,[]
,{}
,""
. - The number
0
. None
.- The value
False
. - Examples:
print(bool(False)) # False print(bool(None)) # False print(bool(0)) # False print(bool("")) # False print(bool(())) # False print(bool([])) # False print(bool({})) # False
- Empty values:
7. Special Case: Custom Objects
- Objects with a
__len__
method that returns0
orFalse
evaluate toFalse
.- Example:
class myclass(): def __len__(self): return 0 myobj = myclass() print(bool(myobj)) # False
- Example:
8. Functions Returning a Boolean
- Functions can return Boolean values and can be used in conditions.
- Example:
def myFunction(): return True print(myFunction()) # True if myFunction(): print("YES!") else: print("NO!")
- Example:
9. Built-in Boolean Functions
- Python includes functions like
isinstance()
to check data types, which returnTrue
orFalse
.- Example:
x = 200 print(isinstance(x, int)) # True
- Example:
10. Quiz/Exercise
- Question: What will be the result of the following syntax?
print(5 > 3)
- Correct Answer:
True
- Correct Answer:
No comments:
Post a Comment