L-2 Introduction to Coding in Python
L-2 Introduction to Coding in Python
Coding in Python
Beginning the journey of Python Programming
Trainer:
Ms. Nidhi Grover Raheja
Agenda for Today
We will cover the following topics in today’s training session:
➢ Python Basics
- Keywords
- Identifiers (Variables)
- Comments
- Input and Output
- Data types in Python
➢ Data Structures
- Strings
- Lists
- Tuples
- Sets
- Dictionaries
Keywords in python
Reserved Special Words
4
Standard Input/Output in Python
Take user Input using input() function.
❖ The functions like input() and print() are widely used for standard
input and output operations respectively.
❖ In Python, we have the input() function to allow this.
❖ The syntax for input() is
input([prompt])
where prompt is the string we wish to display on the screen.
❖ Example:
num = input('Enter a number: ')
5
Standard Input/Output in Python (contd.)
Python Output Using print() function.
❖ We use the print() function to output data to the standard output device (screen).
❖ The actual syntax of the print() function is:
print(*objects, sep=' ', end='\n', file=sys.stdout)
❖ Examples:
print(‘Hello User')
Output: Hello User
print(1,2,3,4)
Output: 1 2 3 4
print(1,2,3,4,sep='#',end='&') 6
Output: #1#2#3#4&
Comments in Python
Comment your text.
Example 1:
# Demo of format()
❖ The values that exist within the str.format() method are essentially tuple data types
and each individual value contained in the tuple can be called by its index number,
which starts with the index number 0.
❖ Syntax :
where:-
10
Positional Arguments
{0}{1} position arguments
❖ An Identifier is used to identify the literals (or values) used in the program.
❖ A variable is a named temporary storage area (or say a memory location) that can be given
some value.
❖ No need to specify the type of variable since Python is a type infer language and is intelligent
enough to get variable type itself.
12
Identifier naming conventions
How to name an Identifier?
13
Variable declaration & assignment
How to use variables?
14
Variable Concatenation
How to join variables?
❖ If we want to concatenate Python variables of different data types, let’s say a number variable and a
Python String variable, then we will have to declare the number variable as a string. If the number
variable is not declared as a string variable before concatenating the number variable with a string
variable, then Python will throw a TypeError.
❖ Example: a = ‘Hello’
b = 100
print (a+b)
❖ Here, this block of code will throw a TypeError as variable a is string type and variable b is number
type. To remove this error, we will have to declare the number variable as a string variable as
shown in the example below:
print(a + str(b))
❖ Output:
Hello100
15
Datatypes in python
Types of Data and their values.
❖ Python provides various standard data types that defines what type of data is being stored.
❖ Every variable is associated with a data type.
❖ The different types of Data types available in Python are shown in the diagram:
SEQUENCE
NUMERIC DICTIONARY BOOLEAN SET
TYPES
16
Sequence Types in Python
Collection of Items with ordering.
17
Datatypes in python (contd.)
Types of Data and their values.
❖ Number data types store numeric values. They are immutable data types i.e. changing the value
of a number data type results in a newly allocated object.
❖ In Python integers are whole numbers with no decimal point and fractional part.
❖ Floating-point numbers are real numbers with a decimal point and fractional part.
19
Binary, Octal & Hexadecimal Numbers
Numbers in different formats.
❖ There are a few built-in Python functions that let us convert numbers explicitly from one type to
another. These are:
❑ complex (x) : to convert x into a complex number where the imaginary part stays 0
and x becomes the real part
❑ complex (x, y) : to convert x and y to a complex number where x becomes the real part
and y becomes the imaginary part
21
String literals
String values
23
Lists sequence type
Data Lists.
❖ The list is a most versatile data type available in Python which can be written as a list of comma-
separated values (items) between square brackets.
❖ Please note that the items in a list need not be of the same type.
❖ list indices start at 0, and lists can be sliced, concatenated and so on.
❖ For example −
list1 = [‘English', ‘Maths', 90, 80]
list2 = [1, 2, 3, 4, 5 ]
list3 = ["a", "b", "c", "d"];
❖ To access values in lists, use the square brackets for slicing along with the index or indices to
obtain value available at that index.
24
Lists sequence type (contd.)
Data Lists.
❑ Creating a List
25
Built-in Methods & Functions for Lists.
Applying methods & Functions to Data Lists.
Method Description
27
Tuples sequence type
Data Tuple.
❖ A tuple is a sequence of immutable Python objects. Tuples are sequences, just like lists.
❖ Tuples are different from Lists because, the tuples cannot be changed unlike lists and tuples may or
may not use parentheses ( ), whereas lists use square brackets [ ].
❖ For example −
tup1 = ('physics', 'chemistry', 1997, 2000)
tup2 = (1, 2, 3, 4, 5 )
tup3 = "a", "b", "c", "d"
❖ The empty tuple is written as two parentheses containing nothing −tup1 = (); To write a tuple for only
one value −tup1 = (50,)
❖ Like string indices, tuple indices start at 0, and they can be sliced, concatenated, and so on.
28
Tuples sequence type (contd.)
Data Tuple.
❑ Creating a Tuple
29
Tuples Methods & Functions
Data Tuple.
Python has two built-in methods that you can use on tuples.
Method Description
count() Returns the number of times a specified value occurs in a tuple
index() Searches the tuple for a specified value and returns the position
of where it was found
30
Sequence Vs Collections
Data Collection not sequence.
❖ A sequence is a group of items with a deterministic ordering. The order in which we put them in is
the order in which we get an item out from them.
❖ Python collection, unlike a sequence, does not have a deterministic ordering. In a collection, while
ordering is arbitrary, physically, they do have an order.
❖ Every time we visit a set, we get its items in the same order. However, if we add or remove an item,
it may affect the order.
❖ Two major types of collections:
1. Set is a collection which is unordered and unindexed. No duplicate members.
2. Dictionary is a collection which is unordered, changeable and indexed. No duplicate members
31
Python Sets
Data Sets.
❖ A set in Python is mutable, iterable, and does not have any duplicate elements.
❖ It is an unordered collection of elements which may be of different Python Data Types.
❖ We cannot access items in a set by referring to an index, since sets are unordered the items has
no index. But we can iterate through set items by using a for loop, and ask if a specified value is
present in a set, by using the ‘in’ keyword.
❖ Some of the properties of sets :
❑ A set in Python doesn’t index the elements in a particular order i.e. In Python sets,
elements don’t have a specific order.
❑ Sets in Python can’t have duplicates. Each item is unique.
❑ The elements of a set in Python are immutable. They can’t accept changes once added.
32
Python Sets (contd.)
Data Sets.
❑ Creating a Set
❖ Frozen Sets Frozen sets are immutable objects that only support methods and operators
that produce a result without affecting the frozen set or sets to which they are applied.
33
Python Set Operators
Data Set Operators.
Operator Description
key in s containment check and non-containment check
key not in s
s1 == s2 Equivalence Check
s1 != s2
s1 <= s2 i.e. s1is subset of s2 Subset Check
s1 < s2 i.e. s1 is proper subset of s2
s1 >= s2 i.e. s1is superset of s2 Superset Check
s1 > s2 i.e. s1 is proper superset of s2
s1 | s2 Union of s1 and s2
s1 & s2 Intersection of s1 and s2
s1 – s2 Difference i.e. the set of elements in s1 but not s2
s1 ˆ s2 To find set of elements in precisely one of s1 or s2
34
Common Python Set methods
Data Set Methods.
Method Description
update() It updates a set with the union of this set and others.
add() It adds an element to a set.
clear() It removes all elements from a set.
copy() It returns a copy of a set.
difference() It returns a set containing difference between two or more sets.
difference_update() It removes the items in a set that are also included in other set.
discard() It removes a specified item.
remove() It removes a specified element.
35
Common Python Set methods (contd.)
Data Set Methods.
Method Description
pop() It removes an element from a set.
intersection() It returns a set, that is the intersection of two other sets.
intersection_update() It removes items in a set that are not present in another set(s).
isdisjoint() It returns whether two sets have an intersection or not.
issubset() It returns whether another set contains a specific set or not.
issuperset() It returns whether a set contains another set or not.
symmetric_difference() It returns a set with the symmetric differences of two sets.
union() or | It returns a set containing the union of sets.
intersection or & It returns a set comprising common elements in two sets.
36
Dictionaries in Python
Data Dictionary.
41
Python Dictionaries
Data Dictionary.
❑ Creating a Dictionary
42
Python Dictionaries Methods
Data Dictionary.
Method Description
clear() It removes all elements from a dictionary.
copy() It returns a copy of a dictionary.
fromkeys() It returns a dictionary with the specified keys and values.
get() It returns the value of a specified key.
items() It returns a list containing a tuple for each key–value pair.
keys() It returns a list containing the dictionary’s keys.
pop() It removes an element with a specified key.
popitem() It removes the last inserted (key, value) pair.
setdefault() It returns the value of a specified key.
update() It updates a dictionary with the specified key–value pairs.
values() It returns a list of all values in a dictionary.
43
Python Dictionaries Functions
Data Dictionary Functions.
Function Description
len(dictionary) Gives the total length of the dictionary. This would be equal to the number
of items in the dictionary.
str(dictionary) Produces a printable string representation of a dictionary.
type(dictionary) Returns the type of the passed variable. If passed variable is dictionary,
then it would return a dictionary type.
44