Python3 Beginner Workshop
“Talk is cheap. Show me the code.”
― Linus Torvalds
Himanshu Awasthi
B.Tech(VII Sem)
@himanshu230195
2
Agenda for todays workshop
• Numbers
• Strings
• List
• Tuples
• Dictionary
• Control statements - if/for
• functions
• in built functions
• classes
3
4
5
Lets dive into Python
Numbers :
Python supports integers, floating point numbers and complex
numbers. They are defined as int, float and complex class in Python.
Integers and floating points are separated by the presence or absence
of a decimal point. 5 is integer whereas 5.0 is a floating point number.
Complex numbers are written in the form, x + yj, where x is the real
part and y is the imaginary part.
We can use the type() function to know which class a variable or a
value belongs to and isinstance() function to check if it belongs to a
particular class.
6
Numbers
Open you terminal & start code :
>>> a=5
>>> type(a)
<class 'int'>
>>> type(5.0)
<class 'float'>
>>> c =5+3j
>>> c+3
(8+3j)
>>> isinstance(c,complex)
True
>>> type(c)
<class 'complex'>
7
Cont..
Number System Prefix
Binary ‘0b’ or ‘0B’
Octal ‘0o’ or ‘0O’
Hexadecimal ‘0x’ or ‘0X’
For eg :
>>> 0b1101011
107
>>> 0xFB + 0b10
253
>>> 0o15
13
8
Cont..
Type Conversion:
We can convert one type of number into another. This is also known as coercion.
We can also use built-in functions like int(), float() and complex() to convert between types explicitly.
For eg:
>>> int(2.3)
2
>>> int(-2.8)
-2
>>> float(5)
5.0
>>> complex('3+5j')
(3+5j)
When converting from float to integer, the number gets truncated (integer that is closer to zero).
9
Cont..
Python Decimal:
Python built-in class float performs some calculations that
might amaze us. We all know that the sum of 1.1 and 2.2 is
3.3, but Python seems to disagree.
>>> (1.1 + 2.2) == 3.3
False
10
Cont..
To overcome this issue, we can use decimal module that
comes with Python. While floating point numbers have
precision up to 15 decimal places, the decimal module has
user settable precision.
For eg:
>>> from decimal import Decimal
>>> print(Decimal('1.1')+Decimal('2.2'))
3.3
11
String
Strings are nothing but simple text. In Python we declare strings in between
“” or ‘’ or ‘” ‘” or “”” “””. The examples below will help you to understand
string in a better way.
>>> s = "I am Indian"
>>> s
'I am Indian'
>>> s = 'I am Indian'
>>> s
'I am Indian'
>>> s = "Here is a line
... splitted in two lines"
>>> s
'Here is a linesplitted in two lines'
12
Cont..
Now if you want to multiline strings you have to use triple
single/double quotes.
>>> s = """This is a
... multiline string, so you can
... write many lines"""
>>> print(s)
This is a
multiline string, so you can
write many lines
13
Cont..
Every string object is having couple of buildin methods available, we already saw
some of them like s.split(” ”).
>>> s = "Himanshu Awasthi"
>>> s.title()
'Himanshu Awasthi'
>>> z = s.upper()
>>> z
'HIMANSHU AWASTHI'
>>> z.lower()
'himanshu awasthi'
>>> s.swapcase()
'hIMANSHU aWASTHI'
14
Cont..
Lets practice :
isalnum()
isalpha()
isdigit()
islower()
split()
join()
len()
#Lets check Palindrome
15
List
We are going to learn a data structure called list. Lists can be written as
a list of comma-separated values (items) between square brackets.
>>>list = [ 1, 342, 2233423, 'Kanpur', 'python']
>>>a
[1, 342, 2233423, 'Kanpur', 'python']
Lets practice ^^
16
Cont..
Practice these inbuilt functions and keywords :
del
sort()
reverse()
remove()
count()
insert()
append()
17
Cont..
Using lists as stack and queue:
pop()
List Comprehensions:
For example if we want to make a list out of the square values of another list, then;
>>>a = [1, 2, 3]
>>>[x**2 for x in a]
[1, 4, 9]
>>>z = [x + 1 for x in [x**2 for x in a]]
>>>z
[2, 5, 10]
18
Touple
Tuples are data separated by comma.
>>> tuple = 'this', 'is' , 'kanpur' , 'tech' , 'community'
>>> tuple
('this', 'is', 'kanpur', 'tech', 'community')
>>> for x in tuple:
... print(x, end=' ')
...
this is kanpur tech community
Note :Tuples are immutable, that means you can not del/add/edit any
value inside the tuple
19
Dictionary
Dictionaries are unordered set of key: value pairs where keys are unique. We
declare dictionaries using {} braces. We use dictionaries to store data for any
particular key and then retrieve them.
>>> data = { 'himanshu':'python' , 'hitanshu':'designer' , 'hardeep':'wordpress'}
>>> data
{'hardeep': 'wordpress', 'hitanshu': 'designer', 'himanshu': 'python'}
>>> data['himanshu']
'python'
Lets practice Add/Del elements in dictionary
20
Cont..
dict() can create dictionaries from tuples of key,value pair.
>>> dict((('himanshu','python') , ('hardeep','wordpress')))
{'hardeep': 'wordpress', 'himanshu': 'python'}
If you want to loop through a dict use Iteritems() method.
In python3 we use only items()
>>> data
{'hardeep': 'wordpress', 'hitanshu': 'designer', 'himanshu': 'python'}
>>> for x , y in data.items():
... print("%s uses %s" % (x ,y))
...
hardeep uses wordpress
hitanshu uses designer
himanshu uses python
21
Cont..
You may also need to iterate through two sequences same time, for that use
zip() function.
Eg:
>>> name= ['ankit', 'hardeep']
>>> work= ['php' , 'wordpress']
>>> for x , y in zip(name , work):
... print("%s uses %s" % (x ,y))
...
ankit uses php
hardeep uses wordpress
22
Control statements
Lets practice :
If statement
Else statement
While loop
Eg : Fibonacci Series
Table multiplication
23
functions
Reusing the same code is required many times within a same program.
Functions help us to do so. We write the things we have to do repeatedly in a
function then call it where ever required.
Defining a function:
We use def keyword to define a function. General syntax is like
def functionname(params):
– statement1
– Statement2
– >>> def sum(a, b):
– ... return a + b
24
Cont..
Practice some functions example ;
Like factorial
>>> def fact(n):
... if n == 0:
... return 1
... return n* fact(n-1)
...
>>> print(fact(5))
120
How map & lambda works
25
classes
Classes provide a means of bundling data and functionality together.
We define a class in the following way :
class nameoftheclass(parent_class):
● statement1
● statement2
● statement3
●
>>> class MyClass(object):
… a = 90
… b = 88
...
>>>p = MyClass()
>>>p
<__main__.MyClass instance at 0xb7c8aa6c>
>>>dir(p)
26
Cont..
__init__ method:
__init__ is a special method in Python classes, it is the constructor method for a
class. In the following example you can see how to use it.
class Student(object):
– def __init__(self, name, branch, year):
● self.name = name
● self.branch = branch
● self.year = year
● print("A student object is created.")
– def print_details(self):
● print("Name:", self.name)
● print("Branch:", self.branch)
● print("Year:", self.year)
27
Cont..
>>> std1 = Student('Himanshu','CSE','2014')
A student object is created
>>>std1.print_details()
Name: Himanshu
Branch: CSE
Year: 2014
Lets take a look another example ;
28
Happy Coding
Thank you!

Python basics

  • 1.
    Python3 Beginner Workshop “Talkis cheap. Show me the code.” ― Linus Torvalds Himanshu Awasthi B.Tech(VII Sem) @himanshu230195
  • 2.
    2 Agenda for todaysworkshop • Numbers • Strings • List • Tuples • Dictionary • Control statements - if/for • functions • in built functions • classes
  • 3.
  • 4.
  • 5.
    5 Lets dive intoPython Numbers : Python supports integers, floating point numbers and complex numbers. They are defined as int, float and complex class in Python. Integers and floating points are separated by the presence or absence of a decimal point. 5 is integer whereas 5.0 is a floating point number. Complex numbers are written in the form, x + yj, where x is the real part and y is the imaginary part. We can use the type() function to know which class a variable or a value belongs to and isinstance() function to check if it belongs to a particular class.
  • 6.
    6 Numbers Open you terminal& start code : >>> a=5 >>> type(a) <class 'int'> >>> type(5.0) <class 'float'> >>> c =5+3j >>> c+3 (8+3j) >>> isinstance(c,complex) True >>> type(c) <class 'complex'>
  • 7.
    7 Cont.. Number System Prefix Binary‘0b’ or ‘0B’ Octal ‘0o’ or ‘0O’ Hexadecimal ‘0x’ or ‘0X’ For eg : >>> 0b1101011 107 >>> 0xFB + 0b10 253 >>> 0o15 13
  • 8.
    8 Cont.. Type Conversion: We canconvert one type of number into another. This is also known as coercion. We can also use built-in functions like int(), float() and complex() to convert between types explicitly. For eg: >>> int(2.3) 2 >>> int(-2.8) -2 >>> float(5) 5.0 >>> complex('3+5j') (3+5j) When converting from float to integer, the number gets truncated (integer that is closer to zero).
  • 9.
    9 Cont.. Python Decimal: Python built-inclass float performs some calculations that might amaze us. We all know that the sum of 1.1 and 2.2 is 3.3, but Python seems to disagree. >>> (1.1 + 2.2) == 3.3 False
  • 10.
    10 Cont.. To overcome thisissue, we can use decimal module that comes with Python. While floating point numbers have precision up to 15 decimal places, the decimal module has user settable precision. For eg: >>> from decimal import Decimal >>> print(Decimal('1.1')+Decimal('2.2')) 3.3
  • 11.
    11 String Strings are nothingbut simple text. In Python we declare strings in between “” or ‘’ or ‘” ‘” or “”” “””. The examples below will help you to understand string in a better way. >>> s = "I am Indian" >>> s 'I am Indian' >>> s = 'I am Indian' >>> s 'I am Indian' >>> s = "Here is a line ... splitted in two lines" >>> s 'Here is a linesplitted in two lines'
  • 12.
    12 Cont.. Now if youwant to multiline strings you have to use triple single/double quotes. >>> s = """This is a ... multiline string, so you can ... write many lines""" >>> print(s) This is a multiline string, so you can write many lines
  • 13.
    13 Cont.. Every string objectis having couple of buildin methods available, we already saw some of them like s.split(” ”). >>> s = "Himanshu Awasthi" >>> s.title() 'Himanshu Awasthi' >>> z = s.upper() >>> z 'HIMANSHU AWASTHI' >>> z.lower() 'himanshu awasthi' >>> s.swapcase() 'hIMANSHU aWASTHI'
  • 14.
  • 15.
    15 List We are goingto learn a data structure called list. Lists can be written as a list of comma-separated values (items) between square brackets. >>>list = [ 1, 342, 2233423, 'Kanpur', 'python'] >>>a [1, 342, 2233423, 'Kanpur', 'python'] Lets practice ^^
  • 16.
    16 Cont.. Practice these inbuiltfunctions and keywords : del sort() reverse() remove() count() insert() append()
  • 17.
    17 Cont.. Using lists asstack and queue: pop() List Comprehensions: For example if we want to make a list out of the square values of another list, then; >>>a = [1, 2, 3] >>>[x**2 for x in a] [1, 4, 9] >>>z = [x + 1 for x in [x**2 for x in a]] >>>z [2, 5, 10]
  • 18.
    18 Touple Tuples are dataseparated by comma. >>> tuple = 'this', 'is' , 'kanpur' , 'tech' , 'community' >>> tuple ('this', 'is', 'kanpur', 'tech', 'community') >>> for x in tuple: ... print(x, end=' ') ... this is kanpur tech community Note :Tuples are immutable, that means you can not del/add/edit any value inside the tuple
  • 19.
    19 Dictionary Dictionaries are unorderedset of key: value pairs where keys are unique. We declare dictionaries using {} braces. We use dictionaries to store data for any particular key and then retrieve them. >>> data = { 'himanshu':'python' , 'hitanshu':'designer' , 'hardeep':'wordpress'} >>> data {'hardeep': 'wordpress', 'hitanshu': 'designer', 'himanshu': 'python'} >>> data['himanshu'] 'python' Lets practice Add/Del elements in dictionary
  • 20.
    20 Cont.. dict() can createdictionaries from tuples of key,value pair. >>> dict((('himanshu','python') , ('hardeep','wordpress'))) {'hardeep': 'wordpress', 'himanshu': 'python'} If you want to loop through a dict use Iteritems() method. In python3 we use only items() >>> data {'hardeep': 'wordpress', 'hitanshu': 'designer', 'himanshu': 'python'} >>> for x , y in data.items(): ... print("%s uses %s" % (x ,y)) ... hardeep uses wordpress hitanshu uses designer himanshu uses python
  • 21.
    21 Cont.. You may alsoneed to iterate through two sequences same time, for that use zip() function. Eg: >>> name= ['ankit', 'hardeep'] >>> work= ['php' , 'wordpress'] >>> for x , y in zip(name , work): ... print("%s uses %s" % (x ,y)) ... ankit uses php hardeep uses wordpress
  • 22.
    22 Control statements Lets practice: If statement Else statement While loop Eg : Fibonacci Series Table multiplication
  • 23.
    23 functions Reusing the samecode is required many times within a same program. Functions help us to do so. We write the things we have to do repeatedly in a function then call it where ever required. Defining a function: We use def keyword to define a function. General syntax is like def functionname(params): – statement1 – Statement2 – >>> def sum(a, b): – ... return a + b
  • 24.
    24 Cont.. Practice some functionsexample ; Like factorial >>> def fact(n): ... if n == 0: ... return 1 ... return n* fact(n-1) ... >>> print(fact(5)) 120 How map & lambda works
  • 25.
    25 classes Classes provide ameans of bundling data and functionality together. We define a class in the following way : class nameoftheclass(parent_class): ● statement1 ● statement2 ● statement3 ● >>> class MyClass(object): … a = 90 … b = 88 ... >>>p = MyClass() >>>p <__main__.MyClass instance at 0xb7c8aa6c> >>>dir(p)
  • 26.
    26 Cont.. __init__ method: __init__ isa special method in Python classes, it is the constructor method for a class. In the following example you can see how to use it. class Student(object): – def __init__(self, name, branch, year): ● self.name = name ● self.branch = branch ● self.year = year ● print("A student object is created.") – def print_details(self): ● print("Name:", self.name) ● print("Branch:", self.branch) ● print("Year:", self.year)
  • 27.
    27 Cont.. >>> std1 =Student('Himanshu','CSE','2014') A student object is created >>>std1.print_details() Name: Himanshu Branch: CSE Year: 2014 Lets take a look another example ;
  • 28.