Featured

    Featured Posts

Python Tutorial 5:Type Conversion In Python


Type Conversion:



 §  The process of converting the value of one data type (integer, string, float, etc.) to  
       another data type is called type conversion. Python has two types of type conversion.
   1.     Implicit Type Conversion
   2.     Explicit Type Conversion 
Explicit Type Conversion:
 §  In Explicit Type Conversion, users convert the data type of an object to required data type. We use the predefined functions like int()float()str(), etc to perform explicit type conversion.

·        int()
·        float()
·        complex()
·        bool()
·        str()
int()
 §  By using this function, we can convert values from other types to int

print(int(123.456)) #output will be 123
print(int(True))    #output will be 1
print(int(False))   #output will be 0
print(int(“10”))    #output will be 10
print(int(10+20j))
print(int(10+20j))
TypeError: can't convert complex to int

Note:-
§  when we are trying to convert string value into int type compulsory string value  
   should be int type with base 10.
print(int("10.2"))
print(int("10.2"))
ValueError: invalid literal for int() with base 10: '10.2'

print(int("0B111"))
print(int("0B111"))
ValueError: invalid literal for int () with base 10: '0B111'

Note:
§  We can convert from any type to int except complex type.
float(): 
 §  By using this function, we can convert values from other types to float.

print(float(10))  #output will be 10.0
print(float(True)) #output will be 1.0
print(float(False)) #output will be 0.0

§  Whenever we are trying to convert str type to float type compulsory str should 
  be either integral or floating-point literal and should be specified only in base-10.
print(float("10")) #output will be 10.0 
print(float("10.1")) #output will be 10.1
print(float("ten"))
print(float("ten"))
ValueError: could not convert string to float: 'ten'

print( float(0B111))  #output will be 7.0
print( float("0B111"))
print( float("0B111"))
ValueError: could not convert string to float: '0B111'
Note:-
   |- We can convert any type to float except to complex type.

complex():
   |- Other Types to complx type.

Form-1: complex(x)==>x+0j
print(complex(10))   #output will be (10+0j)
print(complex(10.5)) #output will be (10.5+0j)
print(complex(True)) #output will be (1+0j)
print(complex(False)) #output will be (0j)
print(complex("10"))  #output will be (10+0j)
print(complex("10.5")) #output will be (10.5+0j)
print(complex("ten"))
print(complex("ten"))
ValueError: complex() arg is a malformed string

Form-2: complex(x,y)==>x+yj
print(complex(10,20))   #output will be (10+20j)
print(complex(True,False))  #output will be (1+0j)
print(complex(10,20.5))  #output will be (10+20.5j)
print(complex("10","12"))
print(complex("10","12"))
TypeError: complex() can't take second arg if first is a string

bool():

 §  By using this function, we can convert values from other types to bool.
|- For int arguments
             |- For non-zero value it returns True.
             |- For zero value it returns False.

print(bool(0))  #output will be False
print(bool(1))  #output will be True
print(bool("10"))  #output will be True

|- For float arguments
              |- If before decimal and after decimal is zero then it returns False.
              |- If before decimal or after decimal is non-zero value then it returns True.

print(bool(0.0))  #output will be False 
print( bool(0.1)) #output will be True
print(bool(0.01)) #output will be True
print(bool(2.3)) #output will be True
|- For complex arguments
                |- If both real and img part is zero then it will return False.
                |- If at least one part is non-zero then it will return True.

print(bool(0+0j)) #output will be False
print( bool(0+1j)) #output will be True
print(bool(0+2.5j)) #output will be True
print( bool(2.5+0j)) #output will be True

|- For str arguments
            |- arg is empty string==>"==>False
            |- arg is non-empty==> True

print(bool(''))  #output will be False
print(bool('python')) #output will be True
print( bool(' '))  #output will be True

str():-
|- is Used To convert any types to str types.
print(str(100))    #output will be 100
print(str(2.6))    #output will be 2.6
print(str(True))   #output will be True
print(str(False))   #output will be False
print(str(10+20j))  #output will be 10+20j

ord(character):-
§  By using ord() method we can converts any character to a numeric value. This method takes only one length string.
# converting character  to integer 
c = ord('a'
print ("After converting character to integer : ",end=""
print (c)  
output:

After converting character to integer : 97

# converting character  to integer 
c = ord('abc'
print ("After converting character to integer : ",end=""
print (c) 
    c = ord('abc') 
TypeError: ord() expected a character, but string of length 3 found

chr(number):-
§  By using chr(number) method we can convert number to its corresponding ASCII  
  character. 
# converting integer to character
c = chr(65)
print ("After converting integer to character : ",end="")
print (c)
# converting integer to character
c = chr(100)
print ("After converting integer to character : ",end="")
print (c)
# converting integer to character
c = chr(55)
print ("After converting integer to character : ",end="")
print (c)
output:
After converting integer to character : A
After converting integer to character : d
After converting integer to character : 7

Python Tutorial 4:print() Function In Python




Python 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.

First Form Of print() Method 
  § We can use print() without any arguments.

What is the purpose of print() without any arguments
  §  To insert a new line separator

print()
 §  This will produce an invisible newline character, which in turn will cause a blank line to appear on your screen.

print("java")
print("python")

#output will be
 java 
 python

Ø If we want insert new line character between both statement then we should go print () without any arguments

print("java")
print()
print("python")
#output will be 
java

python
  
Second Form: - print(string) 
|- print(string) method with string arguments

print("java")
print("python")

#output will be
 java 
 python 

 §  If we are using print(string) method with string arguments then escape character is allowed to use.
          print("java\n python")
print("java\tpython")

#output will be
          java
 python
java   python

 §  whenever we are using * operator with string type then one argument should be string type and other should be int type.

print("python"*3)
#output will be pythonpythonpython

Print() method with multiple arguments

print(arg1,arg2,agr2,.....argn)

 §  whenever we want to display multiple argument value at a time using print() method then each argument seperated with comma operator.

 §  suppose if we want to display two arguments at a time then we are using print() in follwing ways.

print("java","python")
          #output will be java python

 §  print(arg1,arg2) then it will display first arguments value then space then second aruments value.

§  what is difference between two statements

print("java"+"python")                      #output will be javapython
print("java","python")                       #java python

print() with variable number of arguments

a,b,c=10,20,30
print(a,b,c) #output will be 10 20 30


§  This statement displays variable a, b, c value.
§  First display the value of a variable then space then value of b variable then space then value of c variable.

§  Here All three variable value are separated with space but suppose my requirement is that I want to display all three-variable separated with comma operator. How we can fulfill such type requirement.

Parameters inside the Print function i.e. Sep and End 


print(<variable-name or string,sep=<seperator-value>,end=<end-value>)
§  To fulfill such type requirement python provides one attribute sep.
using sep attribute we can fulfill all customize type requirement.

Sep Parameter in Python

 §  As the name suggests, sep is used for adding separators into the string provided.

 §When we print more value than one, then how should the value be separated from 
      each other.

 §  Using sep attribute in print() function we can specify customize separator between values.

 §  If we don’t specify any value to the “sep” parameter the by default it is considered to be a no-space.

§  Display three variable value and each value separated with comma
a,b,c=10,20,30
print(a,b,c,sep=",")
#output will be 10,20,30

§  display three variable value and each value separated with colon
a,b,c=10,20,30
print(a,b,c,sep=":")#output will be 10:20:30
§  Display date value and each value separated with slash(/)

#for formatting today's date using backslash
print('26','07','2020', sep='/')
#output will be 26/07/2020

§  Display Two value and each value separated with @
#formatting using @ symbol
print('Scott','Tiger',sep='@')
#output will be Scott@Tiger

v print () method with end attribute: -
§  When we are using more than one print statement, then what should be the separator between them.
§  By default, the print method ends with a newline. This means there is no need to explicitly specify the parameter end as '\n.
§  But if we want to customize then we can customize it by using end attribute in print() function.
§  The end parameter is used to append any string at the end of the output of the print statement in python.

print(object) can take any type argument.

l=[10,20,30,40,50]
t=(10,20,30,40,50)
s={10,20,30,40,50}
print(l)
print(t)
print(s)
output:
[10, 20, 30, 40, 50]
(10, 20, 30, 40, 50)
{40, 10, 50, 20, 30}
§  right now here All the lines are being printed in a separate line. but if we want to 
  print them all in one line then we have to use the end attribute in print() function.

l=[10,20,30,40,50]
t=(10,20,30,40,50)
s={10,20,30,40,50}
print(l,end=' ')
print(t,end=' ')
print(s,end=' ')
output:
[10, 20, 30, 40, 50] (10, 20, 30, 40, 50) {40, 10, 50, 20, 30}

# ends the output with '#' hash
print('Welcome')
print('To')
print('Gravity4Tech')
output:
Welcome
To
Gravity4Tech
§  right now, here All the lines are being printed in a separate line. but if we want to print them all in one end with # hash then we have to use the end attribute in print() function.
# ends the output with '#' hash
print('Welcome',end='#')
print('To',end='#')
print('Gravity4Tech')
output:
Welcome#To#Gravity4Tech


print() function with replacement operator.


{} => replacement operator

Python String format()

§  The string format() method formats the given string accordingly output in Python.

"formated string".format(val1,val2,val3...)

'var1= {}, var= {}, var3= {}’. format (val1, val2, val3)

§  This format () method first reads the value of the passed parameter and also changes them according to the given string.
§   In the given formatted string Curly Braces are exchanged with the pass value in the format method.
§  The first curly braces will be exchanged with the first value, the second curly braces will be exchanged with the second value, in the same way the rest will be.
§  Each curly brace has an index position. index position starts with zero.
§  The curly braces are just placeholders for the arguments to be placed.


In the above example, {0} is placeholder for 10 and {1} is placeholder for 20 and {2} is placeholder for 30.
Specifying the index position is also optional.


Python String format() with keywords argument.


 §  We've used the same example from above to show the difference between keyword and positional arguments.

 §  Here, instead of just the parameters, we've used a key-value for the parameters. Namely, name="scott" and age=50.

 §  Since, these parameters are referenced by their keys as {name} and {age}, they are known as keyword or named arguments.

 §  Internally, the placeholder {name} is replaced by the value of name - "scott". Since, it doesn't contain any other format codes, "Adam" is placed.

 §  For the argument age=50, the placeholder {age} is replaced by the value 50.

msg="Hello {name},your age is:{age} years".format(name='Scott',age=50)
print(msg)
output:
Hello Scott,your age is:50 years


Number Formatting Types
Type Meaning
d        Decimal integer
c        Corresponding Unicode character
b        Binary format
o        Octal format
x        Hexadecimal format (lower case)
X       Hexadecimal format (upper case)
n        Same as 'd'. Except it uses current locale setting for number separator
e        Exponential notation. (lowercase e)
E       Exponential notation (uppercase E)
f        Displays fixed point number (Default: 6)
F       Same as 'f'. Except displays 'inf' as 'INF' and 'nan' as 'NAN'
g        General format. Rounds number to p significant digits. (Default precision: 6)
G       Same as 'g'. Except switches to 'E' if the number is large.
%      Percentage. Multiples by 100 and puts % at the end.



Display  formatting for octal, binary and hexadecimal format.

# octal, binary and hexadecimal format
print("bin:{0:b},oct:{0:o},hex:{0:x}".format(15))

output:
bin:1111,oct:17,hex:f

Display  formatting for % Percentage. Multiples by 100 and puts % at the end..

#% percentage
print("Your score is {:%}".format(3))

output:
Your score is 300.000000%

Display  formatting  of class members using format()

#define Student Class
class Student:
    def __init__(self):
        self.rollno=101
        self.name='john'

# format rollno
print("{s.name}'s Rollno is: {s.rollno}".format(s=Student()))

output:
john's Rollno is: 101

 §  Here, Student object is passed as a keyword argument s.

 §  Inside the template string,Student's name and rollno are accessed using .name and .rollno respectively.

Display  formatting  of dictionary members using format()

# define Student dictionary
student = {'rollno': 101, 'name': 'John','course':'B.tech'}

# format student
print("{s[name]}'s rollno is: {s[rollno]} and course is:{s[course]}".format(s=student))

output:
John's rollno is: 101 and course is:B.tech

 §  Similar to class, student dictionary is passed as a keyword argument s.

 §  Inside the template string, student's name and rollno and course are accessed using [name] and [rollno] [course] respectively.

www.CodeNirvana.in

Powered by Blogger.

About

Site Links

Popular Posts

Translate

Total Pageviews