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

Python Presentation 1

The document serves as an introductory guide to Python, covering its installation, basic operations, data types, and key programming concepts such as functions, classes, and inheritance. It highlights the differences between Python 2.x and 3.x, and provides examples of data structures like lists, tuples, and dictionaries, along with control flow statements. Additionally, it touches on socket programming and networking concepts, emphasizing the differences between TCP and UDP protocols.
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
4 views

Python Presentation 1

The document serves as an introductory guide to Python, covering its installation, basic operations, data types, and key programming concepts such as functions, classes, and inheritance. It highlights the differences between Python 2.x and 3.x, and provides examples of data structures like lists, tuples, and dictionaries, along with control flow statements. Additionally, it touches on socket programming and networking concepts, emphasizing the differences between TCP and UDP protocols.
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 64

Python

Contents

• Introduction to Python
• Installing python
• Numbers, variables & basic operations
• Data Types – Lists, tuples & dictionary
• Various operators
• Defining functions
• Defining Classes
• Inheritance
What is Python ?

A dynamic, open source programming language with a focus on


simplicity and productivity. It has an
elegant syntax that is natural to read and easy to write.
There are so many programming Languages. Why Python ?
Why Python?

 Python is Simple & Beautiful

 Python is Object-Oriented
• Structure supports concepts as Polymorphism,
Operation overloading & Multiple Inheritance

 Python is Free (Open Source Language )


• Downloading & Installing Python is Free & Easy
• Source Code is easily Accessible

 Python is Portable & Powerful


• Runs virtually on every major Platforms used today
• Dynamic Typing, Built-in types & tools, Library
Utilities, Automatic Memory Management
There are two versions of Python currently available –

Python 2.x Python 3.x


Which version to use
Python2 or Python3?
Lets see the basic differences-

Python 2.x is legacy, Python 3.x is the present and future of the language.

The most visible difference is probably the way the “print” statement
works.
In python2 it’s a statement
print “Hello World!”

In Python3 it’s a function


print(“Hello World!”)
Getting Started with Python
Type the following text at the Python prompt and press the Enter:

>>> print "Hello, Python!“

If you are running new version of Python, then you would need to use print
statement with parenthesis as in

print ("Hello, Python!")

However in Python version 2.4.3, this produces the following result:

Hello, Python!
Python Strings:

Strings in Python are identified as a contiguous set of characters in between


quotation marks.

str = 'Hello World!'

Print(str) # Prints complete string


print(str[0]) # Prints first character of the string
Print(str[2:5]) # Prints characters starting from 3rd to 6th
print(str[2:]) # Prints string starting from 3rd character
print(str * 2) # Prints string two times
print(str + "TEST“) # Prints concatenated string
Python Lists:

Lists are the most versatile of Python's compound data types. A list contains
items separated by commas and enclosed within square brackets ([]).

list1 = [ ‘hello', 786 , 4.1, ‘Ram', 702 ]


list2 = [123, ‘Victor']

print(list1) # Prints complete list


print(list1[0]) # Prints first element of the list
print(list1[1:3]) # Prints elements starting from 2nd to 4th
print(list1[2:]) # Prints elements starting from 3rd element
print(list2 * 2) # Prints list two times
print(list1 + list2) # Prints concatenated lists
Positive and negative indices

>>> t = [23, ‘abc’, 4.56, [2,3], ‘def’]

Positive index: count from the left, starting with 0


>>> t[1]
‘abc’

Negative index: count from right, starting with –1


>>> t[-3]
4.56
Python Tuples:
A tuple is another sequence data type that is similar to the list. Unlike lists, however,
tuples are enclosed within parentheses.

tuple1 = ( ‘hello', 786 , 2.23, ‘victor', 70.2 )


tuple2 = (123, ‘jay')
print(tuple1) # Prints complete list
print(tuple1[0]) # Prints first element of the list
print(tuple1[1:3]) # Prints elements starting from 2nd to 4th
print(tuple1[2:]) # Prints elements starting from 3rd element
print(tuple2 * 2) # Prints list two times
print(tuple1 + tuple2) # Prints concatenated lists
Python Dictionary:
Python 's dictionaries consist of key-value pairs.

dict1 = {'name': 'john','code':6734, 'dept': 'sales'}

print(dict1['name’]) # Prints value for 'one' key


print(dict['code’]) # Prints value for 2 key
print(dict1) # Prints complete dictionary
print(dict1.keys()) # Prints all the keys
Print(dict1.values()) # Prints all the values
The ‘in’ Operator
• Boolean test whether a value is inside a container:
>>> t = [1, 2, 4, 5]
>>> 3 in t
False
>>> 4 in t
True
>>> 4 not in t
False
• For strings, tests for substrings
>>> a = 'abcde'
>>> 'c' in a
True
>>> 'cd' in a
True
>>> 'ac' in a
False
• Be careful: the in keyword is also used in the syntax of for loops and list
comprehensions
Lists are mutable

>>> li = [‘abc’, 23, 4.34, 23]


>>> li[1] = 45
>>> li
[‘abc’, 45, 4.34, 23]
• We can change lists in place.
• Name li still points to the same memory reference when
we’re done.
Tuples are immutable
>>> t = (23, ‘abc’, 4.56, (2,3), ‘def’)
>>> t[2] = 3.14
Traceback (most recent call last):
File "<pyshell#75>", line 1, in -toplevel-
tu[2] = 3.14
TypeError: object doesn't support item assignment

• You can’t change a tuple.


• You can make a fresh tuple and assign its reference to a
previously used name.
>>> t = (23, ‘abc’, 3.14, (2,3), ‘def’)
• The immutability of tuples means they’re faster than lists.
Operations on Lists Only

>>> li = [1, 11, 3, 4, 5]

>>> li.append(‘a’) # Note the method syntax


>>> li
[1, 11, 3, 4, 5, ‘a’]

>>> li.insert(2, ‘i’)


>>>li
[1, 11, ‘i’, 3, 4, 5, ‘a’]
Operations on Lists Only

Lists have many methods, including index, count, remove,


reverse, sort
>>> li = [‘a’, ‘b’, ‘c’, ‘b’]
>>> li.index(‘b’) # index of 1st occurrence
1
>>> li.count(‘b’) # number of occurrences
2
>>> li.remove(‘b’) # remove 1st occurrence
>>> li
[‘a’, ‘c’, ‘b’]
If else structure

if expression1:
statement(s)
elif expression2:
statement(s)
elif expression3:
statement(s)
else:
statement(s)
For loop

for iterating_var in sequence:


statements(s)
While loop

while expression:
statements(s)
Defining Functions

Argument Return
Function
Defining Functions

def functionname( parameters ):


"function_docstring"
function_suite
return [expression]

Example:
def printme( str ):
"This prints a passed string into this function"
print(str)
return
Class

>>> class person:


def sayhi(self):
print(‘Hello, How are you?’)
>>> p=person()
>>> p.sayhi()
Hello, How are you?
Inheritance :
>>> class A:
def hello(self):
print(‘I am Super Class’)
>>> class B(A):
def bye(self):
print(‘I am Sub Class’)

>>> p=B()
>>> p.hello()
I am Super Class
>>> p.bye()
I am Sub Class
Using in-built Modules

>>> import time


>>> print(‘The sleep started’)
The Sleep started
>>> time.sleep(3)
>>> print(‘The sleep Finished’)
The sleep Finished
Serial Communication

Import serial

Ser=serial.Serial(‘COM4’,9600)

#for reading serial data


print(ser.readline())

# for sending serial data


Ser.write(‘s’)
Python Arithmetic Operators
Operator Description Example
+ Addition Adds values on either side of the operator. a + b = 30
Subtracts right hand operand from left hand operand. a – b = -10
- Subtraction

* Multiplication Multiplies values on either side of the operator a * b = 200


/ Division Divides left hand operand by right hand operand b/a=2
Divides left hand operand by right hand operand and b%a=0
% Modulus
returns remainder
Performs exponential (power) calculation on operators a**b =10 to the power 20
** Exponent

Floor Division - The division of operands where the 9//2 = 4 and 9.0//2.0 = 4.0, -11//3 = -4, -
result is the quotient in which the digits after the 11.0//3 = -4.0
decimal point are removed. But if one of the operands
// is negative, the result is floored, i.e., rounded away
from zero (towards negative infinity):
Python Comparison Operators
Operator Description Example
If the values of two operands are equal, then the condition
== (a == b) is not true.
becomes true.
If values of two operands are not equal, then condition
!=
becomes true.
If the value of left operand is greater than the value of right
> (a > b) is not true.
operand, then condition becomes true.
If the value of left operand is less than the value of right
< (a < b) is true.
operand, then condition becomes true.
If the value of left operand is greater than or equal to the
>= (a >= b) is not true.
value of right operand, then condition becomes true.
If the value of left operand is less than or equal to the value
<= (a <= b) is true.
of right operand, then condition becomes true.
Python Assignment Operators
Operator Description Example
Assigns values from right side operands to left side c = a + b assigns value of a + b into
=
operand c
It adds right operand to the left operand and assign the
+= Add AND c += a is equivalent to c = c + a
result to left operand

It subtracts right operand from the left operand and assign


-= Subtract AND c -= a is equivalent to c = c - a
the result to left operand

It multiplies right operand with the left operand and assign


*= Multiply AND c *= a is equivalent to c = c * a
the result to left operand

It divides left operand with the right operand and assign c /= a is equivalent to c = c / ac /= a
/= Divide AND
the result to left operand is equivalent to c = c / a

%= Modulus It takes modulus using two operands and assign the result
c %= a is equivalent to c = c % a
AND to left operand
Python Logical Operators
Operator Description Example

If both the operands are true then condition


and Logical AND (a and b) is true.
becomes true.

If any of the two operands are non-zero then


or Logical OR (a or b) is true.
condition becomes true.

not Logical NOT Used to reverse the logical state of its operand. Not(a and b) is false.
Python Membership Operators
Operator Description Example
Evaluates to true if it finds a variable in
x in y, here in results in a 1 if x is a member
in the specified sequence and false
of sequence y.
otherwise.
Evaluates to true if it does not find a
x not in y, here not in results in a 1 if x is
not in variable in the specified sequence and
not a member of sequence y.
false otherwise.
NUMBERS
Python Number Conversion
– Type int(x) to convert x to a plain integer.
– Type long(x) to convert x to a long integer.
– Type float(x) to convert x to a floating-point number.
– Type complex(x) to convert x to a complex number
with real part x and imaginary part zero.
– Type complex(x, y) to convert x and y to a complex
number with real part x and imaginary part y. x and y
are numeric expressions
NUMBERS
String Parsing
• Print("My name is %s and weight is %d kg!" % ('Zara', 21) )
Format Symbol Conversion
%c character
%s string conversion via str() prior to formatting
%i signed decimal integer
%d signed decimal integer
%u unsigned decimal integer
%o octal integer
%x hexadecimal integer (lowercase letters)
%X hexadecimal integer (UPPERcase letters)
%e exponential notation (with lowercase 'e')
%E exponential notation (with UPPERcase 'E')
Sets
• A set contains an unordered collection of unique and immutable objects.
The set data type is, as the name implies, a Python implementation of the
sets as they are known from mathematics. This explains, why sets unlike
lists or tuples can't have multiple occurrences of the same element.
>>> adjectives = {"cheap","expensive","inexpensive","economical"}
>>> adjectives
set(['inexpensive', 'cheap', 'expensive', 'economical']) >>>

>>> x = set("A Python Tutorial")


>>> x
set(['A', ' ', 'i', 'h', 'l', 'o', 'n', 'P', 'r', 'u', 't', 'a', 'y’, 'T'])

>>> cities = set(("Paris", "Lyon", "London","Berlin","Paris","Birmingham"))


>>> cities
set(['Paris', 'Birmingham', 'Lyon', 'London', 'Berlin']) >>>
This Week
• Socket Programming – Networking with python
• Email Access
• Web Access
• MySQL Integration
• Os, timieit, math and shutil
• Python Regular Expressions
• Testing with python
Socket Programming –?
• Sockets are the endpoints of a bidirectional communications
channel. Sockets may communicate within a process,
between processes on the same machine, or between
processes on different continents.
• Sockets may be implemented over a number of different
channel types: Unix domain sockets, TCP, UDP, and so on.
The socket library provides specific classes for handling the
common transports as well as a generic interface for
handling the rest.
TCP UDP
TCP is a connection-oriented protocol UDP is a connectionless protocol.
TCP is suited for applications that require UDP is suitable for applications that need
high reliability, and transmission time is fast, efficient transmission, such as
relatively less critical. games. UDP's stateless nature is also
useful for servers that answer small
queries from huge numbers of clients.
HTTP, HTTPs, FTP, SMTP, Telnet DNS, DHCP, VOIP.
The speed for TCP is slower than UDP. UDP is faster because error recovery is
not attempted. It is a "best effort"
protocol.
There is absolute guarantee that the data There is no guarantee that the messages
transferred remains intact and arrives in or packets sent would reach at all.
the same order in which it was sent.
Socket programming using TCP
domain
The family of protocols that is used as the transport
mechanism. These values are constants such as AF_INET,
PF_INET, PF_UNIX, PF_X25, and so on.
type
The type of communications between the two endpoints,
typically SOCK_STREAM for connection-oriented
protocols and SOCK_DGRAM for connectionless
protocols.
Server socket method
• s.bind()
This method binds address (hostname, port number pair)
to socket.
• s.listen()
This method sets up and start TCP listener.
• s.accept()
This passively accept TCP client connection, waiting until
connection arrives (blocking).
Client socket method
• s.connect()
This method actively initiates TCP server
connection
Genral socket programming
s.recv()
• This method receives TCP message
s.send()
• This method transmits TCP message
s.recvfrom()

• This method receives UDP message


s.sendto()
• This method transmits UDP message
s.close()
• This method closes socket
socket.gethostname()
• Returns the hostname.
Exceptions - Python
• Python provides two very important features to handle any
unexpected error in your Python programs and to add
debugging capabilities in them:

• Exception Handling
• Assertions:
What is Exception?
• An exception is an event, which occurs during the execution of a
program that disrupts the normal flow of the program's instructions. In
general, when a Python script encounters a situation that it cannot
cope with, it raises an exception. An exception is a Python object that
represents an error.

• When a Python script raises an exception, it must either handle the


exception immediately otherwise it terminates and quits.
os
• The main purpose of the OS module is to interact with your operating
system. The primary use is to create folders, remove folders, move
folders, and sometimes change the working directory.
RE
• Identifiers:
• \d = any number
• \D = anything but a number
• \s = space
• \S = anything but a space
• \w = any letter
• \W = anything but a letter
• . = any character, except for a new line
• \b = space around whole words
• \. = period. must use backslash, because . normally means any character.
RE
• Modifiers:
• {1,3} = for digits, u expect 1-3 counts of digits, or "places"
• + = match 1 or more
• ? = match 0 or 1 repetitions.
• * = match 0 or MORE repetitions
• $ = matches at the end of string
• ^ = matches start of a string
• | = matches either/or. Example x|y = will match either x or y
• [] = range, or "variance"
• {x} = expect to see this amount of the preceding code.
• {x,y} = expect to see this x-y amounts of the precedng code
RE
• White Space Charts:
• \n = new line
• \s = space
• \t = tab
• \e = escape
• \f = form feed
• \r = carriage return
• Characters to REMEMBER TO ESCAPE IF USED!
• .+*?[]$^(){}|\
• Brackets:
• [] = quant[ia]tative = will find either quantitative, or quantatative.
• [a-z] = return any lowercase letter a-z
• [1-5a-qA-Z] = return all numbers 1-5, lowercase letters a-q and uppercase A-Z
Features and philosophy

• Python is a widely used high-level programming language for general-purpose programming,


created by Guido van Rossum and first released in 1991. An interpreted language, Python has a
design philosophy that emphasizes code readability, and a syntax that allows programmers to
express concepts in fewer lines of code than might be used in languages such as C++ or Java.
The language provides constructs intended to enable writing clear programs on both a small and
large scale.
Exercise
• Given an array of ints length 3, return an array with the elements "rotated left" so
[1, 2, 3] yields [2, 3, 1].

rotate_left3([1, 2, 3]) → [2, 3, 1]
rotate_left3([5, 11, 9]) → [11, 9, 5]
rotate_left3([7, 0, 0]) → [0, 0, 7]
solution
def rotate_left3(nums):
l=len(nums)
k=[]
for i in range(1,l):
k.append(nums[i])
k.append(nums[0])
return k
Exercise
• #Given 2 int arrays, a and b, each length 3, return a new array length 2 containing
their middle elements.
• middle_way([1, 2, 3], [4, 5, 6]) → [2, 5]
• middle_way([7, 7, 7], [3, 8, 0]) → [7, 8]
• middle_way([5, 2, 9], [1, 4, 5]) → [2, 4]
Exercise
#Given 2 arrays of ints, a and b, return True if they have the same first element or
they have the same last element. Both arrays will be length 1 or more.
common_end([1, 2, 3], [7, 3]) → True
common_end([1, 2, 3], [7, 3, 2]) → False
common_end([1, 2, 3], [1, 3]) → True
Exercise
#Given an array of ints, return True if the sequence of numbers 1, 2, 3
appears in the array somewhere.
array123([1, 1, 2, 3, 1]) → True
array123([1, 1, 2, 4, 1]) → False
array123([1, 1, 2, 1, 2, 3]) → True
solution
def array123(nums):
# Note: iterate with length-2, so can use i+1 and i+2 in the loop
for i in range(len(nums)-2):
if nums[i]==1 and nums[i+1]==2 and nums[i+2]==3:
return True
return False
Exercise
#Given a non-empty string like "Code" return a string like "CCoCodCode".
string_splosion('Code') → 'CCoCodCode’
string_splosion('abc') → 'aababc’
string_splosion('ab') → 'aab'
solution
def string_splosion(str):
result = ""
# On each iteration, add the substring of the chars 0..i
for i in range(len(str)):
result = result + str[:i+1]
return result
Exercise
The password generator

• Write a password generator in Python. Be creative with how you


generate passwords - strong passwords have a mix of lowercase
letters, uppercase letters, numbers, and symbols. The passwords
should be random, generating a new password every time the user
asks for a new password. Include your run-time code in a main
method.
• Extra:
• Ask the user how strong they want their password to be. For weak
passwords, pick a word or two from a list.
Exercise the hangman

• In the game of Hangman, a clue word is given by the program that the player has to
guess, letter by letter. The player guesses one letter at a time until the entire word has
been guessed. (In the actual game, the player can only guess 6 letters incorrectly
before losing).
• Let’s say the word the player has to guess is “EVAPORATE”. For this exercise, write the
logic that asks a player to guess a letter and displays letters in the clue word that were
guessed correctly. For now, let the player guess an infinite number of times until they
get the entire word. As a bonus, keep track of the letters the player guessed and
display a different message if the player tries to guess that letter again. Remember to
stop the game when all the letters have been guessed correctly!
• https://www.google.com/settings/security/lesssecureapps

You might also like