Basics of Python
programming:
Data Types
Input and Output Statements
• input() function for taking the user input
• It accepts all user input as string.
• The user may enter a number or a string but the input() function
treats them as strings only
• The input() takes exactly what is typed from the keyboard,
converts it into a string and assigns it to the variable on left-hand
side of the assignment operator (=).
• Entering data for the input function is terminated by pressing the
enter key.
• The syntax for input() is:
input ([Prompt])
Eg:
sname=input(“enter your name”)
To get more than one input
Type Conversion
• Converting from one data type to other is known as type conversion
• Two types of Conversion
• Implicit type conversion
when the interpreter understands such a need by itself and does
the type conversion automatically
• Explicit Type conversion
(forced) when the programmer specifies for the interpreter to convert
a data type to another [Link] general form of an explicit data type
conversion is:
(new_data_type) (expression)
Implicit Conversion
Implicit conversion, also known as coercion,
happens when data type conversion is done
automatically by Python and is not instructed by the
programmer
num1 = 10 #num1 is an integer
num2 = 20.0 #num2 is a float
sum1 = num1 + num2
#sum1 is sum of a float and an integer
print(sum1) print(type(sum1))
Explicit type conversion
int(x) - Converts x to an integer
float(x) - Converts x to a floating-point number
str(x) -Converts x to a string representation
chr(x) -Converts ASCII value of x to character
ord(x) - returns the character associated with the ASCII code x
Type Conversion
Try conversion from float to int
A=45.6
B=50.5
C=int(A+B)
Type conversion between numbers and strings in two ways
• str()
• +
N=100
S=str(N)
S1=“Welcome”+N # if N not converted then error will be
raised
Only String and String can be concatenated
Type Conversion
Try conversion from float to int
A=45.6
B=50.5
C=int(A)+int(B)+D
The variable D has not been defined so it will raise Name
Error
v='a'+1
print(v)
TypeError: can only concatenate str (not "int") to str
print(chr(97)) # ASCII to Character
print(ord('a')) # Character to ASCII
a='50'
b='20'
c=a+b
print(c)
Print in Python
print(object(s), sep=separator, end=end)
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)
print("Welcome","To",end=" ")
print("India")
Welcome To India