Location via proxy:   [ UP ]  
[Report a bug]   [Manage cookies]                
0% found this document useful (0 votes)
4 views

Introduction Python Operators

Uploaded by

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

Introduction Python Operators

Uploaded by

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

Introduction to Programming

with Python
What is Python
• Python is a very Popular Programming Language.

• It was Developed by Guido Van Rossum in 1991 at CWI


(centrum wiskunde & Informatica) Netherland.

• Python is a general purpose and High Level


Programming Language.

• Python is a dynamically typed, general purpose


programming language that supports an object-oriented
programming approach as well as a functional
programming approach.
Facts about Python
◼ Python’s methodologies can be used in a broad range of
applications.
◼ Bridging the Gap between abstract computing and real world
applications.
◼ Rising Demand for Python Programmers.
◼ Google, Nokia, Disney, Yahoo, IBM use Python.
◼ Not only a Scripting language, also supports Web
Development and Database Connectivity.
Features of Python

• Simple and easy to learn


• Platform-Independent
• Free and open source
• Interpreted
• Rich Library Support
• Embeddable and extensible
• Portable
• Robust
• Object - Oriented, procedural and functional.
• very readable and well structured code
Why Python
◼ Easy – to – learn.
◼ Code is 3-5 times shorter than Java.
◼ 5-10 times shorter than C++.
◼ Since it allows you to express very powerful ideas in very
few lines of code while being very readable.
◼ Therefore maintainability is high.
◼ Stepping Stone to Programming universe.
◼ Python code is often said to be almost like pseudocode.
Where Python is Used
• Web Frameworks and application.
• GUI based desktop application.
• Graphic design,image processing application,games
and scientific/computational applications
• ML,AI,Neural-Networks
• Data Science,Data visualization
• IOT
• Database development
➢ Who uses Python?
◼ Google

◼ PBS

◼ NASA

◼ Library of Congress

◼ Instagram

◼ Dropbox

◼ Pinterest

• ...the list goes on...


Internal working of
Python
• Python doesn’t convert its code into machine
code, something that hardware can understand.
It converts it into something called byte code. So
within Python, compilation happens, but it’s just
not in a machine language. It is into byte code
(.pyc or .pyo) and this byte code can’t be
understood by the CPU. So we need an
interpreter called the Python virtual machine to
execute the byte codes.
Python-Releases
◼ Python 1.0 - January 1994
◼ Python 1.5 - December 31, 1997

◼ Python 1.6 - September 5, 2000

◼ Python 2.0 - October 16, 2000


◼ Python 2.1 - April 17, 2001

◼ Python 2.2 - December 21, 2001

◼ Python 2.3 - July 29, 2003

◼ Python 2.4 - November 30, 2004

◼ Python 2.5 - September 19, 2006

◼ Python 2.6 - October 1, 2008

◼ Python 2.7 - July 3, 2010

◼ Python 3.0 - December 3, 2008


◼ Python 3.1 - June 27, 2009

◼ Python 3.2 - February 20, 2011

◼ Python 3.3 - September 29, 2012

◼ Python 3.4 - March 16, 2014

◼ Python 3.5 - September 13, 2015

◼ Python 3.6 - December 23, 2016


Installing Python
◼ Download Python from www.python.org
◼ Any version will do for this class
◼ By and large they are all mutually compatible
◼ Recommended version: 3.x ..latest version (32 bit or 64
bit)
◼ Recommended 64 bit
◼ Use IDLE or IDE
Interactive Shell-Python IDLE (GUI)
A Code Sample (in IDLE)
x = 34 - 23 # A comment.
y = “Hello” # Another one.
z = 3.45
if z == 3.45 or y == “Hello”:
x= x + 1
y = y + “ World” # String
concat.
print x
print y
Interactive Shell-Python Command Line
Data Type/variables/Assignment
Dynamic Typing-
▪ Java: statically typed
▪ Variables are declared to refer to objects of a given type
▪ Methods use type signatures to enforce contracts
▪ Python
▪ Variables come into existence when first assigned to
▪ A variable can refer to an object of any type
▪ All types are (almost) treated the same way
▪ Main drawback: type errors are only caught at
◼ runtime
Assignment
▪ Binding a variable in Python means setting a
name to hold a reference to some object.
▪ Assignment creates references, not copies (like Java)
▪ A variable is created the first time it appears on
the left side of an assignment expression:
x = 3
▪ An object is deleted (by the garbage collector).
▪ Names in Python do not have an intrinsic type.
Objects have types.
▪ Python determines the type of the reference automatically
based on what data is assigned to it.
(Multiple Assignment)
▪ You can also assign to multiple names at the same time.

>>> x, y = 2, 3
>>> x 2
>>> y
3
Variables
◼ variable: A named piece of memory that can store a value.
◼ Usage:
◼ Compute an expression's result,
◼ store that result into a variable,
◼ and use that variable later in the program.

◼ assignment statement: Stores a value into a variable.


◼ Syntax:
name = value

◼ Examples: x = 5
gpa = 3.14

x 5 gpa 3.14

◼ A variable that has been given a value can be used in expressions.


x + 4 is 9
Naming Rules
▪ Names are case sensitive and cannot start with a number.
They can contain letters, numbers, and underscores.
bob Bob _bob _2_bob_ bob_2 BoB
▪ There are some reserved words:
and, assert, break, class, continue, def, del,
elif, else, except, exec, finally, for, from,
global, if, import, in, is, lambda, not, or, pass,
print, raise, return, try, while
Everything is an object

◼ Everything means
>>> x = 7
everything, >>> x
including functions 7
>>> x = 'hello'
and classes (more >>> x
on this later!) 'hello'
>>>
◼ Data type is a

property of the
object and not of
the variable
Numbers: Integers

◼ Integer – the
equivalent of a C long >>> 132224
132224
◼ Long Integer – an
>>> 132323 **
unbounded integer 2
value. 17509376329L
>>>
Numbers: Floating Point

◼ int(x) converts x to >>> 1.23232


1.2323200000000001
an integer >>> print 1.23232
1.23232
◼ float(x) converts x
>>> 1.3E7
to a floating point 13000000.0
>>> int(2.0)
◼ The interpreter
2
shows >>> float(2)
a lot of digits 2.0
Numbers: Complex

◼ Built into Python


◼ Same operations are
>>> x = 3 + 2j
>>> y = -1j
supported as integer >>> x +y
and float (3+1j)
>>> x *y
(2-3j)
Numbers are immutable

x 4.5
>>> x = 4.5
>>> y=x y
>>> y += 3
>>> x x 4.5
4.5
y 7.5
>>> y
7.5
String Literals

◼ Strings are
immutable >>> x = 'hello'
>>> x = x + ' there'
◼ There is no char type >>> x
like in C++ or Java 'hello there'

◼ + is overloaded to do

concatenation
String Literals: Many Kinds
◼ Can use single or double quotes, and three
double quotes for a multi-line string
>>> 'I am a string'
'I am a string'
>>> "So am I!"
'So am I!'
>>> s = """And me too!
though I am much longer
than the others :)"""
'And me too!\nthough I am much longer\nthan the
others :)‘
>>> print s
And me too!
though I am much longer
than the others :)‘
Lists
◼ Ordered collection of
data
>>> x = [1,'hello', (3 + 2j)]
◼ Data can be of >>> x
[1, 'hello', (3+2j)]
different types >>> x[2]
◼ Lists are mutable (3+2j)
>>> x[0:2]
◼ Issues with shared [1, 'hello']

references and
mutability
◼ Same subset

operations as Strings
Tuples

◼ Tuples are immutable


• versions of lists
◼ One strange point is the format>>> x = (1,2,3)
to make a tuple with
>>> x[1:]
one element: (2, 3)
• ‘,’ is needed to differentiate from
>>>
theymathematical
= (2,)
>>> y
expression (2) (2,)
>>>
Dictionaries

◼ A set of key-value pairs


◼ Dictionaries are mutable

>>> d = {1 : 'hello', 'two' : 42, 'blah' :


[1,2,3]}
>>> d
{1: 'hello', 'two': 42, 'blah': [1, 2, 3]}
>>> d['blah']
[1, 2, 3]
Data Type Summary

◼ Lists, Tuples, and Dictionaries can store


any type (including other lists, tuples,
and dictionaries!)
◼ Only lists and dictionaries are mutable

◼ All variables are references


Data Type Summary
◼ Integers: 2323, 3234L
◼ Floating Point: 32.3, 3.1E2
◼ Complex: 3 + 2j, 1j
◼ Lists: l = [ 1,2,3]
◼ Tuples: t = (1,2,3)
◼ Dictionaries: d = {‘hello’ : ‘there’, 2 : 15}
Input

◼ The input(string) method returns a line


of user input as a string
◼ The parameter is used as a prompt

◼ The string can be converted by using the

conversion methods int(string) converts


to int, float(string) converts to float or
eval(string) converts and evaluates
expressions etc.
Comments
Multiline Statements
Expressions
◼ expression: A data value or set of operations to compute a value.
Examples: 1 + 4 * 3
42

◼ Arithmetic operators we will use:


+ - * / addition, subtraction/negation, multiplication, division
% modulus, a.k.a. remainder
** exponentiation

◼ precedence: Order in which operations are computed.


◼ * / % ** have a higher precedence than + -
1 + 3 * 4 is 13

◼ Parentheses can be used to force a certain order of evaluation.


(1 + 3) * 4 is 16
Math commands
◼ Python has useful commands for performing calculations.
Command name Description Constant Description
abs(value) absolute value e 2.7182818...
ceil(value) rounds up pi 3.1415926...
cos(value) cosine, in radians
floor(value) rounds down
log(value) logarithm, base e
log10(value) logarithm, base 10
max(value1, value2) larger of two values
min(value1, value2) smaller of two values
round(value) nearest whole number
sin(value) sine, in radians
sqrt(value) square root

◼ To use many of these commands, you must write the following at


the top of your Python program:
from math import *
print
◼ print : Produces text output on the console.

◼ Syntax:
print "Message"
print Expression
◼ Prints the given text message or expression value on the console, and
moves the cursor down to the next line.
print Item1, Item2, ..., ItemN
◼ Prints several messages and/or expressions on the same line.

◼ Examples:
print("Hello, world!“)
age = 45
print ("You have", 65 - age, "years until retirement“)
Output:
Hello, world!
You have 20 years until retirement
How many ways for print in python

• 1- Using Print() function- The most common way to


output text to the console.

• print("Hello, world!")

• 2- Using sys.stdout.write()- Directly writes text to the


standard output (console), similar to print() but without
automatic newline.

• import sys
• sys.stdout.write("Hello, world!\n")
• 3-Format method-
• name = "world"
• print("Hello, {}!".format(name))

• 4-Using f-Strings (Python 3.6+):Allows


embedding expressions inside string literals, using
curly braces {}.
• name = "world" print(f"Hello, {name}!")
• 5-Using str() join: Joins a list of strings into a
single string with a specified separator.

• parts = ["Hello", "world!"]


• print(" ".join(parts))
Operator
Different forms of Operator
Types Of Operators
Arithmetic Operators
Example of Arithmatic
Operator
Relational Operators
Example of Relational
Operator
Assignment Operators
Bitwise Operators
Logical Operators
Example of Relational
Operator
Membership & Identity
Example of Membership
Operator
Example of Identity Operator
id() function
type() Function
Operator Precedence and Associativity

Operator Precedence –
• Determines which operations are performed first when
multiple operators are present in an expression.

Associativity-
Defines the order in which operators of the same
precedence level are evaluated (left-to-right or right-to-
left).
Examples
• Ex-1
• result = 5 + 3 * 2
• print(result) # Output: 11

• Ex-2
• result = 5 > 3 and 4 < 6
• print(result) # Output: True

• Ex-3
• result = 20 // 5 * 2
• print(result) # Output: 8

• Ex-4
• result = 2 ** 3 ** 2
• print(result) # Output: 512

You might also like