0% found this document useful (0 votes)
30 views16 pages

Python Imp

Python is a dynamic, high-level and interpreted programming language. It supports object-oriented programming and is easy to learn yet powerful. Python can be used for web development, desktop applications, software development, data science, business applications and more. It has a large standard library and is cross-platform, free and open-source. Common Python data types include numbers, strings, lists, tuples and dictionaries.

Uploaded by

asnaph9
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
Download as pdf or txt
0% found this document useful (0 votes)
30 views16 pages

Python Imp

Python is a dynamic, high-level and interpreted programming language. It supports object-oriented programming and is easy to learn yet powerful. Python can be used for web development, desktop applications, software development, data science, business applications and more. It has a large standard library and is cross-platform, free and open-source. Common Python data types include numbers, strings, lists, tuples and dictionaries.

Uploaded by

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

Introduction To Python

What is Python :
Python is a general purpose, dynamic, high-level, and interpreted programming language. It supports Object
Oriented programming approach to develop applications. It is simple and easy to learn and provides lots of
high-level data structures.
Python is easy to learn yet powerful and versatile scripting language, which makes it attractive for Application
Development.
Python supports multiple programming pattern, including object-oriented, imperative, and functional or
procedural programming styles.
Python is not intended to work in a particular area, such as web programming. That is why it is known
as multipurpose programming language because it can be used with web, enterprise, 3D CAD, etc.
We don't need to use data types to declare variable because it is dynamically typed so we can write a=10 to
assign an integer value in an integer variable.
Python makes the development and debugging fast because there is no compilation step included in Python
development, and edit-test-debug cycle is very fast.

Features :-
1) Easy to Learn and Use
Python is easy to learn and use. It is developer-friendly and high level programming language.
2) Expressive Language
Python language is more expressive means that it is more understandable and readable.
3) Interpreted Language
Python is an interpreted language i.e. interpreter executes the code line by line at a time.This makes
debugging easy and thus suitable for beginners.
4) Cross-platform Language
Python can run equally on different platforms such as Windows, Linux, Unix and Macintosh etc. So, we
can say that Python is a portable language.
5) Free and Open Source
Python language is freely available at offical web address.The source-code is also available. Therefore it is
open source.
6) Object-Oriented Language
Python supports object oriented language and concepts of classes and objects come into existence.
7) Extensible
It implies that other languages such as C/C++ can be used to compile the code and thus it can be used further
in our python code.
8) Large Standard Library
Python has a large and broad library and prvides rich set of module and functions for rapid application
development.
9) GUI Programming Support
Graphical user interfaces can be developed using Python.
10) Integrated
It can be easily integrated with languages like C, C++, JAVA etc.

Python History and Versions :-


The implementation of Python was started in the December 1989 by Guido Van Rossum at CWI in
Netherland.
o ABC programming language is said to be the predecessor of Python language which was capable of
Exception Handling and interfacing with Amoeba Operating System.
o Python is influenced by following programming languages:
o ABC language.
o Modula-3
Python programming language is being updated regularly with new features and supports. There are lots of
updations in python versions, started from 1994(python 1.0) to current release(python 3.8).

Python Applications :-
Python is known for its general purpose nature that makes it applicable in almost each domain of software
development. Python as a whole can be used in any sphere of development.
Here, we are specifing applications areas where python can be applied.
1) Web Applications
We can use Python to develop web applications. It provides libraries to handle internet protocols such as
HTML and XML, JSON, Email processing, request, beautifulSoup, Feedparser etc.
2) Desktop GUI Applications
Python provides Tk GUI library to develop user interface in python based application.
3) Software Development
Python is helpful for software development process. It works as a support language and can be used for build
control and management, testing etc.
4) Scientific and Numeric
Python is popular and widely used in scientific and numeric computing. Some useful library and package are
SciPy, Pandas, IPython etc. SciPy is group of packages of engineering, science and mathematics.
5) Business Applications
Python is used to build Bussiness applications like ERP and e-commerce systems. Tryton is a high level
application platform.
6) Console Based Application
We can use Python to develop console based applications. For example: IPython.
7) Audio or Video based Applications
Python is awesome to perform multiple tasks and can be used to develop multimedia applications. Some of
real applications are: TimPlayer, cplay etc.
8) 3D CAD Applications
To create CAD application Fandango is a real application which provides full features of CAD.
9) Enterprise Applications
Python can be used to create applications which can be used within an Enterprise or an Organization. Some
real time applications are: OpenErp, Tryton, Picalo etc.

Python Comments :-
Comments in Python can be used to explain any program code. It can also be used to hide the code as well.
Comments are the most helpful stuff of any program. It enables us to understand the way, a program works.
In python, any statement written along with # symbol is known as a comment. The interpreter does not interpret
the comment.
Comment is not a part of the program, but it enhances the interactivity of the program and makes the program
readable.
Python supports two types of comments:
1) Single Line Comment:
In case user wants to specify a single line comment, then comment must start with #
2) Multi Line Comment:
Multi lined comment can be given inside triple quotes.

eg:
#single line comment
print "Hello Python"
'''''This is
multiline comment'''
Output:
Hello Python
PYTHON VARIABLES
Variable is a name which is used to refer memory location. Variable also known as identifier and used to hold value.
In Python, we don't need to specify the type of variable because Python is a type infer language and smart enough to get
variable type.
Variable names can be a group of both letters and digits, but they have to begin with a letter or an underscore.
Identifier Naming
Variables are the example of identifiers. An Identifier is used to identify the literals used in the program. The rules to
name an identifier are given below.
o The first character of the variable must be an alphabet or underscore ( _ ).
o All the characters except the first character may be an alphabet of lower-case(a-z), upper-case (A-Z), underscore
or digit (0-9).
o Identifier name must not contain any white-space, or special character (!, @, #, %, ^, &, *).
o Identifier name must not be similar to any keyword defined in the language.
o Identifier names are case sensitive for example my name, and MyName is not the same.
o Examples of valid identifiers : a123, _n, n_9, etc.
o Examples of invalid identifiers: 1a, n%4, n 9, etc.

Declaring Variable and Assigning Values

Python does not bound us to declare variable before using in the application. It allows us to create variable at required
time.

We don't need to declare explicitly variable in Python. When we assign any value to the variable that variable is declared
automatically.

The equal (=) operator is used to assign value to a variable.

Multiple Assignment

Python allows us to assign a value to multiple variables in a single statement which is also known as multiple
assignment.We can apply multiple assignments in two ways either by assigning a single value to multiple variables or
assigning multiple values to multiple variables.

1. Assigning single value to multiple variables

Eg:

x=y=z=50 Output: >>>


print x 50
print y 50
print z 50
>>>

2. Assigning multiple values to multiple variables:


Eg: output>>>
a,b,c=5,10,15 5
print a 10
print b 15
print c >>>

PYTHON DATA TYPES


Variables can hold values of different data types. Python is a dynamically typed language hence we need not define the
type of the variable while declaring it. The interpreter implicitly binds the value with its type.

Python enables us to check the type of the variable used in the program. Python provides us the type() function which
returns the type of the variable passed.

Standard data types :

1. Numbers
2. String
3. List
4. Tuple
5. Dictionary

1) Numbers :
Number stores numeric values. Python creates Number objects when a number is assigned to a variable.
Python supports 4 types of numeric data.

1. int (signed integers like 10, 2, 29, etc.)


2. long (long integers used for a higher range of values like 908090800L, -0x1929292L, etc.)
3. float (float is used to store floating point numbers like 1.9, 9.902, 15.2, etc.)
4. complex (complex numbers like 2.14j, 2.0 + 2.3j, etc.)

Python allows us to use a lower-case L to be used with long integers. However, we must always use an upper-case L to
avoid confusion.

A complex number contains an ordered pair, i.e., x + iy where x and y denote the real and imaginary parts respectively).

2) String

The string can be defined as the sequence of characters represented in the quotation marks. In python, we can use single,
double, or triple quotes to define a string.

In the case of string handling, the operator + is used to concatenate two strings as the operation "hello"+"
python" returns "hello python".

The operator * is known as repetition operator as the operation "Python " *2 returns "Python Python ".

In the case of string handling, the operator + is used to concatenate two strings as the operation "hello"+"
python" returns "hello python".

The operator * is known as repetition operator as the operation "Python " *2 returns "Python Python ".

str1 = 'hello javatpoint' #string str1


str2 = ' how are you' #string str2 Output:
print (str1[0:2]) #printing first two character using slice operator he
print (str1[4]) #printing 4th character of the string o
print (str1*2) #printing the string twice hello javatpointhello javatpoint
print (str1 + str2) #printing the concatenation of str1 and str2 hello javatpoint how are you

3) List
Lists are similar to arrays in C. However; the list can contain data of different types. The items stored in the list are
separated with a comma (,) and enclosed within square brackets [].

We can use slice [:] operators to access the data of the list. The concatenation operator (+) and repetition operator (*)
works with the list in the same way as they were working with the strings.

l= [1, "hi", "python", 2] Output:

print (l[3:]); [2]


print (l[0:2]); [1, 'hi']
print (l); [1, 'hi', 'python', 2]
print (l + l); [1, 'hi', 'python', 2, 1, 'hi', 'python', 2]
print (l * 3); [1, 'hi', 'python', 2, 1, 'hi', 'python', 2, 1, 'hi', 'python', 2]

4) Tuple

A tuple is similar to the list in many ways. Like lists, tuples also contain the collection of the items of different data types.
The items of the tuple are separated with a comma (,) and enclosed in parentheses ().

A tuple is a read-only data structure as we can't modify the size and value of the items of a tuple.

t = ("hi", "python", 2) Output:


print (t[1:]); ('python', 2)
print (t[0:1]); ('hi',)
print (t); ('hi', 'python', 2)
print (t + t); ('hi', 'python', 2, 'hi', 'python', 2)
print (t * 3); ('hi', 'python', 2, 'hi', 'python', 2, 'hi', 'python', 2)
print (type(t)) <type 'tuple'> Traceback (most recent call last):
File "main.py", line 8, in <module>
t[2] = "hi"; t[2] = "hi";
TypeError: 'tuple' object does not support item assignment

5) Dictionary

Dictionary is an ordered set of a key-value pair of items. It is like an associative array or a hash table where each key
stores a specific value. Key can hold any primitive data type whereas value is an arbitrary Python object.

The items in the dictionary are separated with the comma and enclosed in the curly braces {}.

Consider the following example.

d = {1:'Jimmy', 2:'Alex', 3:'john', 4:'mike'}; Output:


print("1st name is "+d[1]); 1st name is Jimmy
print("2nd name is "+ d[4]); 2nd name is mike
print (d); {1: 'Jimmy', 2: 'Alex', 3: 'john', 4: 'mike'}
print (d.keys()); [1, 2, 3, 4]
print (d.values()); ['Jimmy', 'Alex', 'john', 'mike']
PYTHON OPERATORS

The operator can be defined as a symbol which is responsible for a particular operation between two operands. Operators are
the pillars of a program on which the logic is built in a particular programming language. Python provides a variety of
operators described as follows.
o Arithmetic operators
o Comparison operators
o Assignment Operators
o Logical Operators
o Bitwise Operators
o Membership Operators
o Identity Operators

Arithmetic operators

Operator Description

+ (Addition) It is used to add two operands. For example, if a = 20, b = 10 => a+b = 30

- (Subtraction) It is used to subtract the second operand from the first operand. If the first operand is less than the
second operand, the value result negative. For example, if a = 20, b = 10 => a - b = 10

/ (divide) It returns the quotient after dividing the first operand by the second operand. For example, if a = 20, b
= 10 => a/b = 2

* It is used to multiply one operand with the other. For example, if a = 20, b = 10 => a * b = 200
(Multiplication)

% (reminder) It returns the reminder after dividing the first operand by the second operand. For example, if a = 20,
b = 10 => a%b = 0

** (Exponent) It is an exponent operator represented as it calculates the first operand power to second operand.

// (Floor It gives the floor value of the quotient produced by dividing the two operands.
division)

Comparison operator

Comparison operators are used to comparing the value of the two operands and returns boolean true or false accordingly.
The comparison operators are described in the following table.

Operator Description

== If the value of two operands is equal, then the condition becomes true.

!= If the value of two operands is not equal then the condition becomes true.
<= If the first operand is less than or equal to the second operand, then the condition becomes true.

>= If the first operand is greater than or equal to the second operand, then the condition becomes true.

> If the first operand is greater than the second operand, then the condition becomes true.

< If the first operand is less than the second operand, then the condition becomes true.

Python assignment operators

The assignment operators are used to assign the value of the right expression to the left operand. The assignment operators
are described in the following table.

Operator Description

= It assigns the the value of the right expression to the left operand.

+= It increases the value of the left operand by the value of the right operand and assign the modified
value back to left operand. For example, if a = 10, b = 20 => a+ = b will be equal to a = a+ b and
therefore, a = 30.

-= It decreases the value of the left operand by the value of the right operand and assign the modified
value back to left operand. For example, if a = 20, b = 10 => a- = b will be equal to a = a- b and
therefore, a = 10.

*= It multiplies the value of the left operand by the value of the right operand and assign the modified
value back to left operand. For example, if a = 10, b = 20 => a* = b will be equal to a = a* b and
therefore, a = 200.

%= It divides the value of the left operand by the value of the right operand and assign the reminder back
to left operand. For example, if a = 20, b = 10 => a % = b will be equal to a = a % b and therefore, a =
0.

**= a**=b will be equal to a=a**b, for example, if a = 4, b =2, a**=b will assign 4**2 = 16 to a.

//= A//=b will be equal to a = a// b, for example, if a = 4, b = 3, a//=b will assign 4//3 = 1 to a.

Bitwise operator

The bitwise operators perform bit by bit operation on the values of the two operands.

For example,

if a = 7; then, binary (a) = 0111


b = 6; binary (b) = 0011
hence, a & b = 0011 a ^ b = 0100
a | b = 0111 ~ a = 1000
Operator Description

& (binary If both the bits at the same place in two operands are 1, then 1 is copied to the result. Otherwise, 0
and) is copied.

| (binary or) The resulting bit will be 0 if both the bits are zero otherwise the resulting bit will be 1.

^ (binary xor) The resulting bit will be 1 if both the bits are different otherwise the resulting bit will be 0.

~ (negation) It calculates the negation of each bit of the operand, i.e., if the bit is 0, the resulting bit will be 1
and vice versa.

<< (left shift) The left operand value is moved left by the number of bits present in the right operand.

>> (right The left operand is moved right by the number of bits present in the right operand.
shift)

Logical Operators

The logical operators are used primarily in the expression evaluation to make a decision. Python supports the following
logical operators.

Operator Description

and If both the expression are true, then the condition will be true. If a and b are the two expressions, a →
true, b → true => a and b → true.

or If one of the expressions is true, then the condition will be true. If a and b are the two expressions, a →
true, b → false => a or b → true.

not If an expression a is true then not (a) will be false and vice versa.

Membership Operators

Python membership operators are used to check the membership of value inside a Python data structure. If the value is
present in the data structure, then the resulting value is true otherwise it returns false.

Operator Description

in It is evaluated to be true if the first operand is found in the second operand (list, tuple, or dictionary).

not in It is evaluated to be true if the first operand is not found in the second operand (list, tuple, or dictionary).

Identity Operators
Operator Description

is It is evaluated to be true if the reference present at both sides point to the same object.

is not It is evaluated to be true if the reference present at both side do not point to the same object.

Operator Precedence and Associativity

When different operators appear in the same expression, the normal rules of arithmetic apply. All Python operators have a
precedence and associativity:
• Precedence—when an expression contains two different kinds of operators, which should be applied first?
• Associativity—when an expression contains two operators with the same precedence, which should be applied first?

Operator Description

** The exponent operator is given priority over all the others used in the expression.

~+- The negation, unary plus and minus.

* / % // The multiplication, divide, modules, reminder, and floor division.

+- Binary plus and minus

>> << Left shift and right shift

& Binary and.

^| Binary xor and or

<= < > >= Comparison operators (less then, less then equal to, greater then, greater then equal to).

<> == != Equality operators.

= %= /= //= -= += Assignment operators


*= **=

is is not Identity operators

in not in Membership operators

As in standard arithmetic, in Python if the addition is to be performed first, parentheses can override the precedence rules.

Arity Operatos Associativity


Unary +, -
Binary *, /, % Left
Binary +, - Left
Binary = RightArity

The unary operators have a higher precedence than the binary operators, and the unary operators are
right associative. w = x = y = z
should be read right to left. First y gets the value of z, then y gets z’s value as well
Python Keywords

Python Keywords are special reserved words which convey a special meaning to the compiler/interpreter. Each keyword
have a special meaning and a specific operation. These keywords can't be used as variable. Following is the List of Python
Keywords.

True False None and as

asset def class continue break

else finally elif del except

global for if from import

raise try or return pass

nonlocal in not is lambda

Python Literals

Literals can be defined as a data that is given in a variable or constant.

Python support the following literals:

I. String literals:
tring literals can be formed by enclosing a text in the quotes. We can use both single as well as double quotes for a String.

Eg: "Aman" , '12345'

Types of Strings:

There are two types of Strings supported in Python:

a).Single line String- Strings that are terminated within a single line are known as Single line Strings.

Eg: >>> text1='hello'

b).Multi line String- A piece of text that is spread along multiple lines is known as Multiple line String.

There are two ways to create Multiline Strings:

1). Adding black slash at the end of each line. 2).Using triple quotation marks:-
Eg: Eg:
1. >>> text1='hello\ >>> str2='''''welcome
user'
to
>>> text1 SSSIT'''
'hellouser' >>> print str2
>>> welcome

to
SSSIT
>>>
II.Numeric literals:

Numeric Literals are immutable. Numeric literals can belong to following four different numerical types.

Int(signed integers) Long(long integers) float(floating point) Complex(complex)

Numbers( can be both Integers of unlimited Real numbers with In the form of a+bj where a forms
positive and negative) size followed by both integer and the real part and b forms the
with no fractional lowercase or uppercase fractional part eg: - imaginary part of complex
part.eg: 100 L eg: 87032845L 26.2 number. eg: 3.14j

III. Boolean literals:


A Boolean literal can have any of the two values: True or False.

IV. Special literals.


Python contains one special literal i.e., None.
None is used to specify to that field that is not created. It is also used for end of lists in Python.
Eg:

>>> val1=10
>>> val2=None
>>> val1
10
>>> val2
>>> print val2
None
>>>
V. Literal Collections.
Collections such as tuples, lists and Dictionary are used in Python.
List:

o List contain items of different data types. Lists are mutable i.e., modifiable.
o The values stored in List are separated by commas(,) and enclosed within a square brackets([]). We can store different
type of data in a List.
o Value stored in a List can be retrieved using the slice operator([] and [:]).
o The plus sign (+) is the list concatenation and asterisk(*) is the repetition operator.

Eg:

>>> list=['aman',678,20.4,'saurav']
>>> list1=[456,'rahul']
>>> list
['aman', 678, 20.4, 'saurav']
>>> list[1:3]
[678, 20.4]
>>> list+list1
['aman', 678, 20.4, 'saurav', 456, 'rahul']
>>> list1*2
[456, 'rahul', 456, 'rahul']
>>>
Interpreter V/S compiler
An interpreter is like a compiler, in that it translates higher-level source code into machine language. It works differently,
however.A compiled program does not need to be recompiled to run, but an interpreted program must be interpreted each
time it is executed. In general,compiled programs execute more quickly than interpreted programs because the translation
activity occurs only once. Interpreted programs, on the other hand, can run as is on any platform with an appropriate
interpreter; they do not need to be recompiled to run on a different platform. Python, for example, is used mainly as an
interpreted language, but compilers for it are available. Interpreted languages are better suited for dynamic, explorative
development which many people feel is ideal for beginning programmers.

The Python interpreter performs following tasks to execute a Python program :-


Step 1 : The interpreter reads a python code or instruction. Then it verifies that the instruction is well formatted, i.e. it
checks the syntax of each line.If it encounters any error, it immediately halts the translation and shows an error message.
Step 2 : If there is no error, i.e. if the python instruction or code is well formatted then the interpreter translates it into its
equivalent form in intermediate language called “Byte code”.Thus, after successful execution of Python script or code, it is
completely translated into Byte code.
Step 3 : Byte code is sent to the Python Virtual Machine(PVM).Here again the byte code is executed on PVM.If an error
occurs during this execution then the execution is halted with an error message.

Python IDLE,Writing and executing Python Scripts


IDLE Editors. An editor allows the programmer to enter the program source code and save it to files.Most programming
editors increase programmer productivity by using colors to highlight language features. The syntax of a language refers to
the way pieces of the language are arranged to makewell-formed sentences. The editor understands the syntax of the Python
language and uses different colors to highlight the various components that comprise a program. Much of the work of program
development occurs in the editor.
You can see the cursor blinking right after >>>. This is where you will be writing your code. Also, the current running version
of Python is also mentioned at the top.In IDLE we write code line by line. One line will handle one thing. You type whatever
you want in that line and press enter to execute it. IDLE works more like a terminal or command prompt - You write one
line, press enter, it executes. We can also create python file which will contain the complete multiline program and can
execute that using IDLE as well. A python script has an extension .py.
When we open the IDLE, a session is created, which saves all the lines of code that you write and execute in that one window
as a single program.

print ("Hello, World!")

We can write and execute this code in IDLE, or you can save this code in a python code file, name it test.py(you can name
it anything, just keep the extension of the file as .py).
To run the test.py python script, open IDLE, go to the directory where you saved this file using the cd command, and then
type the following in command prompt or your terminal:
python test.py
Python Statement :-
Instructions written in the source code for execution are called statements. There are different types of statements
in the Python programming language like Assignment statement, Conditional statement, Looping statements etc.
These all help the user to get the required output. For example, n = 50 is an assignment statement.
Multi-Line Statements: Statements in Python can be extended to one or more lines using parentheses (), braces
{}, square brackets [], semi-colon (;), continuation character slash (\). When the programmer needs to do long
calculations and cannot fit his statements into one line, one can make use of these characters.
Declared using Continuation Character (\): Declared using parentheses () :
s=1+2+3+\ n = (1 * 2 * 3 + 7 + 8 + 9)
4+5+6+\
7+8+9
Declared using square brackets [] : Declared using braces {} :
footballer = ['MESSI', x = {1 + 2 + 3 + 4 + 5 + 6 +
'NEYMAR', 7 + 8 + 9}
'SUAREZ']
Declared using semicolons(;) :
flag = 2; ropes = 3; pole = 4
Python Expressions :-
A literal value like 34 and a variable like x are examples of a simple expressions. Values and variables can be
combined with operators to form more complex expressions. All expressions have a value. The process of
determining the expression’s value is called evaluation.Evaluating simple expressions is easy. The literal value 54
evaluates to 54. The value of a variable named x is the value stored in the memory location bound to x. The value
of a more complex expression is found by evaluating the smaller expressions that make it up and combining them
with operators to form potentially new values.

Expression Meaning
x+y x added to y, if x and y are numbers
x concatenated to y, if x and y are strings
x-y x take away y, if x and y are numbers
x*y x times y, if x and y are numbers
x concatenated with itself y times, if x is a string and y is an integer
y concatenated with itself x times, if y is a string and x is an integer
x/y x divided by y, if x and y are numbers
x // y Floor of x divided by y, if x and y are numbers
x%y Remainder of x divided by y, if x and y are numbers
x ** y x raised to y power, if x and y are numbers

Python Indentation :-
Most of the programming languages like C, C++, and Java use braces { } to define a block of code. Python,
however, uses indentation.A code block (body of a function, loop, etc.) starts with indentation and ends with the
first unindented line. The amount of indentation is up to you, but it must be consistent throughout that block.
Generally, four whitespaces are used for indentation and are preferred over tabs. Here is an example.
for i in range(1,11):
print(i)
if i == 5:
break
The enforcement of indentation in Python makes the code look neat and clean. This results in Python programs
that look similar and consistent.Indentation can be ignored in line continuation, but it's always a good idea to
indent. It makes the code more readable.
For example:
A) if True:
print('Hello')
a=5
B) if True: print('Hello'); a = 5
both are valid and do the same thing, but the former style is clearer.
User Input Function
The print function enables a Python program to display textual information to the user. Programs may use
the input function to obtain information from the user. The simplest use of the input function assigns a
string to a variable:
x = input()
The parentheses are empty because, the input function does not require any information to do its job.
print('Please enter some text:')
x = input()
print('Text entered:', x)
print('Type:', type(x))

Eg:
num1 = int(input('Please enter an integer value: '))
num2 = int(input('Please enter another integer value: '))
print(num1, '+', num2, '=', num1 + num2)

int(input('Please enter an integer value: '))


uses a technique known as functional composition. The result of the input function is passed directly to
the int function instead of using the intermediate variables. We frequently will use functional composition to make
our program code simpler.
Eval() Function
The eval() function evaluates the specified expression, if the expression is a legal Python statement, it will be
executed. The python eval() function parses the expression passed to it and runs python expression(code) within
the program.
eval(expression, globals=None, locals=None)
Where
 Expression − It is the python expression passed onto the method.
 globals − A dictionary of available global methods and variables.
 locals − A dictionary of available local methods and variables.
In the below example we allow the user to cerate an expression and run a python program to evaluate that
expression. So it helps in create dynamic code.
Eg: output ;-
x1 = eval(input('Entry x1? ')) 'Entry x1? : 4
print('x1 =', x1, ' type:', type(x1)) x1 = 4 type: <class ’int’>
x2 = eval(input('Entry x2? ')) Entry x2? 4.0
print('x2 =', x2, ' type:', type(x2)) x2 = 4.0 type: <class ’float’>

Type() Function
type() method returns class type of the argument(object) passed as parameter. type() function is mostly used for
debugging purposes.
Two different types of arguments can be passed to type() function, single and three argument. If single
argument type(obj) is passed, it returns the type of given object.
All expressions in Python have a type. The type of an expression indicates the kind of expression it is. An
expression’s type is sometimes denoted as its class.
Synax :- type(object, bases, dict)
Parameter Description

object Required. If only one parameter is specified, the type() function returns the type of this
object

bases Optional. Specifies the base classes

dict Optional. Specifies the namespace with the definition for the class
>>> x = 5.62
>>> x >>> type(x)
5.62 <class ’float’>
print() Function
The print() function prints the specified message to the screen, or other standard output device.
The message can be a string, or any other object, the object will be converted into a string before written to the
screen.
Syntax : print(object(s), sep=separator, end=end, file=file, flush=flush)
Parameter Description

object(s) Any object, and as many as you like. Will be converted to string before printed

sep='separator' Optional. Specify how to separate the objects, if there is more than one. Default is ' '

end='end' Optional. Specify what to print at the end. Default is '\n' (line feed)

file Optional. An object with a write method. Default is sys.stdout

flush Optional. A Boolean, specifying if the output is flushed (True) or buffered (False). Default
is False
Eg :- OUTPUT:-
print("Hello", "how are you?") Hello how are you?
x = ("apple", "banana", "cherry")
print(x) ('apple', 'banana', 'cherry')
print("Hello", "how are you?", sep="---") Hello---how are you?

Eg:-

print('A', end='')
print('B', end='') ABC
print('C', end='')
print()
print('X') X
print('Y') Y
print('Z') Z
print()-essentially moves the cursor down to next line.Sometimes it is convenient to divide the output of a single
line of printed text over several Python statements.

**************************************************

You might also like