sampleqa.in tutorials, Python Programming  tutorial

Python Variables


Naming your Variables

  • Always begins with Alphabets/letter or Underscore Character
  • Never user special characters in variables name like, &,%,#,@,$ etc.,
  • Never use Python keywords as a Variable Name
  • Python variables are case-sensitive, so _v=10,_V=11, both are different variables
  • use Camel case
  • Use snake case
Note: Variable must be defined/initialized before its use. Otherwise NameError exception will be thrown

Statement is an instruction to the Interpreter

Expressions are combination of variables,values,statements,and operators that forces the interpreter to evaluate it.

Python Operators

  • Arithmetic Operators
  • Logical Operators
  • Bit-wise Operators
  • Relational Operators
  • Augmented Assignment Operators

Arithmetic Operators

OperatorDescription
    +    Addition Operator
    -   Subtraction Operator
    /   Division Operator
    //   Integer divsion Operator
    %   Remainder Operator
    **   Exponentiation Operator
      Python 3.10.5 (main, Jun  9 2022, 00:00:00) [GCC 11.3.1 20220421 (Red Hat 11.3.1-2)] on linux
	Type "help", "copyright", "credits" or "license" for more information.
>>> i=2;j=3
>>> 2+3
5
>>> i+j
5
>>> i-j
-1
>>> i*j
6
>>> i/j
0.6666666666666666
>>> i//j
0
>>> i%j
2
>>> i**j
8
>>> 

      

Logical Operators Operators

OperatorDescription
    and    
    or    
    not    
      
      

Bit-wise Operators

OperatorDescription
    |    
    &    
    ^    
    >>    
    <<    

Relational Operators

OperatorDescription
    <    
    >    
    >=    
    <=    
    ==    
    !=    
      
      

Augmented Assignment Operators

OperatorDescription
   op1*=op2    op1 operand 1,op2 operand 2
op1*=op2, op1 is multiplied by op2, result is assigned to op1. x*=5 <==> x=x*5
   op1/=op2    op1/=op2, op1 is divided by op2, result(Quotient) is assigned to op1. x/=5 <==> x=x/5
   op1%=op2    op1/=op2, op1 is divided by op2, result(remainder) is assigned to op1. x%=5 <==> x=x%5
   op1+=op2    op1+=op2, op1 is Added to op2, result is assigned to op1. x+=5 <==> x=x+5
   op1-=op2    op1-=op2, op1 is substracted from op2, result is assigned to op1. x-=5 <==> x=x-5

Python Ternary Operator

     Ternary Operators are very famous in Other Programming languages like C,C++, & Java. neste In Python syntax is little different compared to other programming languages.

Syntax:

[evaluate on True] if condition else [evaluate on False]

Condition is evaluated first, condition is True returns [evaluate on True] , Condition is False , [evalate on False] will be returned

	>>>a=20
	>>>b=30
	
find max value using ternary operator
	>>> a if ( a > b )  else b
	30
	
find max value from 3 values
	>>>a=10;b=20;c=5	
	>>> a if (a>b and a>c) else b if (b > c) else c
	20
	

ADS