0% found this document useful (0 votes)
5 views

L-2 Introduction to Coding in Python

Uploaded by

omvati343
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
5 views

L-2 Introduction to Coding in Python

Uploaded by

omvati343
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 43

Introduction to

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

❖ Python Keywords are special reserved words that convey a special


meaning to the compiler/interpreter.
❖ Each keyword has a special meaning and a specific operation.
❖ These keywords can't be used as variables.
❖ In Python 3.12, there are 35 keywords.
❖ To see all keywords in Python use the command:
import keyword
print(keyword.kwlist)

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)

❑ Here, objects is the value(s) to be printed.


❑ The sep separator is used between the values. It defaults into a space character.
❑ After all values are printed, end is printed. It defaults into a new line.
❑ The file is the object where the values are printed and its default value
is sys.stdout (screen).

❖ 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.

❖ Writing comments is a good programming practice. It enables us to understand


the way, a program works.
❖ Comments are non-executable part of the code, but it enhances the readability
of the program and makes it more understandable for the coders.
❖ These not only help other programmers working on the same project but the
testers can also refer them for clarity in testing phase.
❖ Python supports two types of comments:
1. Single Line Comment: In case user wants to specify a single line
comment, then comment must start with #.
2. Multi Line Comment: Multi lined comment can be given inside triple
quotes single or double.
7
Output Formatting using format() function
format()

❖ str.format() is a string formatting methods in Python3.


❖ It enables to concatenate elements within a string through positional
formatting along with multiple substitutions and value formatting.
❖ The string that is passed as parameters into the format function is
replaced & concatenated into the placeholders defined by {}.
❖ Syntax:
{ } .format(value)
where:-
1. (value) : is any integer, floating point constant, a string,
character or variable.
2. Return_type : A formatted string with parameter value placed
in the placeholder {}.
8
Output Formatting using format() function
format()

Example 1:

# Demo of format()

print ("{}, Hello ! Welcome to python lecture." .format("Good Evening…"))

# Demo of format() with a variable

str1 = "This lecture is about {}"


print (str1.format("Python Programming"))

# Demo of format() with a numeric constant value

print (“There are {} players in a cricket team” .format(12))


9
Output Formatting using format() function
format() and Positional Arguments

❖ 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 :

{0} {1}.format(positional_argument, keyword_argument)

where:-

1. Positional_argument may be integer, floating point constant, string, character or a


variable.
2. Keyword_argument is a variable passed as parameter.

10
Positional Arguments
{0}{1} position arguments

# Demo of Positional arguments in order

print("{0} and {1} are great programming languages".format(“Python”, “Java”))

# Demo of jumbled index numbers

print("{1} and {0} are great programming languages".format(“Python”, “Java”))

print(“Learning {} , {} and {} programming languages is great {}” .format(“Java”, “Python”, “Kotlin”,


“fun”))

# Demo of Keyword arguments

print(“{lang} is a {0} purpose {1}”.format(“general”, “language”, lang =“Python”))


11
Identifiers or Variables in python
Variables are Literals with name

❖ An Identifier is used to identify the literals (or values) used in the program.

❖ Variable is also known as identifier which is used to hold certain value.

❖ 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?

The rules for naming an identifier are listed below:


❖ The first character of the Identifier name must be an alphabet or underscore ( _ ).
❖ All the characters in Identifier name except the first character can be an alphabet
in upper-case (A-Z), lower-case (a-z), an underscore or a digit (0-9).
❖ Identifier name must not contain any white-space, or special character (!, @, #, $,
%, ^, &, *).
❖ No keyword can be used as identifier name.
❖ Identifier names are case sensitive i.e., ContactNo, Contactno, contactno and
contact_No are all different.
❖ Examples of valid identifiers : ab789, _a, a_78, ab, etc.
❖ Examples of invalid identifiers: 7a, a!7, a 7, @qw etc.

13
Variable declaration & assignment
How to use variables?

❖ In Python we don't need to declare variables beforehand explicitly.


❖ Rather we may create variable as and when required anywhere
anytime.
❖ The equal (=) operator can be used to assign a value to the
variable.
❖ We may also assign a value to the variable at the time of declaring
the variable.

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:

PYTHON DATA TYPES

SEQUENCE
NUMERIC DICTIONARY BOOLEAN SET
TYPES

COMPLEX STRINGS LISTS TUPLES


INTEGER FLOAT
NUMBER

16
Sequence Types in Python
Collection of Items with ordering.

❖ The most basic data structure in Python is the 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.
❖ Each element of a sequence is assigned a number - its position or
index. The first index is zero, the second index is one, and so forth.
❖ There are 5 basic sequence types:
❑ Strings
❑ Lists
❑ Tuples

17
Datatypes in python (contd.)
Types of Data and their values.

● Python data types are categorized


into two as follows: Data Types in
Python
❖ Mutable Data Types: Data
types in python where the
value assigned to a variable
can be changed Immutable Types: Mutable Types:
Immutable
Number
Types: Mutable Types:
Dictionaries
1. Number
Strings 1. Dictionaries
Lists
❖ Immutable Data Types: Data Tuples
2. Strings Sets
2. Lists
types in python where the 3. Tuples 3. Sets
value assigned to a variable
cannot be changed
NUMERIC DATATYPES IN PYTHON
Numeric 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.

❖ Integers can have positive, negative or zero value.

❖ Floating-point numbers are real numbers with a decimal point and fractional part.

❖ It is possible to represent an integer in hexa-decimal or octal form.

❖ type() method returns class type of the argument(object) passed as parameter.

19
Binary, Octal & Hexadecimal Numbers
Numbers in different formats.

❖ For octal numbers (i.e. base 8): precede a number by 0o i.e. :

0o (zero + lowercase letter 'o’)


0o (zero + uppercase letter ’O’)

❖ For Hexadecimal numbers (i.e. base 16): precede a number by 0x i.e. :


0x (zero + lowercase letter 'x’)
0x (zero + uppercase letter 'X’)

❖ For Binary numbers (i.e. base 2): precede a number by b i.e.:

0b (zero + lowercase letter 'b’)


0B (zero + uppercase letter 'B')
20
Number Type Conversion
Convert one type to other.

❖ There are a few built-in Python functions that let us convert numbers explicitly from one type to
another. These are:

❑ int (x) : to convert x into an integer value

❑ float (x) : to convert x into a floating-point number

❑ 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

❖ String literals can be defined as collection of characters enclosed in quotes.

❖ Following types of string literals are present in Python:


➢ Single-line Strings –Those strings that are terminated within a single-line
are known as Single line String literals. Example: str1=‘Welcome’
➢ Multi-line Strings - A text string that is written in multiple lines is called as
multi-line string. There are two ways to create multiline strings:
1. By adding a black slash at the end of each String.
Example: str2=‘Python \
Strings'
print(str2) Output : Python Strings
2. Using triple quotation marks:-
Example: str3= ''' Hello all to
Python class'''
print (str3) Output: Hello all to Python class 22
String Indexing, Slicing and Negative Slicing
[:]

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.

❖ Various operations can be performed on Lists:

❑ Creating a List

❑ Accessing elements in a List

❑ Updating elements in a List

❑ Appending new elements to List

❑ Deleting elements from List

25
Built-in Methods & Functions for Lists.
Applying methods & Functions to Data Lists.

Python includes the following list of Methods −


Method Description
append() Adds an element at the end of the list
clear() Removes all the elements from the list
copy() Returns a copy of the list
count() Returns the number of elements with the specified value
extend() Add the elements of a list, to the end of the current list
index() Returns the index of the first element with the specified value
insert() Adds an element at the specified position
pop() Removes the element at the specified position
remove() Removes the item with the specified value
reverse() Reverses the order of the list
26
sort() Sorts the list
Built-in Methods & Functions for Lists.
Applying methods & Functions to Data Lists.

Python includes the following list of Functions −

Method Description

min(list_name) Returns the minimum value from a list in Python


max(list_name) Returns the largest value from a list in Python
len(list_name) Returns the number of elements in a list in Python
cmp(list1,list2) Compares two lists in Python (depreciated in python3)

list(sequence) Converts the sequence of a list in Python

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 [ ].

❖ Creating a tuple is as simple as putting different comma-separated values.

❖ 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.

❖ Various operations can be performed on Tuple:

❑ Creating a Tuple

❑ Accessing elements in a Tuple

❑ Deleting entire 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.

❖ Various operations can be performed on Sets:

❑ Creating a Set

❑ Accessing elements in a Set

❑ Add new elements in Set

❑ Get the Length of a Set

❑ Deleting elements from Set

❑ Join Two Sets

❖ 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.

❖ Python dictionary is yet another unordered collection of elements.


❖ The difference between Python dictionary sets lies in the fact that unlike sets, a dictionary
contains keys and values rather than just elements.
❖ Like lists, Python dictionaries can also be changed and modified, but unlike lists the values in
dictionaries are accessed using keys and not by their indexes or positions.
❖ Each key is separated from its value by a colon (:), the items are separated by commas, and the
whole thing is enclosed in curly braces.
❖ An empty dictionary without any items is written with just two curly braces, like this: {}.
❖ Keys are unique within a dictionary while values may not be. So, more than one entry per key is
not allowed.
❖ The values of a dictionary can be of any type, but the keys must be of an immutable data type
such as strings, numbers, or tuples.

41
Python Dictionaries
Data Dictionary.

❖ Various operations can be performed on Dictionary:

❑ Creating a Dictionary

❑ Accessing elements in a Dictionary

❑ Add new elements in Dictionary

❑ Updating elements in Dictionary

❑ Deleting elements from 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

You might also like