Python
Python
Arithmetic operators
used with numeric values to perform common mathematical
operations
Assignment operators
used to assign values to variables
Logical operators
used to combine conditional statements
Identity operators
used to compare the objects, not if they are equal, but if they are actually
the same object, with the same memory location
Bitwise operators
Bitwise operators are used to compare (binary) numbers
Zero fill left Shift left by pushing zeros in from the right
<<
shift and let the leftmost bits fall off
Shift right by pushing copies of the leftmost
Signed right
>> bit in from the left, and let the rightmost bits
shift
fall off
=============================================
As a matter of fact, everything in Python is an object. Each object has identity,
a type, and a value (given by the user / or a default value). The identity, in
Python, refers to the address and does not change. The type can be any of the
following.
None: This represents the absence of a value.
Numbers: Python has three types of numbers:
Integer: It does not have any fractional part
Floating Point: It can store number with a fractional part
Complex: It can store real and imaginary parts
Sequences: These are ordered collections of elements. There are three types of
sequences in Python:
String
Tuples
Lists
Numbers
Ceil: The ceiling of a given number is the nearest integer greater than or
equal to that number. For example, the ceiling of 2.678 is 3.
>>> import math
>>>math.ceil(2.678)
3
That of 2 is 2.
>>>math.ceil(2)
2
>>>
Copy sign: The sign of the second argument is returned along with the result
on the execution of this function.
math.copysign(x, y)
Return x with the sign of y.
On a platform that supports signed zeros, copy sign (1.0, – 0.0) returns –1.0.
Fabs: The absolute value of a number is its positive value
In Python, this task is accomplished with the function fabs (x).
The fabs(x) returns the absolute value of x.
>>>math.fabs(-2.45)
2.45
Factorial: The factorial of a number x is defined as the continued product of
the numbers from 1 to that value. That is:
Factorial(x) = 1 × 2 × 3 × … × n.
In Python, the task can be accomplished by the factorial function math.
factorial(x).
It returns the factorial of the number x. Also if the given number is not an
integer or is negative, then an exception is raised.
Floor: The floor of a given number is the nearest integer smaller than or
equal to that number. For example the floor of 2.678 is 2 and that of 2 is also
2.
>>> import math
>>>math.floor(2.678)
2
>>>math.floor(2)
2
>>>
Fractions
Python also provides the programmer the liberty to deal with fractions. The use
of fractions and decimals has been shown in the following listing.
from fractions import Fraction
print(Fraction(128, -26))
-64/13
================================================
STRINGS
A string is a sequence of characters.
Strings can be created by enclosing characters inside a single quote or double-
quotes. Even triple quotes can be used in Python but generally used to represent
multiline strings and docstrings.
Hello
Hello
Hello
Hello, welcome to
the world of Python
The index of -1 refers to the last item, -2 to the second last item and so on.
We can access a range of items in a string by using the slicing operator :
(colon).
str = programiz
str[0] = p
str[-1] = z
str[1:5] = rogr
str[5:-2] = am
If we try to access an index out of the range or use numbers other than an
integer, we will get errors.
We cannot delete or remove characters from a string. But deleting the string
entirely is possible using the del keyword.
The + operator does this in Python. Simply writing two string literals together
also concatenates them.
The * operator can be used to repeat the string for a given number of times.
# Python String Operations
str1 = 'Hello'
str2 ='World!'
# using +
print('str1 + str2 = ', str1 + str2)
# using *
print('str1 * 3 =', str1 * 3)
Writing two string literals together also concatenates them like + operator.
If we want to concatenate strings in different lines, we can use parentheses.
3 letters found
str = 'cold'
# enumerate()
list_enumerate = list(enumerate(str))
print('list(enumerate(str) = ', list_enumerate)
#character count
print('len(str) = ', len(str))
If we want to print a text like He said, "What's there?" , we can neither use single
quotes nor double quotes. This will result in a SyntaxError as the text itself
contains both single and double quotes.
One way to get around this problem is to use triple quotes. Alternatively, we
can use escape sequences.
\a ASCII Bell
\b ASCII Backspace
\f ASCII Formfeed
\n ASCII Linefeed
>>> print("C:\\Python32\\Lib")
C:\Python32\Lib
>>> print("This is printed\nin two lines")
This is printed
in two lines
>>> print("This is \x48\x45\x58 representation")
This is HEX representation
Raw String to ignore escape sequence
The format() method that is available with the string object is very versatile and
powerful in formatting strings. Format strings contain curly braces {} as
placeholders or replacement fields which get replaced.
We can use positional arguments or keyword arguments to specify the order.
# default(implicit) order
default_order = "{}, {} and {}".format('John','Bill','Sean')
print('\n--- Default Order ---')
print(default_order)
The format() method can have optional format specifications. They are
separated from the field name using colon. For example, we can left-justify < ,
right-justify > or center ^ a string in the given space.
We can also format integers as binary, hexadecimal, etc. and floats can be
rounded or displayed in the exponent format. There are tons of formatting you
can use. Visit here for all the string formatting available with
the format() method.
We can even format strings like the old sprintf() style used in C programming
language. We use the % operator to accomplish this.
>>> x = 12.3456789
>>> print('The value of x is %3.2f' %x)
The value of x is 12.35
>>> print('The value of x is %3.4f' %x)
The value of x is 12.3457
>>> "PrOgRaMiZ".lower()
'programiz'
>>> "PrOgRaMiZ".upper()
'PROGRAMIZ'
>>> "This will split all words into a list".split()
['This', 'will', 'split', 'all', 'words', 'into', 'a', 'list']
>>> ' '.join(['This', 'will', 'join', 'all', 'words', 'into', 'a', 'string'])
'This will join all words into a string'
>>> 'Happy New Year'.find('ew')
7
>>> 'Happy New Year'.replace('Happy','Brilliant')
'Brilliant New Year'