0% found this document useful (0 votes)
5 views

Python Data Types - Jupyter Notebook_017ae85a1acb61f561c41b1ab55449c7

The document introduces fundamental Python concepts, including syntax, data types, variables, and expressions. It covers key elements like indentation, keywords, and operators, as well as the importance of comments for code clarity. Additionally, it explains type conversion, variable creation, and arithmetic, comparison, and logical operators in Python.

Uploaded by

gihananjulayt
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
5 views

Python Data Types - Jupyter Notebook_017ae85a1acb61f561c41b1ab55449c7

The document introduces fundamental Python concepts, including syntax, data types, variables, and expressions. It covers key elements like indentation, keywords, and operators, as well as the importance of comments for code clarity. Additionally, it explains type conversion, variable creation, and arithmetic, comparison, and logical operators in Python.

Uploaded by

gihananjulayt
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 17

Objectives

Introduce Fundamental Python Concepts


Explore Data Types and Variables
Work with Expressions
Take Input from the User

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.

Understanding Python syntax is fundamental to writing effective and error-free programs.

Key Elements of Python Syntax:


Indentation: Python uses indentation to define code blocks. This is crucial for determining
the structure and execution flow of your code.

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:

Python is a case-sensitive language.


Statements must be terminated with a newline or a semicolon.
Whitespace is significant in Python, especially for indentation.
Proper use of parentheses, brackets, and quotes is essential for correct syntax.

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.

Here's a simple example:

In [1]: print("Hello, World!")

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:

In [2]: print("You are", 20, "years old.")

You are 20 years old.

In [3]: print("The value of pi is:", 3.14159)

The value of pi is: 3.14159

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:

In [4]: # This is a comment


print("Hello, world!")

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.

Why Comments Matter:

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:

Integers: Whole numbers (e.g., 10, -5, 0).


Floating-point numbers: Numbers with decimal points (e.g., 3.14, -2.5).

2. Strings: Sequences of characters enclosed in quotes (e.g., "Hello", 'world').

3. Booleans: True or False values.

The following code cells contain some examples.

In [6]: # Integer

11

Out[6]: 11

In [7]: # Float

2.14

Out[7]: 2.14

In [8]: # String

"Hello, Python 101!"

Out[8]: '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

In [11]: # Type of "Hello, Python 101!"



type("Hello, Python 101!")

Out[11]: str

Integers

Integers are whole numbers, both positive and negative. They can be used to represent
quantities, counts, or positions.

Here are some examples of integers:

In [12]: # Print the type of -1



type(-1)

Out[12]: int

In [13]: # Print the type of 4



type(4)

Out[13]: int

In [14]: # Print the type of 0



type(0)

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:

In [15]: # Print the type of 1.0



type(1.0) # Notice that 1 is an int, and 1.0 is a float

Out[15]: float

In [16]: # Print the type of 0.5



type(0.5)

Out[16]: float

In [17]: # Print the type of 0.56



type(0.56)

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:

You can create strings using either single or double quotes:

In [18]: # Single quotes


print('Hello, world!')

# Double quotes
print("This is a string")

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' ).

In [19]: print("Hello, world')

Cell In[19], line 1


print("Hello, world')
^
SyntaxError: EOL while scanning string literal

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.

In [20]: # Value true



True

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").

In [21]: # Value false



False

Out[21]: False

When you ask Python to display the type of a boolean object it will show bool which stands
for boolean:

In [22]: # Type of True



type(True)

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.

Common Type Convensions

Converting to a string

Use the str() function to convert any object to a string.

In [23]: str(10) # Converts the integer 10 to the string "10"

Out[23]: '10'

Converting to an integer:

Use the int() function to convert a number or a string representing a number to an integer.

In [24]: int("10") # Converts the string "10" to the integer 10

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")

ValueError: invalid literal for int() with base 10: 'hello'

Converting to a float:

Use the float() function to convert a number or a string representing a number to a


float.
In [26]: float("3.14") # Converts the string "3.14" to the float 3.14

Out[26]: 3.14

In [27]: float(2) # Converts the integer 2 to the float 2.0

Out[27]: 2.0

Implicit Type Conversion

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.

Key points to remember:

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:

Variable Naming Rules in Python

1. Start with a letter or underscore.

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.

Variable names can include letters, numbers, and underscores.


Other characters, such as spaces, special symbols, or punctuation marks, are not
allowed.
Examples:
Valid: my_variable_123 , productPrice , _private_data
Invalid: my variable , variable#1 , $variable

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

In [28]: # Creating variables


name = "Alice"
age = 30
is_student = True

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

Variables can hold values of different data types:

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:

Choose descriptive variable names that reflect their purpose.


Example Instead of x , use customer_name or product_price .

Use consistent naming conventions.


Snake case: Words are separated by underscores, and all letters are lowercase (e.g.,
my_variable ).
Camel case:The first letter of the first word is lowercase, while the first letter of each
subsequent word is capitalized (e.g., myVariable ).
Pascal case: The first letter of every word, including the first word, is capitalized (e.g.,
MyVariable ).

Avoid using reserved keywords as variable names.


Common reserved keywords: if , else , for , while , def , class , return , etc.

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

Operation Symbol Example

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)

In [32]: # Addition operation expression



43 + 60 + 16 + 41

Out[32]: 160

We can perform subtraction operations using the minus operator. In this case the result is a
negative number:

In [33]: # Subtraction operation expression



50 - 60

Out[33]: -10

We can do multiplication using an asterisk:

In [34]: # Multiplication operation expression



5 * 5

Out[34]: 25

We can also perform division with the forward slash:

In [35]: # Division operation expression



25 / 5

Out[35]: 5.0

In [36]: # Division operation expression



25 / 6

Out[36]: 4.166666666666667

In [37]: # Integer division operation expression



28.7 // 5

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

Operation Symbol Example

Equal to == 10 == 5 # Output: False

Not equal to != 10 != 5 # Output: True

Greater than > 10 > 5 # Output: True

Less than < 10 < 5 # Output: False

Greater than or equal to >= 10 >= 5 # Output: True

Less than or equal to <= 10 <= 5 # Output: False

Logical Operators

Operation Symbol Example

And and True and False # Output: False

Or or True or False # Output: True

Not not not True # Output: False

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

Arithmetic Assignment Operators


Arithmetic assignment operators combine arithmetic operations with assignment, providing
a shorthand way to modify the value of a variable.
They have the general form: variable_name operator= expression , where operator
is an arithmetic operator ( + , - , * , / , // , % , ** ).

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)

Multiple Variable Assignment:


In Python, you can assign values to multiple variables simultaneously using a comma-
separated list on the right-hand side of the assignment operator. This is known as multiple
variable assignment.

Syntax:

variable1, variable2, ..., variableN = value1, value2, ..., valueN

Example:

In [49]: x, y, z = 10, 20, 30


print(x, y, z)

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

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 [51]: name = input("Enter your name: ")


print("Hello, " + name + "!")

Enter your name: John


Hello, John!

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.

Example with type conversion:

In [52]: age = int(input("Enter your age: "))


print("You are", age, "years old.")

Enter your age: 30


You are 30 years old.

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.

You might also like