Thanks to visit codestin.com
Credit goes to www.scribd.com

0% found this document useful (0 votes)
4 views24 pages

Unit 1

Uploaded by

impu1616
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)
4 views24 pages

Unit 1

Uploaded by

impu1616
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/ 24

Unit-1

Introduction to Python

Python Interpreter/Shell:

Python is an interpreter language. It means it executes the code line by line. Python
provides a Python Shell, which is used to execute a single Python command and display
the result.

It is also known as REPL (Read, Evaluate, Print, Loop), where it reads the command,
evaluates the command, prints the result, and loop it back to read the command again.

Identifier

Python identifiers are user-defined names. They are used to specify the names of
variables, functions, classes, modules, etc.

Rules:

•Identifiers cannot be a keyword.

•Identifiers are case-sensitive.

•It can have a sequence of letters and digits. However, it must begin with a letter or(_)
The first letter of an identifier cannot be a digit.

•It's a convention to start an identifier with a letter rather(_).

•Whitespaces are not allowed.

•We cannot use special symbols like !,@,#,$, and so on.

Valid Identifiers Invalid Identifiers

name @name

return_value return

highest_score highest score

name1 1name

convert_to_string convert to_string

Python is a case-sensitive language. This means, Variable and variable are not the
same.

Comments:

In programming language comments are hints that we use to make our code more
understandable.
Comments are completely ignored by the interpreter. They are meant for fellow
programmers. For example,

# declare and initialize two variables

num1 = 6

num2 = 9

#print the output

print(‘this is thr output’)

output: this is thr output

Keywords

Python has a set of keywords that are reserved words that cannot be used as variable
names, function names, or any other identifiers

Keyword Description

and A logical operator

as To create an alias

assert For debugging

break To break out of a loop

class To define a class

continue To continue to the next iteration of a loop

def To define a function

del To delete an object

elif Used in conditional statements, same as else if

else Used in conditional statements

except Used with exceptions, what to do when an exception occurs

False Boolean value, result of comparison operations

finally Used with exceptions, a block of code that will be executed no matter if
there is an exception or not

for To create a for loop


Statements and Expressions

A statement is an instruction that the Python interpreter can execute. So far we have
come across assignment statements. Some other kinds of statements that we’ll see
shortly are while statements, for statements, if statements, and import statements.
(There are other kinds too!) An expression is a combination of values, variables,
operators, and calls to functions. Expressions need to be evaluated. If you ask

Python to print an expression, the interpreter evaluates the expression and displays the
result.

If we take a look at this same example in the Python shell, we will see one of the distinct
differences between statements and expressions.

>>> y = 3.14

>>> x = len("hello")

>>> print(x)

>>> print(y)

3.14

>>> y

3.14

Note that when we enter the assignment statement, y = 3.14, only the prompt is
returned. There is no value. This is due to the fact that statements, such as the
assignment statement, do not return a value. They are simply executed. On the other
hand, the result of executing the assignment statement is the creation of a reference
from a variable, y, to a value, 3.14. When we execute the print function working only, we
see the value that y is referring to. In fact, evaluating y by itself results in the same
response.

Variables

Variables are containers for storing data values.

Variable Names: variable can have a short name (like x and y) or a more descriptive
name (age, carname, total_volume).

Rules for Python variables:

•A variable name must start with a letter or the underscore character

•A variable name cannot start with a number


•A variable name can only contain alpha-numeric characters

and underscores (A-z, 0-9, and _ )

•Variable names are case-sensitive (age, Age and AGE are three different variables)

Examples:

Legal variable names:

myvar = "Python"

my_var = "Python"

_my_var =”Python"

myVar ="Python"

MYVAR ="Python"

myvar2 ="Python"

Creating Variables

Python has no command for declaring a variable.

A variable is created the moment you first assign a value to it.

X=1

y = "python"

print(x)

print(y)

output:

python

Variables do not need to be declared with any particular type and can even change type
after they have been set.

X =4 # x is of type int

x ="Python” # x is now of type str

print(x)

Output:

Python
If you want to specify the data type of a variable, this can be done with casting.

X = str(3) # x will be '3'

y = int(3) # y will be 3

z = float(3) # z will be 3.0

Get the Type

You can get the data type of a variable with the type() function.

X=1

y ="Python"

print(type(x))

print(type(y))

Output:

<class ‘int’>

<class ‘str’>

Single or Double Quotes:

String variables can be declared either by using single or double quotes:

x ="Python"

# is the same as

x =’Python’

output:

Python

Python

Variable names are case-sensitive.

a =4

A =”Python”

#A will not overwrite a

output:

Python
Precedence and Associativity:

Multi Operator expression:

a = 10 + 3 * 4

print(a)

b = (10 + 3) * 4

print(b)

c = 10 + (3 * 4)

print(c)

Output

22

52

22
Data Types in Python

Data types are the classification or categorization of data items. It represents the kind of
value that tells what operations can be performed on a particular data. Since everything
is an object in Python programming, data types are actually classes and variables are
instance (object) of these classes.

Following are the standard or built-in data type of Python:

•Numeric

•Sequence Type

•Boolean

•Set

•Dictionary

Numeric:

In Python, numeric data type represents the data which has numeric value.

Numeric value can be integer, floating number or even complex numbers.

These values are defined as int, float and complex class in Python.

Integers– This value is represented by int class. It contains positive or negative whole
numbers (without fraction or decimal). In Python there is no limit to how long an integer
value can be.

Float – This value is represented by float class. It is a real number with floating point
representation. It is specified by a decimal point. Optionally, the character e or E
followed by a positive or negative integer may be appended to specify scientific
notation.

Complex Numbers – Complex number is represented by complex class. It is specified


as (real part) + (imaginary part)j. For example – 2+3.

Sequence Type:

In Python, sequence is the ordered collection of similar or different data types.


Sequences allow to store multiple values in an organized and efficient fashion.

There are several sequence types in Python –

• String • List • Tuple


1) String:
In Python, Strings are arrays of bytes representing Unicode characters. A string is
a collection of one or more characters put in a single quote, double-quote or
triple quote. In python there is no character data type, a character is a string of
length one. It is represented by str class.
Creating String Strings:
In Python can be created using single quotes or double quotes or even triple
quotes.
# Creating a String
# with single Quote/double quote/ triple quotes
String1 = 'hello’
String2 = “hello”
string3 = ‘’’hello’’’
print(String1)
print(String2)
print(string3)
output:
hello
hello
hello
2) List:
Lists are just like the arrays, declared in other languages which is a ordered
collection of data. It is very flexible as the items in a list do not need to be of the
same type.
Creating List Lists:
In Python can be created by just placing the sequence inside the square
brackets[].
# Creating a List with
# the use of multiple values
List = ["python", “OS", "CN”]
print("\nList containing multiple values: ")
print(List) 3)
Tuple Just like list, tuple is also an ordered collection of Python objects. The only
difference between tuple and list is that tuples are immutable
i.e. tuples cannot be modified after it is created. It is represented by tuple class.
# Creating a Tuple with the use of Strings

tuple1 = ('Python', 'For')

tupel2 = (‘BCA’)

tupel= tupel1+tupel2
print(tupel)

Output:

(‘Python’,’For’,’BCA’)

Boolean

Data type with one of the two built-in values,True or False. Boolean objects that are
equal to True are truthy (true), and those equal to False are falsy (false). But non-
Boolean objects can be evaluated in Boolean context as well and determined to be true
or false. It is denoted by the class bool

# Python program to demonstrate boolean type

print(type(True))

print(type(False))

print(type(true))

Output:

<class 'bool'>

<class 'bool'>

Set

In Python, Set is an unordered collection of data type that is iterable,

mutable and has no duplicate elements. The order of elements in a set is

undefined though it may consist of various elements.

# Creating a Set with

# a mixed type of values

# (Having numbers and strings)

set1 = set([1, 2, 'Python', 4, 'For', 6, 'Computer'])

print(set1)

output:

{1, 2, 4, 6, ‘Python', 'Computer'}

Dictionary

Dictionary: in Python is an unordered collection of data values, used to store data


values like a map, which unlike other Data Types that hold only single value as an
element, Dictionary holds key : value pair. Key-value is provided in the dictionary to
make it more optimized. Each key-value pair in a Dictionary is separated by a colon :,
whereas each key is separated by a ‘comma’.

# Creating a Dictionary with Integer Keys

Dict = {1: 'Python', 2: 'CN', 3: 'OS'}

print(Dict)

Output: {1: 'Python', 2: 'CN', 3: 'OS'}

Dict = {1: 'Python', 2: 'CN', 3: 'OS'}

print(Dict[1])

OUTPUT: Python

Comments:

Types of Comments in Python

Python, there are two types of comments:

• single-line comment

• multi-line comment

Single-line Comment: A single-line comment starts and ends in the same line. We use
the # symbol in Python to write a single-line comment. For example:

a = 10 #variable a is assigned with value 10.

Multi-line Comment in Python:

Python doesn't offer a separate way to write multiline comments. However, there are
other ways to get around this issue. We can use # at the beginning of each line of
comment on multiple lines. For example, #this is comment These triple quotes are
generally used for multi-line strings. But if we do not assign it to any variable or function,
we can use it as a comment. ‘’’ hello, this is python class BCA 2ND YEAR’’’ But when we
combine different types of expressions or use multiple operators in a single expression,
operator precedence comes into play.

Reading Input

Python Input

While programming, we might want to take the input from the user. In Python, we can
use theinput()function.

Syntax of input()
# using input() to take user

input num=input(‘enter the number’)

print(‘you entered’,num)

Output: enter the number 5 you entered 5

Python Output

In Python, we can simply use the print() function to print output. For example,

print(‘Python is powerful’)

output: Python is powerful

Type Conversion

There are two types of Type Conversion in Python:

1.Implicit Type Conversion

2.Explicit Type Conversion

Implicit Type Conversion

You can convert from one type to another with the int(), float(), and complex() methods:

x = 1 # int

y = 2.8 # float

z = 1j # complex #convert from int to float:

a = float(x) #convert from float to int:

b = int(y) #convert from int to complex:

c = complex(x)

print(a)

print(b)

print(c)

print(type(a))

print(type(b))

print(type(c))

Output:
1.0

(1+0j)

Explicit Type Conversion

In Explicit Type Conversion in Python, the data type is manually changed by the user as
per their requirement. With explicit type conversion, there is a risk of data loss since we
are forcing an expression to be changed in some specific data type. Various forms of
explicit type conversion are explained below:

1. int(a, base): This function converts any data type to integer. ‘Base’ specifies the
base in which string is if the data type is a string. 2. float(): This function is used
to convert any data type to a floating point number.
# Python code to demonstrate Type conversion
# using int(), float()
# initializing string
s = "10010"
# printing string converting to int base 2
c = int(s,2)
print ("After converting to integer base 2 : ", end="")
print (c)
# printing string converting to float
e = float(s)
print ("After converting to float : ", end="")
print (e)

Output:

After converting to integer base 2 : 18

After converting to float : 10010.0

3. ord() : This function is used to convert a character to integer.

4. hex() : This function is to convert integer to hexadecimal string.

5. oct() : This function is to convert integer to octal string.

6. tuple() : This function is used to convert to a tuple.

7. set() : This function returns the type after converting to set.

8. list() : This function is used to convert any data type to a list type.

9. dict() : This function is used to convert a tuple of order (key,value) into a


dictionary.
10. str() :Used to convert integer into a string.

11. complex(real,imag) : This function converts real numbers to


complex(real,imag) number

12. chr(number): This function converts number to its corresponding ASCII


character.

type() function in Python

Type()method returns class type of the argument(object) passed as

parameter in Python .

Syntax of type() function

Syntax: type(object, bases, dict)

Parameters :

•object: Required. If only one parameter is specified, the

type() function returns the type of this object

•bases : tuple of classes from which the current class derives.

Later corresponds to the __bases__ attribute.

•Dict : a dictionary that holds the namespaces for the class.

Later corresponds to the __dict__ attribute.

Return: returns a new type class or essentially a metaclass.

a = ("Python", "BCA")

b = ["Python", "BCA"]

c = {"Python": 1, "OS":2, "CN":3}

d = "Hello World"

e = 24.87

f = 32.29

print(type(a))

print(type(b))

print(type(c))

print(type(d))
print(type(e))

print(type(f))

Output:

<class 'tuple'>

<class 'list'>

<class 'dict'>

<class 'str'>

<class 'float'>

<class 'float'>

Is Operator

Identity operators are used to compare the objects, not if they are equal, but if they are
actually the same object, with the same memory location:

Operator Description Example

is Returns True if both variables are the same object x is y

is not Returns True if both variables are not the same object x is not y

x = ["Python", "Computer"]

y = ["Python", "Computer"]

z = x print(x is z)

# returns True because z is the same object as x

print(x is y)

# returns False because x is not the same object as y, even if they have the same
content

print(x == y)

# to demonstrate the difference between "is" and "==": this comparison returns True
because x is equal to y

Dynamically and Strongly typed language:

Strong typed: means that variables do have a type and that the type matters when
performing operations on a variable.
Dynamically typed: means that the type of the variable is determined only during run
time. other hand, types in Python are determined during run-time as opposed to
compile-time and thus programmers are not required to declare variables before using
them in the code. Technically, a variable is created when it is assigned a value for the
first time in the code.

This means that a variable must first be assigned a value before it is referenced in the
code otherwise an error will be reported. And as mentioned earlier, the variable
assignment never comes with a type definition since the type is stored with objects and
not with variables/names.

Every time a variable is identified, it automatically gets replaced with the object in
memory it references.

Control Flow Statements in Python:

The if decision control flow statement

if statement is the most simple decision-making statement. It is used to decide whether


a certain statement or block of statements will be executed or not i.e., if a certain
condition is true then a block of statement is executed otherwise not.

Syntax:

if condition:

# Statements to execute if

# condition is true

a = 44

b = 300

if b > a:

print("b is greater than a")

Output: b is greater than a

if-else decision control flow statement

The if statement alone tells us that if a condition is true it will execute a block of
statements and if the condition is false it won’t. But what if we want to do something
else if the condition is false. Here comes the else statement. We can use the else
statement with if statement to execute a block of code when the condition is false.
Syntax:

if (condition):

# Executes this block if

# condition is true

else:

# Executes this block

# condition is false

a = 20

b = 13

if b > a:

print("b is greater than a")

else:

print("a is greater than b")

Output:

a and b are equal

nested-if decision control flow statement

A nested if is an if statement that is the target of another if statement. Nested if


statements mean an if statement inside another if statement. Yes, Python allows us to
nest if statements within if statements. i.e, we can place an if statement inside another
if statement.

Syntax:

if (condition1):

# Executes when condition1 is true

if (condition2):

# Executes when condition2 is true

# if Block is end here

# if Block is end here

x = 41

if x > 10:
print("Above ten,")

if x > 20:

print("and also above 20!")

else:

print("but not above 20.")

Output:

Above ten,

and also above 20!

The Whlie Loop:

Python While Loop is used to execute a block of statements repeatedly until a given
condition is satisfied. And when the condition becomes false, the line immediately after
the loop in the program is executed.

Syntax:

while expression:

statement(s)

Print i as long as i is less than 6:

i=1

while i < 6:

print(i)

i += 1 # this is same as i= i + 1

Output:

5
The for loop:

A for loop is used for iterating over a sequence (that is either a list, a tuple, a dictionary,
a set, or a string). This is less like the for keyword in other programming languages, and
works more like an iterator method as found in other object-orientated programming
languages.

With the for loop we can execute a set of statements, once for each item in a list, tuple,
set etc.

subjects = ["Python","Computer Networks","Operating Systems"]

for x in subjects:

print(x)

Output:

Python

Computer Networks

Operating Systems

Break statement and continue statement in Python

Break statement

The break statement is used to terminate the loop or statement in which it is present.
After that, the control will pass to the statements that are present after the break
statement, if available. If the break statement is present in the nested loop, then it
terminates only those loops which contains break statement.

Syntax:

break

Example:

count = 0

while count <= 100:

print(count)

count = count + 1

if count == 3:

break

Output:
0

In the above example loop, we want to print the values between 0 and 100, but there is a
condition here that the loop will terminate when the variable count becomes equal to 3.

continue statement:

The continue statement causes the loop to skip its current execution at some point and
move on to the next iteration. Instead of terminating the loop like a break statement, it
moves on to the subsequent execution.

for i in range(0,5)

if i == 3:

continue

print(i)

Output:

In the above example loop, we want to print the values between 0 and 5, but there is a
condition that the loop execution skips when the variable count becomes equal to 3.

FUNCTION

A function is a block of code which only runs when it is called. You can pass data,
known as parameters, into a function. A function can return data as a result.

Creating a Function

In Python a function is defined using the def keyword:

Example

def my_function():

print("Hello from a function")

Calling a Function
To call a function, use the function name followed by parenthesis:

Example

def my_function():

print("Hello from a function")

my_function()

Built in functions:

Python has a set of built in functions python has a set of built-in functions.

Defining a Function

You can define functions to provide the required functionality. Here are simple rules to
define a function in Python.

• Function blocks begin with the keyword def followed by the function name and
parentheses ( ( ) ).

• Any input parameters or arguments should be placed within these parentheses.

• You can also define parameters inside these parentheses. The first statement of a
function can be an optional statement - the documentation string of the function or
docstring.

• The code block within every function starts with a colon (:) and is indented.
Downloaded by Impana ([email protected]) lOMoARcPSD|55897885
• The statement return [expression] exits a function, optionally passing back an
expression to the caller. A return statement with no arguments is the same as return
None.

Syntax

def functionname( parameters ):

"function_docstring"

function_suite

return [expression]

By default, parameters have a positional behaviour and you need to inform them in the
same order that they were defined.

Example

The following function takes a string as input parameter and prints it on standard
screen.

def printme( str ):

"This prints a passed string into this function"

print str

return

Calling a Function

Defining a function only gives it a name, specifies the parameters that are to be
included in the function and structures the blocks of code.

Once the basic structure of a function is finalized, you can execute it by calling it from
another function or directly from the Python prompt.

Following is the example to call printme() function –

# Function definition is here

def printme( str ):

"This prints a passed string into this function"

print str

return

# Now you can call printme function


printme("I'm first call to user defined function!")

printme("Again second call to the same function")

When the above code is executed, it produces the following result –

I'm first call to user defined function!

Again second call to the same function

The return Statement

The statement return [expression] exits a function, optionally passing back an


expression to the caller. A return statement with no arguments is the same as return
None.

All the above examples are not returning any value. You can return a value from a
function as follows –

# Function definition is here

def sum( arg1, arg2 ):

# Add both the parameters and return them.

total = arg1 + arg2

print "Inside the function : ", total

return total

# Now you can call sum function

total = sum( 10, 20 )

print "Outside the function : ", total

When the above code is executed, it produces the following result –

Inside the function : 30

Outside the function : 30

Void function in python:

In Python, it is possible to compose a function without a return statement. Functions


like this are called void, and they return None, Python's special object for "nothing".
Here's an example of a void function:
def void_function(who):

print 'Hello,', who + '!'

print 'What a lovely day.'

void_function('Akbar')

Hello, Akbar! What a lovely day.

Void function and returning type function:

>>> def get_ing(wd):

return wd + 'ing' #returning type function

>>> def print_ing(wd):

print wd + 'ing' #void type function

>>> get_ing('interest')

'interesting' #output for return

>>> print_ing('interest')

interesting #output for void

Scope of Variables

All variables in a program may not be accessible at all locations in that program. This
depends on where you have declared a variable.

The scope of a variable determines the portion of the program where you can access a
particular identifier. There are two basic scopes of variables in Python

• Global Variable

• Local Variable

Global vs. Local variables

Variables that are defined inside a function body have a local scope, and those defined
outside have a global scope.

This means that local variables can be accessed only inside the function in which they
are declared, whereas global variables can be accessed throughout the program body
by all functions. When you call a function, the variables declared inside it are brought
into scope. Following is a simple example −

total = 0; # This is global variable.

# Function definition is here


def sum( arg1, arg2 ):

# Add both the parameters and return them."

total = arg1 + arg2; # Here total is local variable.

print "Inside the function local total : ", total

return total;

# Now you can call sum function

sum( 10, 20 );

print "Outside the function global total : ", total

When the above code is executed, it produces the following result −

Inside the function local total : 30

Outside the function global total : 0

Default Parameter/ Default Arguments

In Python, a default parameter is defined with a fallback value as a

default argument. Such parameters are optional during a function call.

If no argument is provided, the default value is used, and if an

argument is provided, it will overwrite the default value.

def greet(name, msg="How are you?”):

print(“Hello “,name + ‘, ‘ + msg)

greet(“BCA Student”)

greet(“BCA Student”, “How are you?”)

This code will print following output for both the calls

‘Hello BCA student, How are you?

You might also like