Python-Module1_3[1]
Python-Module1_3[1]
6.1 Reading numbers from Keyboard: we can read the input from console using input()
function. The syntax of the statement for a number is
Ex:
The above code results in error, because, Python reads numbers also as a string. inpit() produces only
string. Even if the user inputs an integer or float number, it is read as a strng. This problem can be
avoided by converting the string to an integer.
The problem of knowing the number if integer or floating point number and for the truncation
of floating point number, the eval() function is used.
Ex:
In this case, irrespective of what user types, int, float, string or complex, Python accepts the
number and determines the type of value entered by the user.
Python Programming for Data Science [BDS306D]
the argument can be integer, float, string or any other data type.
Ex:
Single or double quotes are used for printing more than one argument by separating them with
a comma. Numbers and variables can be printed directly.
Escape sequence should be used to print special characters.
Ex.
Ex for sep:
Ex for end:
In the above example the end flag ( attribute) is used to create a comma between operands an
and b.
% is an operator that replaces the placeholders. Python supports % character to format the
strings by replacing the placeholders with constants and variables, the syntax is
Values are the arguments supplied to the format string so that the output is as per the user’s
specification.
Ex:
The below lines of python code shows how an integer and string can be combined in the string
interpolation method.
7.3 String Formatting : This is the second way of formatting. Here there will be a format string
and arguments. The syntax is
The placeholders are in the form of curly braces, {}, and are called named replacements or
placeholders.
Python Programming for Data Science [BDS306D]
Here there is no placeholder, hence, the string is printed as it is. That is to say, the print()
function searches for placeholders, in this case. If none are available, it prints the strings
without any formatting.
Python allows the replacement fields and placeholders to put variables and concatenate strings
for printing.
Ex:
Alternately, the arguments for format can be index or positional order. The arguments are
passed as tuples and indexing starts from 0. The arguments would be substituted by removing
the placeholder, as shown in example below.
‘Name’ replaces the argument{0} and the word ‘is’ replaces the argument{1} wherever that
numbered placeholders are present. The arguments can be out of order or can be repeated,
arguments are swapped in the above example.
As shown below, the arguments occur multiple times.
Python Programming for Data Science [BDS306D]
The format can provide field width and precision. It can be specified as :n, where ‘n’ is the
number of characters in the field. If the data is having less than the character width, the extra
spaces are added to the right.