Dictionary and Sets Session 6

Dictionary 

Dictionary is a collection of key-value pairs.

Syntax:

''' a = {“key”: “value”,
“hey”: “code”,
“marks” : “100”,
“list”: [1,2,9]}
a[“key”]	# Prints value
a[“list”] 	# Prints [1,2,9] '''
Properties of Python Dictionaries
  1. It is unordered
  2. It is mutable
  3. It is indexed
  4. It cannot contain duplicate keys
Dictionary Methods

Consider the following dictionary,

a = {“name”: “Codes4u”,from: “Pakistan”,
	“marks”: [92,98,96]}
  1. items() : returns a list of (key,value) tuple.
  2. keys() : returns a list containing dictionary’s keys.
  3. update({“friend”: “Iqra”}) : updates the dictionary with supplied key-value pairs.
  4. get(“name”) : returns the value of the specified keys (and value is returned e.g., “Iqra” is returned here)

More methods are available on docs.python.org

Sets in Python

Set is a collection of non-repetitive elements.

S= Set()          # No repetition allowed!

S.add(1)

S.add(2)

# or Set = {1,2}

If you are a programming beginner without much knowledge of mathematical operations on sets, you can simply look at sets in python as data types containing unique values.

Properties of Sets
  1. Sets are unordered # Elements order doesn’t matter
  2. Sets are unindexed # Cannot access elements by index
  3. There is no way to change items in sets
  4. Sets cannot contain duplicate values
Operations on Sets

Consider the following set:

S = {1,8,2,3}
  1. Len(s) : Returns 4, the length of the set
  2. remove(8) : Updates the set S and removes 8 from S
  3. pop() : Removes an arbitrary element from the set and returns the element removed.
  4. clear() : Empties the set S
  5. union({8, 11}) : Returns a new set with all items from both sets. #{1,8,2,3,11}
  6. intersection({8, 11}) : Returns a set which contains only items in both sets. #{8}


Conditional Expressions

Sometimes we want to play pubg on our phone if the day is Sunday.

Sometimes we order Ice-cream online if the day is sunny.

Sometimes we go hiking if our parents allow.

All these are decisions that depend on the condition being met.

In python programming too, we must be able to execute instructions on a condition(s) being met. This is what conditions are for!

If else and elif in Python

If else and elif statements are a multiway decision taken by our program due to certain conditions in our code.

Syntax:

'''
if (condition1):		// if condition 1 is true
	print(“yes”)
elif (condition2):		// if condition 2 is true
	print(“No”)
else:				// otherwise
	print(“May be”)
'''

Code example:

a = 22
if (a>9):
    print(“Greater”)
else:
    print(“lesser”)

Quick Quiz: Write a program to print yes when the age entered by the user is greater than or equal to 18.

Relational Operators

Relational operators are used to evaluate conditions inside if statements. Some examples of relational operators are:

= = -> equals

>=  -> greater than/equal to

<=, etc.
Logical Operators

In python, logical operators operate on conditional statements. Example:

and -> true if both operands are true else false

or -> true if at least one operand is true else false

not -> inverts true to false and false to true
elif clause

elif in python means [else if]. If statement can be chained together with a lot of these elif statements followed by an else statement.

'''
if (condition1):
    #code
elif (condition 2):
    #code
elif (condition 2):
    #code
….
else:
    #code    '''
  • The above ladder will stop once a condition in an if or elif is met.

Important Notes:

  • There can be any number of elif statements.
  • Last else is executed only if all the conditions inside elifs fail.




 Practice Set

  1. Write a program to create a dictionary of urdu words with values as their English translation. Provide the user with an option to look it up!
  2. Write a program to input eight numbers from the user and display all the unique numbers (once).
  3. Can we have a set with 18(int) and “18”(str) as a value in it?
  4. What will be the length of the following set S:
  5. S = Set()
    
    S.add(20)
    
    S.add(20.0)
    
    S.add(20)

    What will be the length of S after the above operations?

    1. S = {}, what is the type of S?
    2. Create an empty dictionary. Allow 4 friends to enter their favorite language as values and use keys as their names. Assume that the names are unique.
    3. If the names of 2 friends are the same; what will happen to the program in Program 6?
    4. If the languages of two friends are the same; what will happen to the program in Program 6?
    5. Can you change the values inside a list which is contained in set S
    S = {8, 7, 12, “Mustajab”, [1, 2]}
    Write a program to find out whether a student is pass or fail if it requires a total of 40% and at least 33% in each subject to pass. Assume 3 subjects and take marks as an input from the userA spam comment is defined as a text con

10. A spam comment is defined as a text containing the following keywords:

“make a lot of money”, “buy now”, “subscribe this”, “click this”. Write a program to detect these spams.

11.Write a program to find whether a given username contains less than 10 characters or not.

12. Write a program that finds out whether a given name is present in a list or not. 13. Write a program to calculate the grade of a student from his marks from the following scheme:

90-100Ex
80-90A
70-80B
60-70C
50-60D
<50F

Comments

Popular posts from this blog

Loops and Functions Session 8

Python Installation

How to Change your (dev/visual) console color