Featured

    Featured Posts

Python Tutorial 7:Conditional Statement In Python


Conditional Statement In Python

 §  If for some reason you want to interrupt this flow and execute certain statements, only, if certain condition is met, then we use conditional statements.

 §  Conditional expressions, involving keywords such as if, elif, and else, provide Python programs with the ability to perform different actions depending on a Boolean condition: True or False.



 §  When you want to justify one condition while the other condition is not true, then you use "if statement".

   if statement
 §  This is the simplest decision-making statement in Python. It is used to decide if a particular block of code needs to be executed or not. Whenever the given condition is True, then the block of code inside it gets executed, else it does not. 

The syntax for if statement:

if condition:
    body
§  The if statements check the condition. If it evaluates to True, it executes the body of the if statement. If it evaluates to False, it skips the body.

 if else statement

 §  The statements written within the else block get executed whenever the if condition is False. You can imagine the flow of execution this way,
Syntax:
if condition:
      body
else:
    body

Example

if True:

    print "It is true!"

else:

    print "This won't get printed.."

# Output: It is true!

if False:

    print "This won't get printed.."

else:

    print "It is false!"

# Output: It is false!


In Python you can define a series of conditionals using if for the first one, elif for the rest, up until the final (optional) else for anything not caught by the other conditionals.



Syntax:

if expression-1

 Statement-1



elif expression-2

 Statement-2

elif expression-3

 Statement-3




v Write a python program to enter number from 1 to 9 and print in words. If user enter number apart from 1 to 9 then it will print 'Number is allowed only between 0-9

n=int(input('enter number'))

if n==1:

    print("One")

elif n==2:

    print("Two")

elif n==3:

    print("Three")

elif n==4:

    print("Four")

elif n==5:

    print("Five")

elif n==6:

    print("Six")

elif n==7:

    print("Seven")

elif n==8:

    print("Eight")

elif n==9:

    print("Nine")

else:

    print('Number is allowed only between 0-9')

Boolean Logic Expressions

 §  Boolean logic expressions, in addition to evaluating to True or False, return the value that was interpreted as True or False. It is Pythonic way to represent logic that might otherwise require an if-else test.


And operator

 §  The and operator evaluates all expressions and returns the last expression if all expressions evaluate to True. Otherwise it returns the first value that evaluates to False:

print(10 and 20)      #output will be 20

print(10 and 0)        #output will be 0

print(0 and 10)        #output will be 0

print(10 and 20 and 30) #output will be 30

print(10 and "Python")  #output will be python

print(0 and "python")   #output will be 0

print("python" and 10)  #output will be 10

print("" and "python")  #output will be “ ”

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

Or operator

 §  The or operator evaluates the expressions left to right and returns the first value that evaluates to True or the last value (if none are True).      

print(10 or 20)#output will be 10

print(10 or 0)#output will be 10

print(0 or 10)#output will be 10

print(10 or 20 or 30)#output will be 10

print(10 or "Python")#output will be 10

print(0 or "python")#output will be python

print("python" or 10)#output will be python

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

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

print(None or 1)#output will be 1

print(0 or [])#output will be []



Testing for multiple conditions

 §  A common mistake when checking for multiple conditions is to apply the logic incorrectly.

 §  trying to check if two variables are each greater than 2.

 §  If you write the statement in such way

if (a) and (b > 2)

 §  this gives an unexpected result because bool(a) evaluates as True when a is not zero.
    
a=int(input('enter first number'))
b=int(input('enter first number'))
if a and b>2:
    print("Yes")
else:
    print("No")


 § Each variable needs to be compared separately.

a=int(input('enter first number'))

b=int(input('enter first number'))

if a>2 and b>2:

    print("Yes")

else:

    print("No")

 §  Another, similar, mistake is made when checking if a variable is one of multiple values. The statement in this example is evaluated as - if (a == 3) or (4) or (6). This produces an unexpected result because bool (4) and bool(6) each evaluate to True

a=1

if a==3 or 4 or 5 or 6:

    print('Yes')

else:

    print('No')



#output will be Yes

 §  Again each comparison must be made separately

a=1

if a==3 or a==4 or a==5 or a==6:

    print('Yes')

else:

    print('No')

#output will be No


 §  Using the in operator is the canonical way to write this.

n=int(input('enter number'))

if n in(10,20,30):

    print('Yes')

else:

    print('No')

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

www.CodeNirvana.in

Powered by Blogger.

About

Site Links

Popular Posts

Translate

Total Pageviews