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

CCD_Module8-PL101_01

PROGRAMMING LANGUAGE

Uploaded by

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

CCD_Module8-PL101_01

PROGRAMMING LANGUAGE

Uploaded by

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

INFORMATION SHEET PL 101-8.1.

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”

Data types in Python


Every value in Python has a datatype. Since everything is an object in Python
programming, data types aly classes and variables are instances (objects) of these classes.

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

5 is of type <class 'int'>


2.0 is of type <class 'float'>
(1+2j) is complex number? True

 Integers can be of any length, it is only limited by the memory available.


 A floating-point number is accurate up to 15 decimal places. Integer and floating points
are separated by decimal points. 1 is an integer, 1.0 is a floating-point number.
 Complex numbers are written in the form, x + yj, where x is the real part and y is the
imaginary part. Here are some examples.

>>> a = 1234567890123456789
>>> a
1234567890123456789
>>> b = 0.1234567890123456789
>>> b
0.12345678901234568
>>> c = 1+2j
>>> c
(1+2j)

Notice that the float variable b got truncated.

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

Conversion between data types


We can convert between different data types by using different type conversion
functions like int(), float(), str(), etc.

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

Conversion to and from string must contain compatible values.

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

We can even convert one sequence to another.

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

Implicit Type Conversion


In Implicit type conversion, Python automatically converts one data type to another
data type. This process doesn't need any user involvement.

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

num_new = num_int + num_flo

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

When we run the above program, the output will be:

datatype of num_int: <class 'int'>


datatype of num_flo: <class 'float'>

Value of num_new: 124.23


datatype of num_new: <class 'float'>

In the above program,


We add two variables num_int and num_flo, storing the value in num_new.
We will look at the data type of all three objects respectively.

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("Data type of num_int:",type(num_int))


print("Data type of num_str:",type(num_str))

print(num_int+num_str)

When we run the above program, the output will be:

Data type of num_int: <class 'int'>


Data type of num_str: <class 'str'>

Traceback (most recent call last):


File "python", line 7, in <module>
TypeError: unsupported operand type(s) for +: 'int' and 'str'

In the above program,


We add two variables num_int and 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.

Explicit Type Conversion


In Explicit Type Conversion, users convert the data type of an object to the required
data type. We the predefined functions like int(), float(), str(), etc to perform explicit type
conversion.
This type of conversion is also called typecasting because the user casts (changes) the
data type of the objects.
Syntax :

<required_datatype>(expression)

Typecasting can be done by assigning the required data type function to the expression.

Example 3: Addition of string and integer using explicit conversion


num_int = 123
num_str = "456"

print("Data type of num_int:",type(num_int))


print("Data type of num_str before Type Casting:",type(num_str))

num_str = int(num_str)
print("Data type of num_str after Type Casting:",type(num_str))

num_sum = num_int + num_str

print("Sum of num_int and num_str:",num_sum)


print("Data type of the sum:",type(num_sum))

When we run the above program, the output will be:

Data type of num_int: <class 'int'>


Data type of num_str before Type Casting: <class 'str'>

Data type of num_str after Type Casting: <class 'int'>

Sum of num_int and num_str: 579


Data type of the sum: <class 'int'>

In the above program,

We add num_str and num_int variable.

We converted num_str from string(higher) to integer(lower) type using int() function to


perform the addition.

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

# Output: 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(object= separator= end= file= flush=)


Here,

 object - value(s) to be printed


 sep (optional) - allows us to separate multiple objects inside print().
 end (optional) - allows us to add add specific values like new line "\n", tab "\t"
 file (optional) - where the values are printed. It's default value is sys.stdout (screen)
 flush (optional) - boolean specifying if the output is flushed or buffered. Default: False

Example 1: Python Print Statement

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.

Example 2: Python print() with end Parameter


# print with end whitespace
print('Good Morning!', end= ' ')

print('It is rainy today')

Output

Good Morning! It is rainy today

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

print('New Year', 2023, 'See you soon!', sep= '. ')

Output

New Year. 2023. See you soon!

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.

Example: Print Python Variables and Literals

We can also use the print() function to print Python variables. For example,
number = -10.6

name = "Python Programming"

# 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

Python Programming is awesome.

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

print('The value of x is {} and y is {}'.format(x,y))

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

Here, prompt is the string we wish to display on the screen. It is optional.

Example: Python User Input

# using input() to take user input


num = input('Enter a number: ')

print('You Entered:', num)

print('Data type of num:', type(num))

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:

num = int(input(Enter a number: '))

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: __________________

PERFORMANCE TASK PL 101-8.1.1


WRITTEN WORK TITLE:

WRITTEN TASK OBJECTIVE:


MATERIALS:
 Pen and Paper
TOOLS & EQUIPMENT:
 None
ESTIMATED COST: None

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: __________________

PERFORMANCE OUTPUT CRITERIA CHECKLIST PL 101-8.1.1

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: ______________________

You might also like