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

Python 141215095441 Conversion Gate01 PDF

The document provides an introduction and overview of Python. It covers the objectives of learning Python, including syntax, strings, lists, functions, and importing modules. It discusses Python's history and uses in applications like web development, science, and games. It also covers installing Python, running programs, variables and data types, operators, strings and string methods, lists and list methods, tuples, and dictionaries.

Uploaded by

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

Python 141215095441 Conversion Gate01 PDF

The document provides an introduction and overview of Python. It covers the objectives of learning Python, including syntax, strings, lists, functions, and importing modules. It discusses Python's history and uses in applications like web development, science, and games. It also covers installing Python, running programs, variables and data types, operators, strings and string methods, lists and list methods, tuples, and dictionaries.

Uploaded by

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

Introduction to Python

2017
O BJECTIVES I NTRODUCTION S YNTAX S TRINGS L ISTS D ICTIONARY L OOPS F UNCTIONS I MPORT &F UTURE T OPICS

Objectives
I Introduction to Python
I Hands-on
I Syntax
I Strings
I Lists
I Control Flow & Loops
I Functions
I Import & Future Topics
I Helpful hints & resources
O BJECTIVES I NTRODUCTION S YNTAX S TRINGS L ISTS D ICTIONARY L OOPS F UNCTIONS I MPORT &F UTURE T OPICS

What is Python?
I Is it a Scripting language?
I An Object-oriented language maybe?
I How about an Interpreted language?
Python is
I General purpose, object oriented, high level, interpreted
language
I Simple,Portable,Open source & Powerful
I Developed in early 90’s by Guido Van Rossum
O BJECTIVES I NTRODUCTION S YNTAX S TRINGS L ISTS D ICTIONARY L OOPS F UNCTIONS I MPORT &F UTURE T OPICS

Python vs Java
I Dynamic vs Static Typing - Handling variables
I Indentation vs Braces - Separate code into blocks
I Terse vs Verbose - Number of lines of code
I Easy to learn vs Steep learning curve
I Use Python + Java
O BJECTIVES I NTRODUCTION S YNTAX S TRINGS L ISTS D ICTIONARY L OOPS F UNCTIONS I MPORT &F UTURE T OPICS

where is Python used


I Used extensively in web - Django, TurboGears, Plone, etc
I Communicating with Databases - MySQL, Oracle,
MongoDB, etc
I Desktop GUI - GTK+, QT, TK, etc
I Scientific computing - SciPy, Scientific Python, etc
I Software Development - SCons, Buildbot, Roundup, etc
I Games 3D graphics - Pygame, PyKyra, etc
I For success stories -
https://www.python.org/about/success
O BJECTIVES I NTRODUCTION S YNTAX S TRINGS L ISTS D ICTIONARY L OOPS F UNCTIONS I MPORT &F UTURE T OPICS

Download & Installation


I Latest releases - Python 2.7.9 & Python 3.4.3
I Python Interpreter
I Linux - Installed in all distro’s, else
https://www.python.org/downloads/source/
I Mac - Installed, else
https://www.python.org/downloads/mac-osx/
I Windows - Download from
https://www.python.org/downloads/
I Text Editor
I Linux - Vim, Gedit, Kate, Emacs, etc
I Mac - Vim, TextMate or any unix like editor
I Windows - Notepad++ or IDE
I Python Documentation - https://www.python.org/doc/
I Set editor to expand tab to 4 spaces
O BJECTIVES I NTRODUCTION S YNTAX S TRINGS L ISTS D ICTIONARY L OOPS F UNCTIONS I MPORT &F UTURE T OPICS

Ways to run python


I Interactive Interpreter (Classic command line interpreter or Python
Shell) - Run as a calculator or used to run a python program
I Script from command line - Used to run a python program
I Integrated Development Environment (IDE) - Eclipse, Netbeans, etc
Python programs
I Python programs and modules are written as text files
with .py extension
I Program - .py file executed directly as program (often
referred to as scripts)
I Module - .py file referenced via the import statement
I Write a simple print program and save as 'myFirst.py' and save on desktop
print "Hello, Python!"

I Run Python Shell 'C:\path..\myFirst.py'


O BJECTIVES I NTRODUCTION S YNTAX S TRINGS L ISTS D ICTIONARY L OOPS F UNCTIONS I MPORT &F UTURE T OPICS

Variables & Data types


I Variables
I Stores a piece of data and gives it a specific name
I Do not need to specify data type
I Equal sign (=) is used to assign values to variables
I Data Types
I Numbers - int,long,float,complex
I Boolean - True, False
I String
I List
I Tuple
I Dictionary
O BJECTIVES I NTRODUCTION S YNTAX S TRINGS L ISTS D ICTIONARY L OOPS F UNCTIONS I MPORT &F UTURE T OPICS

Indentation,Comments & Math operators


I Indentation
I Whitespace is used to structure the code instead of braces
I A tab - 4 spaces
I Comments
I Single line - #
I Multi-line - Not supported in Python but people use Triple quote.
I Math operators
I Addition (+),Substraction(-),Multiplication(*),Division(/)
I Modulus(%),Exponent(**),Floor Division (//)
I Exercise 1 (Run as calculator and a saved .py program)
Tip Calculator!!
Cost of meal = 54.76
Tax = 7.85%
Tip = 15%
Find cost after tax, tip, cost after tip, total cost
O BJECTIVES I NTRODUCTION S YNTAX S TRINGS L ISTS D ICTIONARY L OOPS F UNCTIONS I MPORT &F UTURE T OPICS

Strings
I Can be declared in single quotes (’ ’) or double quotes (” ”)
or triple quotes (””” ””” or ''' ''')
singleQuote = 'One Line'
doubleQuote = ”One Line with ' eg. Jame's”
tripleQuote = """Span
multiple lines"""
I Each character can be accessed by using their index. Index
starts from zero(0)
I Consider ”Python”
PYTHON
P will be at 0th position of string and N will be at 5th
position from the start
I Strings are ”immutable”
I Immutable means that we cannot change the value. If we have
an instance of the String class, any method you call which
seems to modify the value, will actually create a new string.
O BJECTIVES I NTRODUCTION S YNTAX S TRINGS L ISTS D ICTIONARY L OOPS F UNCTIONS I MPORT &F UTURE T OPICS

String Methods
Let our string variable be called ’var’
I Length of string - len(var)
I Convert to string - str(var)
I Convert to lowercase - var.lower()
I Convert to uppercase - var.upper()
I Is digit/Is alpha - var.isdigit()/var.isalpha()
I Replace characters - var.replace(old,new)
I Split a sentence - var.split(delimiter)
I Swap case - var.swapcase()
I Range slice - var[start index:end index]
O BJECTIVES I NTRODUCTION S YNTAX S TRINGS L ISTS D ICTIONARY L OOPS F UNCTIONS I MPORT &F UTURE T OPICS

String Concatenation Formatting


I Concatenation
I Combining of strings is done by using the (+) operator
between them
I In order to combine a string with a non-string variable, use
str() method to convert non-strings to strings.
I Formatting
The string format operator is %
I %c - character
I %s - string conversion via str() prior to formatting
I %d - signed decimal integer
I %x %X - hexadecimal integer(lowercase/uppercase)
I %f - floating point real number
O BJECTIVES I NTRODUCTION S YNTAX S TRINGS L ISTS D ICTIONARY L OOPS F UNCTIONS I MPORT &F UTURE T OPICS

Lists
I It is a datatype you can use to store a collection of different
pieces of information as a sequence under a single variable
name
I Can be accessed by index
I Creating lists - Putting different comma separated values
within square brackets
list1 = [”physics”,”astronomy”,56.98,”MJ”,-9.36]
I Accessing values - Individual elements or a range of
elements
list1[3];list1[-2];list1[1:4];list1[-3:]
I Updating lists - Update single or multiple entries in a list
list1[2] = ”Botany 101”
I Negative index represents access from the right starting from -1
list1[-2] = ”MJ”
O BJECTIVES I NTRODUCTION S YNTAX S TRINGS L ISTS D ICTIONARY L OOPS F UNCTIONS I MPORT &F UTURE T OPICS

A tad bit more


I Deleting elements - Either use del statement or remove()
method
list1 = [”physics”,”astronomy”,56.98,”MJ”,-9.36]
del list1[3] - when you know the index of the element
list1.remove(”physics”) - when you don’t know the index
of the element
I Other List operations
I Length - len([3,4,5,”supernova”,”jaguar”])
I Concatenation - [1,2,3] + [5,6,7] = [1,2,3,5,6,7]
I Repetition-
[”hi”,”bye”]*3 = [”hi”,”bye”,”hi”,”bye”,”hi”,”bye”]
I Membership(returns Boolean) - 56.98 in list1
O BJECTIVES I NTRODUCTION S YNTAX S TRINGS L ISTS D ICTIONARY L OOPS F UNCTIONS I MPORT &F UTURE T OPICS

List Methods
Let our list variable be called ’list1’
I Length of the list - len(list1)
I Maximum/Minimum value - max(list1)/min(list1)
I Append object to list - list1.append(obj)
I Frequency of object - list1.count(obj)
I Return index - list1.index(obj)
I Insert object - list1.insert(index,obj)
I Delete object - list1.pop()/list1.remove(obj)
I Reverse the list - list1.reverse()
ISort the list(natural order) - list1.sort()
Tuples
Tuples are sequences, just like lists except.
I Tuples are immutable - cannot be changed or updated unlike lists
I Tuples use parentheses (), whereas lists use square brackets []
O BJECTIVES I NTRODUCTION S YNTAX S TRINGS L ISTS D ICTIONARY L OOPS F UNCTIONS I MPORT &F UTURE T OPICS

Dictionary
I Similar to a list by values are accessed by looking up a key
instead of an index
I A key can be a string or number
I Creating dictionaries -key-value pairs are separated by (:),
items are separated by (,) and everything is enclosed in
curly braces
dict1 = {”name”:”Daniel”,”age”:23,”degree”:”MS”}
dict2 = {’name’:”Ian Callum”,’age’:60,
’job’:”Car designer”,
’brand’:”Jaguar”,
’worked-for’:[”Ford”,”TWR”,”Aston Martin”]}
O BJECTIVES I NTRODUCTION S YNTAX S TRINGS L ISTS D ICTIONARY L OOPS F UNCTIONS I MPORT &F UTURE T OPICS

Some more
I Accessing values - Values can be accessed only through
keys
dict1[’age’] - 23
dict2[’brand’] - Jaguar
I Updating dictionary - Add new entry or modify an
existing entry
dict1[’subjects’] = [”OS”,”DBMS”,”Artificial Intelligence”]
dict2[’worked-for’][1]=”Tom Walkinshaw Racing”
I Deleting dictionary elements - 3 variations
dict1 = {”Sayuri”:556-2365,”ken”:556-8749,
”Tom”:556-5800}
del dict[’Sayuri’] - Removes entry with key ’Sayuri’
dict.clear() - Removes all entries in the dictionary
del dict - Deletes entire dictionary
O BJECTIVES I NTRODUCTION S YNTAX S TRINGS L ISTS D ICTIONARY L OOPS F UNCTIONS I MPORT &F UTURE T OPICS

Dictionary Methods
Let our dictionary variable be called ’dict1’
I Length of the dictionary - len(dict1)
I Shallow copy - dict1.copy()
I For key,return value - dict1.get(key)
I Check for key (returns boolean) - dict1.has key(key)
I List of k-v pairs - dict1.items()
I List of keys - dict1.keys()
I List of values - dict1.values()
O BJECTIVES I NTRODUCTION S YNTAX S TRINGS L ISTS D ICTIONARY L OOPS F UNCTIONS I MPORT &F UTURE T OPICS

Control Flow
I Comparison Operators
I Equal to (==)
I Not equal to (!=)
I Less than (<)
I greater than (>)
I greater than or equal to (>=)
I less than or equal to (<=)
I Logical Operators
I Logical AND (and)
I Logical OR (or)
I Logical NOT (not)
I Note: Precedence:- not >and >or
O BJECTIVES I NTRODUCTION S YNTAX S TRINGS L ISTS D ICTIONARY L OOPS F UNCTIONS I MPORT &F UTURE T OPICS

If and else decisions


I If statement - Consists of a Boolean expression followed by
one or more statements
if<condition >:
statement(s)
I If...else statement-If statement followed by an optional else
statement which executes when the Boolean expression is
false
if<condition >:
statement(s)
else :
statement(s)
O BJECTIVES I NTRODUCTION S YNTAX S TRINGS L ISTS D ICTIONARY L OOPS F UNCTIONS I MPORT &F UTURE T OPICS

If,elif and else decisions


I If...elif...else statement Otherwise if the following
expression is true, do this!
if <condition >:
statement(s)
elif <condition >:
statement(s)
else:
statement(s)
O BJECTIVES I NTRODUCTION S YNTAX S TRINGS L ISTS D ICTIONARY L OOPS F UNCTIONS I MPORT &F UTURE T OPICS

Exercise 2
Program to generate 6+2 UC id for a given name.(6+2 ID takes
the first 6 letters from the last name & first and last letters from
the first name)
I Store the first and last names in two different variables.
I Check if the length of the last name is <6 or not.
If < 6, pick first letters of first name to make up for the length
the last name.
I Accordingly, make use of slicing and concatenate the
letters to give the 6+2 ID.
Hint for taking input
Python 2 -> var =input('enter value') # will convert and return number
var =raw_input('enter value') # will return string
Python 3 -> var =input('enter value') # will return string
var =raw_input('enter value') # not available
O BJECTIVES I NTRODUCTION S YNTAX S TRINGS L ISTS D ICTIONARY L OOPS F UNCTIONS I MPORT &F UTURE T OPICS

While loop
I While loop will execute as long as the looping condition is
satisfied or True.
while <loop condition>:
statement(s)
I Infinite loop-Occurs when
I Loop condition cannot possibly be wrong (while 1!=2:)
I Logic of the loop prevents the loop condition from
becoming false
count = 10
while count>0 :
count += 1
O BJECTIVES I NTRODUCTION S YNTAX S TRINGS L ISTS D ICTIONARY L OOPS F UNCTIONS I MPORT &F UTURE T OPICS

While loop
I Break statement - One liner which means, ”exit the current
loop”
count = 0
while True :
Print count
count +=1
if count >= 10:
break
O BJECTIVES I NTRODUCTION S YNTAX S TRINGS L ISTS D ICTIONARY L OOPS F UNCTIONS I MPORT &F UTURE T OPICS

While/else loop
I A feature very unique to Python
I The ’else’ block executes when either
I Loop is never entered
I Loop exits normally
I The ’else’ block does not execute when, the loop exits as a result
of a break
import random #will explain import in latter slide
count = 0
while count<3:
num = random.randint(1,6)
print num
if num == 5:
print ”sorry, you lose!”
break
count +=1
else:
print ”You win!”
O BJECTIVES I NTRODUCTION S YNTAX S TRINGS L ISTS D ICTIONARY L OOPS F UNCTIONS I MPORT &F UTURE T OPICS

For loop
I Each item in the sequence is assigned to the iterating
variable and the statements are executed until the entire
sequence is exhausted
for <iterating var>in <sequence>:
statement(s)
I Iterating over a range of values
I for letter in 'string':
print letter
I for num in range(10):
print num
I for num in range(-6,6):
print num
I for num in range(-10,-100,-30):
print num
I for fruit in ['bannana', 'orange']:
print fruit
O BJECTIVES I NTRODUCTION S YNTAX S TRINGS L ISTS D ICTIONARY L OOPS F UNCTIONS I MPORT &F UTURE T OPICS

More Iterations
I Iterating a string
for letter in ”Monty Python!” :
print ”Current letter:”, letter
I Iterating a list
list1 = [”F-type”,”C-X75”,”XJ-13”]
for index in range(len(list1)):
print ”current model: ”,list1[index]
I Iterating a dictionary
dict1 = {’name’:”Bob”,’age’:34,’dob’:”6-25-1990” }
for keys in dict1.keys():
print ”Value of ”+keys+” :%s” %dict1[keys]
O BJECTIVES I NTRODUCTION S YNTAX S TRINGS L ISTS D ICTIONARY L OOPS F UNCTIONS I MPORT &F UTURE T OPICS

For/else loop
I A feature very unique to Python just like while /else
I The ’else’ block executes when the loop exits normally
I Does not execute when, the loop exits as a result of a break
fruits = [’banana’,’apple’,’orange’,’tomato’,’pear’]
print ’You have...’
for f in fruits:
if f == ’tomato’:
print ’A tomato is not a fruit!’
break
print ’A’,f
else:
print ’A fine selection of fruits!’
O BJECTIVES I NTRODUCTION S YNTAX S TRINGS L ISTS D ICTIONARY L OOPS F UNCTIONS I MPORT &F UTURE T OPICS

Exercise 3
DNA Transcription - The process of converting DNA to RNA
Example :
G->C;C->G;A->T;T->A
Input: GCTAGCCTACG
Output: CGATCGGATGC
Hint: Use ”for” loop to traverse the DNA string. Use ”if...else”
construct to check and replace each letter in the string.
O BJECTIVES I NTRODUCTION S YNTAX S TRINGS L ISTS D ICTIONARY L OOPS F UNCTIONS I MPORT &F UTURE T OPICS

Function Definition
I It is a block of organized, reusable code that is used to
perform an action
I Defining a Function
I Begins with keyword ’def’ followed by the function name
and parentheses
I Any input parameter/arguments should be placed within
these parentheses
I Code block starts with colon (:) and is indented
I return [expression] statement exits a function, optionally
passing back an expression to the caller
def function name(parameters):
”function docstring”
function suite
return [expression]
O BJECTIVES I NTRODUCTION S YNTAX S TRINGS L ISTS D ICTIONARY L OOPS F UNCTIONS I MPORT &F UTURE T OPICS

Calling a Function
I After the basic structure is finalized, we can execute by
either
I Calling it from another function
I Calling it directly from command prompt
I Called function
def printme(str):
”This prints a string passed into the function”
print str
return :

#Function call
printme(’First call to user defined function’)
printme(’Second call to user defined function’)
O BJECTIVES I NTRODUCTION S YNTAX S TRINGS L ISTS D ICTIONARY L OOPS F UNCTIONS I MPORT &F UTURE T OPICS

Importing Modules
I Module is a file that contains definitions - including
variables and functions - that you can use once it is
imported
I Generic import - Import only a module
Syntax: import module l[,module 2[,...module N]
Usage: import math,support
I Function import-Import specific attributes from a module
Syntax: from module name import
name 1[,name 2[,....name N]
Usage: from math import sqrt,pow
O BJECTIVES I NTRODUCTION S YNTAX S TRINGS L ISTS D ICTIONARY L OOPS F UNCTIONS I MPORT &F UTURE T OPICS

More Importing
I Universal import - Import all variables and functions in a
module
Syntax: from module name import *
Usage: import math import *
I dir() Function - Return a sorted list of strings containing
names defined in a module
import math
content = dir(math)
print content
O BJECTIVES I NTRODUCTION S YNTAX S TRINGS L ISTS D ICTIONARY L OOPS F UNCTIONS I MPORT &F UTURE T OPICS

Advanced Topics
I File input&output
I Exceptions
I Classes&Objects
I Regular Expressions
I Database Access
I Multithreading
O BJECTIVES I NTRODUCTION S YNTAX S TRINGS L ISTS D ICTIONARY L OOPS F UNCTIONS I MPORT &F UTURE T OPICS

Helpful hints&resources
I CEAS Library Python resources
I http://guides.libraries.uc.edu/python
I Online links & tutorials
I Python documentation - https://www.python.org/doc/
I Python Programming wiki book -
http://en.wikibooks.org/wiki/Python Programming
I Python tutorials - Udemy, Code academy, etc
O BJECTIVES I NTRODUCTION S YNTAX S TRINGS L ISTS D ICTIONARY L OOPS F UNCTIONS I MPORT &F UTURE T OPICS

Questions ??
O BJECTIVES I NTRODUCTION S YNTAX S TRINGS L ISTS D ICTIONARY L OOPS F UNCTIONS I MPORT &F UTURE T OPICS

Thank you for attending the workshop !!


Your kind suggestions/feedbacks are more than welcome

You might also like