CCD_Module8-PL101_01
CCD_Module8-PL101_01
1
“Python Data Type, Type Conversion, Type Casting, Basic Input, Output, and Import”
In this lesson, we will learn about different data types you can use in Python, also we will learn
about type conversion and uses of type conversion. And also will learn simple ways to display output to
users and take input from users in Python with the help of examples.
References:
• Python Programming for Beginners
INFORMATION SHEET PL 101-8.1.1
“Python Data Type, Type Conversion, Type Casting, Basic Inpu, Output, and Import”
There are various data types in Python. Some of the important types are listed below.
Python Numbers
Integers, floating point numbers, and complex numbers fall under the Python
numbers category. They are defined as int, float , and complex classes in Python.
We can use the type() function to know which class a variable or a value belongs to.
Similarly, the isinstance() function is used to check if an object belongs to a particular class.
a=5
print(a, "is of type", type(a))
a = 2.0
print(a, "is of type", type(a))
a = 1+2j
print(a, "is complex number?", isinstance(1+2j,complex))
Output
>>> a = 1234567890123456789
>>> a
1234567890123456789
>>> b = 0.1234567890123456789
>>> b
0.12345678901234568
>>> c = 1+2j
>>> c
(1+2j)
Python Strings
The string is a sequence of Unicode characters. We can use single quotes or double
quotes to represent strings. Multi-line strings can be denoted using triple quotes, ''' or """.
s = "This is a string"
print(s)
s = '''A multiline
string'''
print(s)
Output
This is a string
A multiline
string
Just like a list and tuple, the slicing operator [ ] can be used with strings. Strings,
however, are immutable.
s = 'Hello world!'
# s[4] = 'o'
print("s[4] = ", s[4])
# s[6:11] = 'world'
print("s[6:11] = ", s[6:11])
# Generates error
# Strings are immutable in Python
s[5] ='d'
Output
s[4] = o
s[6:11] = world
Traceback (most recent call last):
File "<string>", line 11, in <module>
TypeError: 'str' object does not support item assignment
>>> float(5)
5.0
Conversion from float to int will truncate the value (make it closer to zero).
>>> int(10.6)
10
>>> int(-10.6)
-10
>>> float('2.5')
2.5
>>> str(25)
'25'
>>> int('1p')
Traceback (most recent call last):
File "<string>", line 301, in runcode
File "<interactive input>", line 1, in <module>
ValueError: invalid literal for int() with base 10: '1p'
>>> set([1,2,3])
{1, 2, 3}
>>> tuple({5,6,7})
(5, 6, 7)
>>> list('hello')
['h', 'e', 'l', 'l', 'o']
To convert to dictionary, each element must be a pair:
>>> dict([[1,2],[3,4]])
{1: 2, 3: 4}
>>> dict([(3,26),(4,44)])
{3: 26, 4: 44}
Type Conversion
The process of converting the value of one data type (integer, string, float, etc.) to
another data type is called type conversion. Python has two types of type conversion.
Implicit Type Conversion
Explicit Type Conversion
Let's see an example where Python promotes the conversion of the lower data type
(integer) to the higher data type (float) to avoid data loss.
Example 1: Converting integer to float
num_int = 123
num_flo = 1.23
print("datatype of num_int:",type(num_int))
print("datatype of num_flo:",type(num_flo))
print("Value of num_new:",num_new)
print("datatype of num_new:",type(num_new))
In the output, we can see the data type of num_int is an integer while the data type
of num_flo is a float.
Also, we can see the num_new has a float data type because Python always converts
smaller data types to larger data types to avoid the loss of data.
Now, let's try adding a string and an integer, and see how Python deals with it.
Example 2: Addition of string(higher) data type and integer(lower) datatype
num_int = 123
num_str = "456"
print(num_int+num_str)
As we can see from the output, we got TypeError. Python is not able to use Implicit
Conversion in such conditions.
However, Python has a solution for these types of situations which is known as Explicit
Conversion.
<required_datatype>(expression)
Typecasting can be done by assigning the required data type function to the expression.
num_str = int(num_str)
print("Data type of num_str after Type Casting:",type(num_str))
After converting num_str to an integer value, Python is able to add these two variables.
We got the num_sum value and data type to be an integer.
“Python Basic Input, Output, and Import”
Python Output
In Python, we can simply use the print() function to print output. For example,
print('Python is powerful')
Here, the print() function displays the string enclosed inside the single quotation.
Syntax of print()
In the above code, the print() function is taking a single parameter.
However, the actual syntax of the print function accepts 5 parameters
print('Good Morning!')
print('It is rainy today')
Output
Good Morning!
It is rainy today
In the above example, the print() statement only includes the object to be printed. Here, the
value for end is not used. Hence, it takes the default value '\n'.
So we get the output in two different lines.
Output
Notice that we have included the end= ' ' after the end of the first print() statement.
Hence, we get the output in a single line separated by space.
Example 3: Python print() with sep parameter
Output
In the above example, the print() statement includes multiple items separated by a comma.
Notice that we have used the optional parameter sep= ". " inside the print() statement.
Hence, the output includes items separated by . not comma.
We can also use the print() function to print Python variables. For example,
number = -10.6
# print literals
print(5)
# print variables
print(number)
print(name)
Output
5
-10.6
Python Programming
Example: Print Concatenated Strings
We can also join two strings together inside a print() statement. For example,
print('Python Programming is ' + 'awesome.')
Output
Here,
the + operator joins two strings 'Python Programming is ' and 'awesome.'
the print() function prints the joined string
Output formatting
Sometimes we would like to format our output to make it look attractive. This can be done by
using the str.format() method. For example,
x=5
y = 10
Here, the curly braces {} are used as placeholders. We can specify the order in which they are
printed by using numbers (tuple index).
Python Input
While programming, we might want to take the input from the user. In Python, we can use
the input() function.
Syntax of input()
input([prompt])
Output
Enter a number: 10
You Entered: 10
Data type of num: <class 'str'>
In the above example, we have used the input() function to take input from the user and stored
the user input in the num variable.
It is important to note that the entered value 10 is a string, not a number.
So, type(num) returns <class 'str'>.
To convert user input into a number we can use int() or float() functions as:
Here, the data type of the user input is converted from string to integer .
Python Import
When our program grows bigger, it is a good idea to break it into different modules.
A module is a file containing Python definitions and statements. Python modules have a
filename and end with the extension .py.
Definitions inside a module can be imported to another module or the interactive
interpreter in Python. We use the import keyword to do this.
For example, we can import the math module by typing the following line:
import math
We can use the module in the following ways:
import math
print(math.pi)
Output
3.141592653589793
Now all the definitions inside math module are available in our scope. We can also import some
specific attributes and functions only, using the from keyword. For example:
>>> from math import pi
>>> pi
3.141592653589793
While importing a module, Python looks at several places defined in sys.path. It is a list of
directory locations.
>>> import sys
>>> sys.path
['',
'C:\\Python33\\Lib\\idlelib',
'C:\\Windows\\system32\\python33.zip',
'C:\\Python33\\DLLs',
'C:\\Python33\\lib',
'C:\\Python33',
'C:\\Python33\\lib\\site-packages']
We can also add our own location to this list.
STUDENT NAME: __________________________________ SECTION: __________________
Instruction:
PRECAUTIONS:
Do not just copy all your output from the internet.
Use citation and credit to the owner if necessary.
ASSESSMENT METHOD: WRITTEN WORK CRITERIA CHECKLIST
STUDENT NAME: __________________________________ SECTION: __________________
CRITERIA SCORING
Did I . . .
1 2 3 4 5
1. Focus - The single controlling point made with an awareness of a task
about a specific topic.
2. Content - The presentation of ideas developed through facts, examples,
anecdotes, details, opinions, statistics, reasons, and/or opinions
3. Organization – The order developed and sustained within and across
paragraphs using transitional devices and including the introduction and
conclusion.
4. Style – The choice, use, and arrangement of words and sentence
structures that create tone and voice.
5. .
6. .
7. .
8. .
9. .
10. .
TEACHER’S REMARKS: QUIZ RECITATION PROJECT
GRADE:
5 - Excellently Performed
4 - Very Satisfactorily Performed
3 - Satisfactorily Performed
2 - Fairly Performed
1 - Poorly Performed
_______________________________
TEACHER
Date: ______________________