Python

Collections & Conditional Logic in Python

uzairadamjee / September 3, 2022

Conditional Logic in Python

A lot of time we are stuck in a situation like when this happens do something else do some other task, this is also called decision taking based on certain criteria or conditions.

If..elif..else these statements are used when doing the decision-making in Python.

Keep in mind below the logical symbols and logical operators as they will help in decision making and they can be used with IF statements or LOOPS as well

SymbolOperation
==Equal to
!=Not Equal to
Greater than
Less than
>=Greater than equal to
<=Less than equal to
and (logical operator)When two statements are true
or (logical operator)When one of the statement is true
first_name = ‘Jacob’
second_name = ‘David’
if girst_name == second_name:
  print("Both Names matched")
else:
  print("Names not matched")

***indentation***

a = 100
b = 330
if b > a:
  print("b is greater than a")
elif a == b:
  print("a and b are equal")
else:
  print("a is greater than b")

Collections in Python

So far we have learned about how to save a value inside a variable, but what if we have to store multiple values inside a variable?

Well, the answer is we have to use collections for that. It has 4 main types

List:

  • It can store any data type value in it. It can be changed

Tuple:

  • It can store any data type value in it. It can’t be changed

Sets:

  • Collection of no duplicate members. It can’t be indexed

Dictionary:

  • The collection which can be changed and indexed as well but with no duplicate members

LIST:

  • Use square brackets [] to define a list
  • The list is mutable… it can be changed after we define
  • The list can hold values of different types
  • It can hold duplicate values as well

Code:

lst = [“one”, 2, “three”]

print(lst)

TUPLE:

  • Use square brackets () to define tuple
  • Tuple is immutable… it can’t be changed after it defined
  • Tuple can hold values of different types
  • Tuple can hold duplicate values as well

Code:

tup = (‘BMW’, ‘Suzuki’, ‘Nissan’,2)

print(tup)

SETS:

  • Use square brackets {} to define sets
  • It can be changed after initializing
  • It has no duplicate members and It has no indexes
  • It can hold values of different types

Code:

set = {“Nissan”, “BMW”, “Honda”,2}

print(set)

DICTIONARY:

  • Use square brackets {} to define sets
  • It can be changed after initializing and it has indexes in form of Keys as well
  • Two terms to remember

                ->Key
                ->Value

Every item requires a key and its values

  • It has no duplicate members
  • It can hold values of different types
dic = {'Name': 'Uzair', 'Age': 24, 'Education': 'Masters'}
print(dic)

Leave a Reply

Your email address will not be published.