PYTHON
LECTURE 15
Today’s Agenda
• eval( ) Function , Command Line
Arguments and Various print( )
Options
• Using the eval( ) Function
• Using Command Line Arguments
• Using format specifiers in Python
• Using the function format( )
Using The Function eval( )
Python has a very interesting function called eval(
).
This function accepts any valid Python
expression and executes it
Using The Function eval( )
Syntax:
eval(expression)
The argument passed to eval() must follow below
mentioned rules:
It must be given in the form of string
It should be a valid Python code or expression
Examples
• Example: • Example:
x
x = eval(’2+3’)
= eval(‘2+3*6
print(x) ’)
print(x)
• Output:
5
• Output:
20
Examples
• Example: • Example:
x=eval('print(15)
eval(‘print(15)’)
')
print(x)
• Output: • Output:
15 15
None
Examples
• Example: • Example:
from math
x=eval('print()')
import sqrt
print(x) x
= eval(‘sqrt(4
)’)
• Output: print(x)
None • Output:
2.0
Using eval( ) For
Type Conversion
Another important use of eval( ) function is to perform type
conversion .
The eval( ) function interprets the argument inside
character string and coverts it automatically to it’s type.
Same Example
Example: Without eval( ):
x = eval(‘2.5’) x = ‘2.5’
print(x) print(x)
print(type(x)) print(type(x))
Output:
2.5
Output:
<class ‘str’>
2.5
<class ‘float’>
Using eval( ) With input( )
We can use eval( ) with input( ) function to
perform automatic type conversion of values.
In this way , we will not have to use type
conversion functions like int() , float( ) or bool ()
Example
Code:
age = eval(input("Enter your age "))
age=age+10
print("After 10 years , you will be ",age, "years
old")
Output:
Guess The Output
• Example:
a=eval(input("Type something:"))
print(a)
print(type(a))
Suppose user types 25
• Output:
Guess The Output
• Example:
a=eval(input("Type something:"))
print(a)
print(type(a))
• Suppose user types 3.6
• Output:
Guess The Output
• Example:
a=eval(input("Type something:"))
print(a)
print(type(a))
• Suppose user types [10,20,30]
• Output:
Guess The Output
• Example:
a=eval(input("Type something:"))
print(a)
print(type(a))
• Suppose user types Hello
• Output:
Guess The Output
• Example:
a=eval(input("Type something:"))
print(a)
print(type(a))
• Suppose user types “Hello”
• Output:
Command Line Arguments
Command Line Arguments are the values , we
can pass while executing our Python code from
command prompt
These are called
Syntax: commad line
python prog_name <values> arguments
For example:
python demo.py 10 20 30
heir main benefit is that they are another mechanism to
ovide input to our program
Where Are
Command Line Arguments Stored ?
Command Line Arguments are stored by Python
in a special predefined variable called argv
Following are important features of argv:
This variable itself is stored in a module called sys
So to use it , we must import sys module in our program
The variable argv is actually a list
The name of the program is passed as the first
argument which is stored at the 0th index in argv
Example
Code (suppose name of prog is
cmdarg.py):
from sys import argv
print(argv)
print(type(argv))
Suppose we run it as python cmdarg.py 10 20
30
Output:
Accessing Individual Values
argv is a List type object
Lists are index based
They always start from 0th index
So if we want to access individual elements of argv
then we can use the subscript operator passing it
the index number
Accessing Individual Values
Code:
from sys import argv
print(argv[0])
print(argv[1])
print(argv[2])
Suppose we run it as python cmdarg.py 10 20
Output:
Guess The Output
If we try to
Code: access argv
from sys import argv beyond it’s last
index then
print(argv[0]) Python will
print(argv[1]) throw
IndexError
print(argv[2]) exception
Execution: python cmdarg.py
Output:
cmdarg.py
IndexError: list index out of range
Obtaining Number
Of Arguments Passed
The built in function len( ) can be used to get the
number of arguments passed from command
prompt
Code:
from sys import argv
n=len(argv)
print("You have passed",n-1,"arguments")
Output:
Using Slicing Operator
A List in Python is also a sequence type like a
string
So , it also supports slicing i.e. we can use the
slicing operator [ : ] , to retrieve the
list values from any index.
For example , if we don’t want the program name
then we can use the slicing operator passing it the
index number 1 as start index
Example
Code (suppose name of prog is cmdarg.py):
from sys import argv
print(argv[1:])
Execution: python cmdarg.py 10 20 30
Output:
Guess The Output
Code (suppose name of prog is cmdarg.py):
from sys import argv
print(argv[1:])
Execution: python cmdarg.py
Output:
[]
Guess The Output
Code: addnos.py
from sys import argv
print(“First num is“,argv[1])
print(“Sec num is“,argv[2])
print(“Their sum is”,argv[1]+argv[2])
Execution: python addnos.py 15 20
By default ,
Output: Python treats all
the command line
First num is 15 arguments as
Sec num is 20 string values
Their sum is 1520
How To Solve This ?
To solve the previous problem , we will have to type
convert string values to int.
This can be done by using int( ) or eval( ) function
Example
Code:
from sys import argv
a=eval(argv[1])
b=eval(argv[2])
print("Nos are",a,"and",b)
print("Their sum is",a+b)
Guess The Output
Code:
from sys import argv
print(“Hello”,argv[1])
Execution: python cmdarg.py Sachin Kapoor
For Python Sachin
Output: and Kapoor are 2
separate
Hello Sachin arguments , so
argv[1] receives
Sachin and argv[2]
receives Kapoor
Guess The Output
If we want to pass Sachin Kapoor as a single
argument then we
must enclose it in double quotes
Code:
from sys import argv
print(“Hello”,argv[1])
Execution: python cmdarg.py “Sachin Kapoor”
Output:
Hello Sachin Kapoor
Guess The Output
Code:
from sys import argv
print(“Hello”,argv[1])
Execution: python cmdarg.py ‘Sachin Kapoor’
On command
Output: prompt only
Hello ‘Sachin double quoted
strings are
treated as
single value.
Using Format Specifiers
With print()
Just like C language Python also allows us to use
format specifiers with variables.
The format specifiers supported by Python are:
%d: Used for int values
%i: Used for int values
%f: Used for float values
%s: Used for string value
%c: Used for single char
Using Format Specifiers
With print()
Syntax:
print(“format specifier” %(variable list))
Example:
a=10
print(“value of a is %d “ %(a))
Output:
If a single
value of a is 10 variable is there
then parentesis
can be dropped
Using Format Specifiers
With print()
Example:
a=10
msg=“Welcome”
c=1.5
print(“values are %d , %s,%f“ %(a,msg,c))
Output: Number of
Values are 10, Welcome, 1.500000 format
specifiers
must exactly
match with
the number of
vlaues in the
parenthesis
Key Points About Format Specifiers
The number of format specifiers and number of
variables must always match
We should use the specified format specifier to
display a particular value.
For example we cannot use %d for strings
However we can use %s with non string values
also , like boolean
Examples
a=10
print(“%s” %a)
Output:
10
a=10
print(“%f” %a)
Output:
10.000000
Examples
a=10.6 a=10.6
print(“%f” %a) print(“%d” %a)
Output: Output:
10
10.600000
a=10.6 a=10.6
print(“%.2f” %a) print(“%s” %a)
Output:
Output:
10.6
10.60
Examples
a=True a=True
print(“%s” %a) print(“%f” %a)
Output: Output:
1.000000
True
a=True
print(“%d” %a)
Output:
1
Examples
a=“Bhopal” a=“Bhopal”
print(“%s” %a) print(“%f” %a)
Output: Output:
TypeError
Bhopal
a=“Bhopal”
print(“%d” %a)
Output:
TypeError: number required , not str
Examples
a=“Bhopal” x=65
print(“%c” %a[0]) print(“%c” %x)
Output: Output:
A
B
x=65.0
a=“Bhopal”
print(“%c” %x)
print(“%c” %a[0:2]) Output:
Output:
TypeError:
TypeError: %c requires int or char
%c requires int or char
Using The Function format()
Python 3 introduced a new way to do string
formatting by providing a method called format( )
in string object
This “new style” string formatting gets rid of the %
operator and makes the syntax for string
formatting more regular.
Using The Method format()
Syntax:
print(“string with { }”.format(values))
Example
name=“Sachin”
age=36
print(“My name is {0} and my age is
{1}”.format(name,age))
Output:
My name is Sachin and my age is 36
Examples
name=“Sachin”
age=36
print(“My name is {1} and my age is
{0}”.format(age,name))
Output:
My name is Sachin and my age is 36