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

python programming unit 2

The document provides an overview of Python programming concepts including input/output, error types, variables, data types, and functions. It explains the use of various data types such as strings, lists, tuples, and arrays, as well as the importance of functions for code organization and reusability. Additionally, it covers modules in Python, including how to import and use them effectively.

Uploaded by

ahanasayeed.786
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
3 views

python programming unit 2

The document provides an overview of Python programming concepts including input/output, error types, variables, data types, and functions. It explains the use of various data types such as strings, lists, tuples, and arrays, as well as the importance of functions for code organization and reusability. Additionally, it covers modules in Python, including how to import and use them effectively.

Uploaded by

ahanasayeed.786
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 17

BCA_1(PYTHON)

SYEDA HUSNA(BE,Mtech)

UNIT 2
Input and output, error and types, Value and variable data type, string, keywords, identifiers,
statement and expression, comment, constant, tuple, array, operators, function (types of
function), import modules, import files.

INPUT AND OUTPUT INPUT:

Input is data entered by user (end user) in the program. In python, input () function is available
for input.
Syntax for input () is: variable = input (“data”)
x=input ("enter the name:")
y=int (input ("enter the number")) enter the number 3 >>>
OUTPUT: Output can be displayed to the user using Print statement

Syntax: print (expression/constant/variable


Example: print ("Hello”) output: Hello

Syntax Errors
Syntax errors occur when the code violates the programming language's rules.
Examples:
1. Missing or mismatched brackets: print("Hello"
2. Incorrect indentation: if True: print("Hello") (should be indented)
3. Typo in keywords: prnt("Hello") (should be print)
Types of Errors in Python
1. SyntaxError: Errors in code syntax.
2. TypeError: Errors when using incompatible data types. Example: 1 + "hello"
3. ValueError: Errors when a function or operation receives an argument with an incorrect value.
Example: int("hello")
4. NameError: Errors when using an undefined variable. Example: print(x) (if x is not defined)
5. RuntimeError: Errors that occur during code execution.

VARIABLES: A variable allows us to store a value by assigning it to a name, which can


be used later.
1. Named memory locations to store values.
2. Programmers generally choose names for their variables that are meaningful.
3. It can be of any length.
4. No space is allowed.

P.V.S FIRST GRADE COLLEGE ,Chitradurga 1


BCA_1(PYTHON)
SYEDA HUSNA(BE,Mtech)

5. We don't need to declare a variable before using it.


6. In Python, we simply assign a value to a variable and it will exist

VALUES AND DATA TYPE


VALUE: Value can be any letter, number or string.

Eg, Values are 2, 42.0, and 'Hello, World!'. (These values belong to different datatypes.)
Data type:
1. Every value in Python has a data type.
2. It is a set of values, and the allowable operations on those values.
Data Types in Python:
 Every value in Python has a datatype.
 Since everything is an object in Python programming, data types are actually classes and
variables are instance (object) of these classes.
There are various data types in Python.
 Some of the important types are listed below.
1. Numbers
2. Strings
3. List
4. Tuples
5. Sets
6. Dictionary

NUMBERS

Number data types: Number data types store numeric values.


Integers: An integer is a whole number with no decimal places.
1. For example, 1 is an integer, but 1.0 isn’t.
 Number objects are created when you assign a value to them

 Python has three built-in numeric data types: integers, floating-point numbers, and complex
numbers.
Float: In Python, floating point numbers (float) are positive and negative real numbers with a
fractional part denoted by the decimal symbol.
or the scientific notation E or e, e.g. 1234.56, 3.142, -1.55, 0.23, 1.432e2,1e-4

P.V.S FIRST GRADE COLLEGE ,Chitradurga 2


BCA_1(PYTHON)
SYEDA HUSNA(BE,Mtech)

Python has four standard data types:

Sequence:

 A sequence is an ordered collection of items, indexed by positive integers.


 It is a combination of mutable (value can be changed) and immutable (values cannot be
changed) datatypes.
There are three types of sequence data type available in Python, they are
 Strings
 Lists
 Tuples Strings
String:
 A String in Python consists of a series or sequence of characters - letters, numbers, and
special characters.
 Strings are marked by quotes:
• Single quotes(' ') E.g., 'This a string in single quotes'
• double quotes(" ") E.g., "'This a string in double quotes'"
• triple quotes(""" """)E.g., """This is a paragraph. It is made up of multiple lines
and sentences."""
 Individual character in a string is accessed using a subscript(index).
 Characters can be accessed using indexing and slicing operations .Strings are
Immutable i.e the contents of the string cannot be changed after it is created.

P.V.S FIRST GRADE COLLEGE ,Chitradurga 3


BCA_1(PYTHON)
SYEDA HUSNA(BE,Mtech)

LISTS
 List is an ordered sequence of items.
 Values in the list are called elements /items.
 It can be written as a list of comma-separated items (values) between square brackets[].
 Items in the lists can be of different datatypes.

Example:
list1 = ['physics', 'chemistry', 1997, 2000];
list2 = [1, 2, 3, 4, 5 ];
mylist = ["apple", "banana", "cherry"]

P.V.S FIRST GRADE COLLEGE ,Chitradurga 4


BCA_1(PYTHON)
SYEDA HUSNA(BE,Mtech)

TUPLES
A tuple is a collection of objects that are ordered and immutable. Tuples are defined using
parentheses () and elements are separated by commas.
my_tuple = (1, 2, 3, "hello")
print(my_tuple[0]) # Output: 1
 Tuples are another container type extremely similar in nature to lists.
 The only visible difference between tuples and lists is that tuples use parentheses and
lists use square brackets.
 Functionally. there is a more significant difference, and that is the fact that tuples are
immutable.
 Tuples are used to store multiple items in a single variable.
 Tuple is one of 4 built-in data types in Python used to store collections of data, the other
3 are List, Set, and Dictionary, all with different qualities and usage.
 A tuple is a collection which is ordered and unchangeable.

P.V.S FIRST GRADE COLLEGE ,Chitradurga 5


BCA_1(PYTHON)
SYEDA HUSNA(BE,Mtech)

Tuple Items
 Tuple items are ordered, unchangeable, and allow duplicate values.
 Tuple items are indexed, the first item has index [0], the second item has index [1] etc.
1. Ordered: When we say that tuples are ordered, it means that the items have a defined order,
and that order will not change.
2. Unchangeable: Tuples are unchangeable, meaning that we cannot change, add or remove
items after the tuple has been created.
3. Allow Duplicates: Since tuple are indexed, tuples can have items with the same value

all are valid example.


 An identifier cannot start with a digit.
 Keywords cannot be used as identifiers.
 Cannot use special symbols like!, @, #, $, % etc. in our identifier.
 Identifier can be of any length.

P.V.S FIRST GRADE COLLEGE ,Chitradurga 6


BCA_1(PYTHON)
SYEDA HUSNA(BE,Mtech)

STATEMENTS AND EXPRESSIONS:


Statements:
 -Instructions that a Python interpreter can executes are called statements.
 -A statement is a unit of code like creating a variable or displaying a value.
The first line is an assignment statement that gives a value to n. The second line is a print
statement that displays the value of n
>>> n = 17 >>>

print (n) Here,

Expressions:
-An expression is a combination of values, variables, and operators.
- A value all by itself is considered an expression, and also a variable.
COMMENT
A hash sign # is the beginning of a comment anything return after # in a line ignored by
interpreter
Ex: #calculate percentage of a hour
Percentage=(minute*100)/60
CONSTANT
A constant is a type of variable whose value cannot be changed.
Ex: pi=3.14
Gravity = 9.8

. OPERATORS:
Operators are the constructs which can manipulate the value of operands.
Consider the expression 4 + 5 = 9. Here, 4 and 5 are called operands and + is called operator
Types of Operators
Python language supports the following types of operators
a. Arithmetic Operators
b. Comparison (Relational)Operators
c. Assignment Operators
d. Logical Operators
e. Bitwise Operators
f. Membership Operators
g. Identity Operators

P.V.S FIRST GRADE COLLEGE ,Chitradurga 7


BCA_1(PYTHON)
SYEDA HUSNA(BE,Mtech)

P.V.S FIRST GRADE COLLEGE ,Chitradurga 8


BCA_1(PYTHON)
SYEDA HUSNA(BE,Mtech)

P.V.S FIRST GRADE COLLEGE ,Chitradurga 9


BCA_1(PYTHON)
SYEDA HUSNA(BE,Mtech)

P.V.S FIRST GRADE COLLEGE ,Chitradurga 10


BCA_1(PYTHON)
SYEDA HUSNA(BE,Mtech)

FUNCTIONS: Function is a sub program which consists of set of instructions used to perform
a specific task. A large program is divided into basic building blocks called function.
Need for Function:
 When the program is too complex and large they are divided into parts. Each
part is separately coded and combined into single program. Each subprogram is
called as function.
 Debugging, Testing and maintenance becomes easy when the program is
divided into subprograms.
 Functions are used to avoid rewriting same code again and again in a program.
 Function provides code re-usability
 The length of the program is reduced
Types of function: Functions can be classified into two categories:
i) user defined function
ii) Built in function

P.V.S FIRST GRADE COLLEGE ,Chitradurga 11


BCA_1(PYTHON)
SYEDA HUSNA(BE,Mtech)

ii)User Defined Functions:


 User defined functions are the functions that programmers create for their requirement
and use.
 These functions can then be combined to form module which can be used in other
programs by importing them.
Advantages of user defined functions:
• Programmers working on large project can divide the work load by making
different functions.
• If repeated code occurs in a program, function can be used to include those
codes and execute when needed by calling that function.
Function definition:(Sub program)
 def keyword is used to define a function.
 Give the function name after def keyword followed by parentheses in which
arguments are given. End with colon (:)
 Inside the function add the program statements to be executed
 End with or without return statement

P.V.S FIRST GRADE COLLEGE ,Chitradurga 12


BCA_1(PYTHON)
SYEDA HUSNA(BE,Mtech)

Arrays
Arrays are an ordered collection of elements of the same data type. Python arrays can only hold
a sequence of multiple items that are of the same type.
Difference between Python Lists and Python Arrays Lists and arrays behave similarly.
Just like arrays, lists are an ordered sequence of elements.
They are also mutable and not fixed in size, which means they can grow and shrink throughout
the life of the program.
Items can be added and removed, making them very flexible to work with.
However, lists and arrays are not the same thing.
Lists store items that are of various data types. This means that a list can contain integers,
floating point numbers, strings, or any other Python data type, at the same time. That is not the
case with arrays.
Arrays store only items that are of the same single data type. There are arrays that contain only
integers, or only floating point numbers, or only any other Python data type you want to use.
Advantages of Python Arrays
Lists are built into the Python programming language, whereas arrays aren't. Arrays are not a
built-in data structure, and therefore need to be imported via the array module in order to be
used. Arrays of the array module are are useful when you want to work with homogeneous
data. They are also more compact and take up less memory and space which makes them more
size efficient compared to lists.

P.V.S FIRST GRADE COLLEGE ,Chitradurga 13


BCA_1(PYTHON)
SYEDA HUSNA(BE,Mtech)

Define Arrays in Python


Once the array module is imported, we can then go on to define a Python array.
The general syntax for creating an array looks like this:
variable_name = array(typecode,[elements])
 variable_name would be the name of the array.
 The typecode specifies what kind of elements would be stored in the array. Whether it would
be an array of integers, an array of floats or an array of any other Python data type. Remember
that all elements should be of the same data type.
 Inside square brackets you mention the elements that would be stored in the array, with each
element being separated by a comma. You can also create an empty array by just writing
variable_name = array(typecode) alone, without any elements.
Example of how to define an array in Python:
import array as arr
numbers = arr.array('i',[10,20,30])
print(numbers)
#output
#array ('i', [10, 20, 30])

P.V.S FIRST GRADE COLLEGE ,Chitradurga 14


BCA_1(PYTHON)
SYEDA HUSNA(BE,Mtech)

MODULES IN PYTHON
A python module is a file that consists of python definition and statements. A module can
define functions, classes and variables.
It allows us to logically arrange related code and makes the code easier to understand and
use.
 Syntax: import
 module_namemodule_name.function_name(variable)

1.Import statement:
• An import statement is used to import python module in some python source file.
Syntax: import module1 [, module2 […module]]
 Example:
 >>>import math
 >>>print (math.pi)
 3.14159265

P.V.S FIRST GRADE COLLEGE ,Chitradurga 15


BCA_1(PYTHON)
SYEDA HUSNA(BE,Mtech)

2.Import with renaming:


The import a module by renaming it as follows,
 >>>import math as a
 >>>print(“The value of pi is “,a.pi)
 The value of pi is 3.14159265

Writing modules:
• Any python source code file can be imported as a module into another python source file.
For example, consider the following code named as support.py, which is python source file
defining two function add(), display()
 Support.py:
 def add(a,b):
 print (“The result is “,a+b)
 return def display(p):
 print (“welcome “,p)
 return
The support.py file can be imported as a module into another python source file and its
functions can be called from the new files as shown in the following code:

3. Import file name


import support #import module support
support.add(3,4) #calling add() of support module with two integers
support.add (3.5,4.7) #calling add() of support module with two real values
support.add (‘a’,’b’) #calling add() of support module with two character values
support.add (“yona”,”alex”) #calling add() of support module with two string values
support.display (‘fleming’) #calling display() of support module with a string values

P.V.S FIRST GRADE COLLEGE ,Chitradurga 16


BCA_1(PYTHON)
SYEDA HUSNA(BE,Mtech)

P.V.S FIRST GRADE COLLEGE ,Chitradurga 17

You might also like