Introduction Python Operators
Introduction Python Operators
with Python
What is Python
• Python is a very Popular Programming Language.
◼ PBS
◼ NASA
◼ Library of Congress
◼ Dropbox
>>> 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.
◼ Examples: x = 5
gpa = 3.14
x 5 gpa 3.14
◼ 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
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
◼ 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
• print("Hello, world!")
• import sys
• sys.stdout.write("Hello, world!\n")
• 3-Format method-
• name = "world"
• print("Hello, {}!".format(name))
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