Python Data Types - Jupyter Notebook_017ae85a1acb61f561c41b1ab55449c7
Python Data Types - Jupyter Notebook_017ae85a1acb61f561c41b1ab55449c7
Python Syntax
Python syntax refers to the set of rules that define how Python code must be written and
structured to be correctly interpreted and executed by the Python interpreter. Just like grammar
rules in a language ensure that sentences are understandable.
Keywords: Python has reserved words that have specific meanings and cannot be used
as variable names. These keywords include if, else, for, while, def, class, etc.
Operators: Python uses various operators for arithmetic, logical, comparison, and
assignment operations.
Data Types: Python supports various data types, including numbers (integers, floats),
strings, lists, tuples, dictionaries, and sets.
Comments: Comments are used to explain your code and are ignored by the interpreter.
They start with a # character.
Key Points:
Printing
One of the fundamental tasks in programming is to display output. In Python, we use the
print() function to print messages to the console. The message to be printed is enclosed
within quotation marks and placed inside the parentheses of the print() function.
Hello, World!
[Tip:] print() is a function. You passed the string 'Hello, World!' as an argument
to instruct Python on what to print.
Multiple Arguments
The print() function allows you to pass multiple arguments, separated by commas. These
arguments can be of any data type, and they will be printed sequentially, separated by a space
by default.
Example:
Comments
Comments are essential for making your code more readable and understandable, especially
for yourself and others who might work on it later. They provide explanations or notes about the
code's functionality without affecting the program's execution.
How to Write Comments:
To indicate a comment in Python, start the line with a pound sign (#). Anything after the pound
sign on the same line will be treated as a comment and ignored by the Python interpreter.
A Python interpreter is a program that executes Python code. It reads the source code line
by line, translates it into machine-readable instructions, and then carries out those instructions.
Example:
Hello, world!
In this example, the line # This is a comment is a comment and will not be executed by
Python. The line print("Hello, world!") is the actual code that will be executed.
Clarity: Comments help explain the purpose of different sections of your code, making it
easier to understand.
Maintainability: When you revisit your code after a long time, comments can provide
valuable context and help you remember the logic behind your decisions.
Collaboration: Comments make it easier for others to understand and contribute to your
code.
Multi-line comments in Python are enclosed between triple quotes (""" or '''). This allows you
to write comments that span multiple lines.
In [5]: """
This is a multi-line comment.
It can span multiple lines.
"""
print("Hello, world!")
Hello, world!
Key points:
Multi-line comments are useful for providing more detailed explanations or documentation.
They can be used to temporarily disable code sections.
Consistent use of comments improves code readability and maintainability.
Fundamental Data Types in Python
1. Numbers:
In [6]: # Integer
11
Out[6]: 11
In [7]: # Float
2.14
Out[7]: 2.14
In [8]: # String
"Hello, Python 101!"
In Python, you can use the type() function to determine the data type of an object. You'll
notice that Python refers to integers as int , floats as float , and character strings as str .
In Python, everything is an object. This means that every value, from numbers and strings to
custom data structures, is represented as an object. Objects have attributes (data) and
methods (functions) that define their behavior.
In [9]: # Type of 12
type(12)
Out[9]: int
In [10]: # Type of 2.14
type(2.14)
Out[10]: float
Out[11]: str
Integers
Integers are whole numbers, both positive and negative. They can be used to represent
quantities, counts, or positions.
Out[12]: int
Out[13]: int
Out[14]: int
As you can see, the type() function confirms that all these values are of type int ,
indicating they are integers.
Floats
Floating-point numbers (or floats) in Python are used to represent real numbers, which
include numbers with decimal points. They are a superset of integers, meaning they can
represent all integer values as well as numbers with fractional parts
Let's verify the data types of some floating-point numbers using the type() function:
Out[15]: float
Out[16]: float
Out[17]: float
Strings
Strings are sequences of characters enclosed in quotation marks. They can be used to
represent text, words, or any combination of characters.
Creating Strings:
Hello, world!
This is a string
[Tip:] Note that strings can be represented with single quotes ( 'Hello' ) or double quotes
( "Hello" ), but you can't mix both (e.g., "Hello' ).
Booleans
Booleans are a fundamental data type in Python that represent true or false values. They are
essential for making decisions and controlling the flow of your programs.
Out[20]: True
Notice that the value True has an uppercase "T". The same is true for False (i.e. you must
use the uppercase "F").
Out[21]: False
When you ask Python to display the type of a boolean object it will show bool which stands
for boolean:
Out[22]: bool
In [ ]: # Type of False
type(False)
Type Conversion in Python
Type conversion in Python refers to the process of changing the data type of an object from
one to another. This is often necessary when performing operations that require specific data
types or when working with data from different sources.
Converting to a string
Out[23]: '10'
Converting to an integer:
Use the int() function to convert a number or a string representing a number to an integer.
Out[24]: 10
Note: If the string cannot be converted to an integer (e.g., "hello"), it will raise a ValueError .
In [25]: int("hello")
---------------------------------------------------------------------------
ValueError Traceback (most recent call last)
Cell In[25], line 1
----> 1 int("hello")
Converting to a float:
Out[26]: 3.14
Out[27]: 2.0
Python also performs implicit type conversion in certain situations. For example:
When adding an integer and a float, the integer is automatically converted to a float before
the operation.
When comparing a string and an integer, the integer is automatically converted to a string
before the comparison.
Not all type conversions are possible. For example, you cannot convert a string like "hello"
to an integer.
Implicit type conversion can be convenient, but it can also lead to unexpected results if
you're not aware of the rules.
Be mindful of potential data loss or precision issues when converting between different
data types.
Python Variables
Variables in Python are used to store data. They act as containers that hold values, which can
be of different data types (e.g., numbers, strings, booleans).
Creating variables
To create a variable, you simply assign a value to it using the = operator. The variable name
should follow certain rules:
The first character of a variable name must be either a letter (a-z, A-Z) or an
underscore (_).
Examples:
Valid: my_variable , variable1 , _private_var
Invalid: 123variable , @variable
2. Contain only letters, numbers, or underscores.
Be case-sensitive.
Python is case-sensitive, meaning variables with different capitalization are
considered distinct.
For example, myVariable and myvariable are treated as different variables.
Examples:
myVariable and myvariable are not the same.
total_cost and totalCost are not the same.
Example
Assigning Values:
You can assign different values to a variable at any time:
In [29]: x = 10
print(x)
10
In [30]: x = 20
print(x)
20
Numbers: Integers (e.g., 10, -5), floating-point numbers (e.g., 3.14), complex numbers
(e.g., 2+3j)
Strings: Sequences of characters (e.g., "Hello, world!")
Booleans: True or False values
Lists: Ordered collections of elements (e.g., [1, 2, 3])
Tuples: Immutable ordered collections (e.g., (1, 2, 3))
Dictionaries: Unordered collections of key-value pairs (e.g., {'name': 'Alice', 'age': 30})
Example:
In [31]: number = 10
text = "Python"
is_true = True
Best Practices:
Expressions
Expressions in Python are combinations of values, operators, and functions that evaluate to a
result. They are used to perform calculations, comparisons, and logical operations.
Arithmetic Operators
Addition + 1+2=3
Subtraction - 5-4=1
Multiplication * 2*4=8
Division / 6/3=2
Floor division // 32 // 5 = 6
Modulo % 22 % 5 = 2
Exponent ** 3 ** 2 = 9
Note:
Floor division: // (returns the integer quotient)
Modulo: % (returns the remainder)
Out[32]: 160
We can perform subtraction operations using the minus operator. In this case the result is a
negative number:
Out[33]: -10
Out[34]: 25
Out[35]: 5.0
Out[36]: 4.166666666666667
Out[37]: 5.0
In [38]: # Integer division operation expression
25 // 6
Out[38]: 4
In [39]: # modulo operator (%) returns the remainder of dividing two numbers
15 % 4
Out[39]: 3
In [40]: 10 % 16
Out[40]: 10
Comparison Operators
Logical Operators
Order of Operations
Python follows the PEMDAS rule for the order of operations:
1. Parentheses
2. Exponentiation
3. Multiplication and Division (from left to right)
4. Addition and Subtraction (from left to right)
Example:
In [41]: result = 2 * (3 + 4) / 5
print(result)
2.8
You can control the order of operations in long calculations with parentheses.
In [42]: print(((1 + 3) * (9 - 2) / 2) ** 2)
196.0
Examples:
In [43]: x = 10
x += 5 # Equivalent to x = x + 5
print(x)
15
In [44]: y = 20
y -= 3 # Equivalent to y = y - 3
print(y)
17
In [45]: z = 5
z *= 2 # Equivalent to z = z * 2
print(z)
10
In [46]: a = 10
b = 3
a /= b # Equivalent to a = a / b
print(a)
3.3333333333333335
In [47]: c = 10
d = 3
c //= d # Equivalent to c = c // d
print(c)
In [48]: e = 2
f = 3
e **= f # Equivalent to e = e ** f
print(e)
Syntax:
Example:
10 20 30
In this example, the values 10 , 20 , and 30 are assigned to the variables x , y , and z ,
respectively.
Additional Notes:
You can also use multiple variable assignment to swap the values of two variables:
In [50]: x = 10
y = 20
print("Before swapping:")
print("x =", x)
print("y =", y)
# Swap the values of x and y
x, y = y, x
print("After swapping:")
print("x =", x)
print("y =", y)
Before swapping:
x = 10
y = 20
After swapping:
x = 20
y = 10
The input() function is used to get user input from the console. It prompts the user to enter
a value, which is then returned as a string.
Syntax:
variable_name = input(prompt)
prompt : An optional string that is displayed to the user before they are prompted to enter
input.
Example:
In this example, the input() function prompts the user to enter their name. The user's input
is stored in the name variable, and then it is printed in a greeting message.
Key Points:
The input() function always returns a string, even if the user enters a number.
You can use type conversion functions like int() or float() to convert the input to a
different data type if needed.
The prompt argument is optional but can be helpful for providing clear instructions to the
user.
In this example, the input() function is used to get the user's age as a string. The int()
function is then used to convert the string to an integer before printing it.