Python – While Loop

Python Loops

In loops, the statement are executed sequentially till the condition satisfied. The first statement in a function is executed first, followed by the second, and so on. Using Loops we can executed block of code for several times.

Python have two types of loops

StudyGyaan - Python Tutorial - While loop

Python While Loop

While loop we can execute a set of statements as long as a condition is true.

count = 1
while i < 6:
  print(i)
  count = count + 1

We use counter (variable-count) in while so that its does not go into infinite loop.

# While Loop

count = 1

while (count < 10):
if(count == 5):
print("Count", count)
count = count + 1
else:
print("Else Count", count)
Filed under: Python

Python – If…Else Condition

IF ELSE is a Decision Condition where a particular condition is true then that block of code is executed else break or different block of code is executed. Condition can be made using Operators such as Assignment, Comparison, Logical, Membership, Identity Operators

StudyGyaan - Python Tutorial - If..Else Condition

Syntax

If ( Condition ) :
   Statement (s)

If Statement

If statement can be written using if keyword. For example –

a = 33
b = 200
if b > a:
  print("b is greater than a")

# Output: b is greater than a

Indentation

Python relies on indentation, using whitespace, to define scope in the code. Other programming languages often use curly-brackets for this purpose.

a = 33
b = 200
if b > a:
print("b is greater than a")

# Output: Indentation Error Please put Indentation

Elif Statement

The elif keyword is pythons way of saying “if the previous conditions were not true, then try this condition”.

x = 100

if (x==10):
print("X is equal to 10")
elif (x==100):
print("X is equal to 100")

Else Statement

The else keyword catches anything which isn’t caught by the preceding conditions.

x = 100

if (x==10):
print("X is equal to 10")
elif (x==100):
print("X is equal to 100")
else:
print("X is not equal 10")

Nested If Else Statement

Nested If Else means Condition inside Condition. For Example:

y = "Hello"

if (x==100):
   if(y=="Hello"):
      print("X = 100 & y = Hello")
   else:
      print("Not true")
Filed under: Python

Python – Operators

Operators are used to perform operations on variables and values. Operator are nothing but used with variables to get some satisfied output. Using operators you can perform operation on variables like 1 + 2 = 3 where +, = are operators.

Types of Operators

Python divides the operators in the following groups:

  • Arithmetic operators
  • Assignment operators
  • Comparison operators
  • Logical operators
  • Identity operators
  • Membership operators
  • Bitwise operators

Let us have a look at all the operators one by one:

Python Arithmetic Operators

Arithmetic Operators are used to perform arithmetic operation.

OperatorExampleSame As
+Additionx + y
Subtractionx – y
*Multiplicationx * y
/Divisionx / y
%Modulusx % y
**Exponentiationx ** y
//Floor divisionx // y
x = 5
y = 3

print("Additon:",x + y)
print("Substraction:",x - y)
print("Multiplication:",x * y)
print("Division:",x / y)
print("Modulus:",x % y)
print("Exponentiation:",x ** y)
print("Floor Division:",x // y)

Python Assignment Operators

Assignment operators are used to assign values to variables:

OperatorExampleSame As
=x = 5x = 5
+=x += 3x = x + 3
-=x -= 3x = x – 3
*=x *= 3x = x * 3
/=x /= 3x = x / 3
%=x %= 3x = x % 3
//=x //= 3x = x // 3
**=x **= 3x = x ** 3
&=x &= 3x = x & 3
|=x |= 3x = x | 3
^=x ^= 3x = x ^ 3
>>=x >>= 3x = x >> 3
<<=x <<= 3x = x << 3
x = 5

print("Equal Sign:",x )

x = 5
x += 3
print("Addition Assign:",x)

x = 5
x -= 3
print("Substraction Assign:",x)

x = 5
x *= 3
print("Multiplication Assign:",x)

x = 5
x /= 3
print("Division Assign:",x)

x = 5
x %= 3
print("Modulus Assign:",x)

x = 5
x **= 3
print("Exponentiation Assign:",x)

x = 5
x //= 3
print("Floor Division Assign:",x)

Python Comparison Operators

Comparison operators are used to compare two values:

OperatorNameExample
==Equalx == y
!=Not equalx != y
>Greater thanx > y
<Less thanx < y
>=Greater than or equal tox >= y
<=Less than or equal tox <= y
x = 5
y = 3

print("Equal:",x == y)
print("Not Equal:",x != y)
print("Greater Than:",x > y)
print("Less Than:",x < y)
print("Greater than or equal to:",x >= y)
print("Less than or equal to:",x <= y)

Python Logical Operators

Logical operators are used to combine conditional statements:

OperatorDescriptionExample
and Returns True if both statements are truex < 5 and x < 10
orReturns True if one of the statements is truex < 5 or x < 4
notReverse the result, returns False if the result is truenot(x < 5 and x < 10)
x = 5

print(x > 3 and x < 10)
# returns True because 5 is greater than 3 AND 5 is less than 10

print(x > 3 or x < 10)
# returns True because one of the conditions are true (5 is greater than 3, but 5 is not less than 4)

print(not(x > 3 and x < 10))
# returns False because not is used to reverse the result

Python Identity Operators

Identity operators are used to compare the objects, not if they are equal, but if they are actually the same object, with the same memory location:

OperatorDescriptionExample
is Returns true if both variables are the same objectx is y
is notReturns true if both variables are not the same objectx is not y
x = ["apple", "banana"]
y = ["apple", "banana"]
z = x

print(x is z)
# returns True because z is the same object as x

print(x is not z)
# returns False because z is the same object as x

Python Membership Operators

Membership operators are used to test if a sequence is presented in an object:

OperatorDescriptionExample
in Returns True if a sequence with the specified value is present in the objectx in y
not inReturns True if a sequence with the specified value is not present in the objectx not in y
x = ["apple", "banana"]

print("banana" in x)
# returns True because a sequence with the value "banana" is in the list

print("pineapple" not in x)
# returns True because a sequence with the value "pineapple" is not in the list

Python Bitwise Operators

Bitwise operators are used to compare (binary) numbers:

OperatorNameDescription
ANDSets each bit to 1 if both bits are 1
|ORSets each bit to 1 if one of two bits is 1
 ^XORSets each bit to 1 if only one of two bits is 1
NOTInverts all the bits
<<Zero fill left shiftShift left by pushing zeros in from the right and let the leftmost bits fall off
>>Signed right shiftShift right by pushing copies of the leftmost bit in from the left, and let the rightmost bits fall off
Filed under: Python

Python – Casting

Python Variable Casting means converting one data type variable into another data type variable. Casting functions return a new object representing the converted value.

Types of Casting Functions:

  • int(x): Converts a x variable into Integer from float, integer or string (String should be a whole number) variable.
  • float(x): Converts a x variable into Float from float, integer or string (String should be a integer or float) variable.
  • str(x): Converts a x variable into String from float, integer or string variable.

Data Type Conversion Examples:

a = 202             # Integer
x = str(a)          # Output: 202 -> String
y = int(a)          # Output: 202
z = float(a)      # Output: 202.0

b = 1.25 # Float
x = str(b)          # Output: 1.25 -> String
y = int(b)          # Output: 1
z = float(b)      # Output: 1.25

c = "StudyGyaan" # String
x = str(c)          # Output: 1.25 -> String
# y = int(c)  -> Cannot convert        
# z = float(c)  -> Cannot convert
Filed under: Python

Python – Dictionary

Python’s dictionaries are kind of hash-table type where it have key value. A Dictionary contains items separated by commas and enclosed within square curly braces ({  })Dictionary is a collection which is unordered, changeable and indexed. No duplicate members.

Features of Python Tuples

  1. Unordered Lists
  2. Can change values and index after declaring elements
  3. Not allowed duplicate members
  4. Uses curly braces { }
  5. Can store different datatypes

Declaring Dictionary in Python

We can declared dictionary in two different wasy:

# First Way
dict1 = {}
dict1['one']="one"
dict1[1]=1

# Second Way
dict2 = {'two':'two',2:2}

Note – The plus (+) sign is the concatenation operator and the asterisk (*) is the repetition operator. For example −

dict1 = {}
dict1['one']="one"
dict1[1]=1

dict2 = {'two':'two',2:2}

print(dict1)
print(dict2)
print(dict1["one"])
print(dict1[1])
print(dict2.keys())
print(dict2.values())
Filed under: Python