Operation Priority
Operation Priority
1. parentheses
2. power
3. unary minus
4. multiplication, division, and remainder
5. addition and subtraction
print (10 / 5 / 2) # 1.0
print(8 / 2 * 5) # 20.0
The expressions above may seem ambiguous to you, since they have alternative
solutions depending on the operation order: either 1.0 or 4.0 in the first example, and
either 20.0 or 0.8 in the second one. In such cases, Python follows a left-to-right
operation convention from mathematics. It's a good thing to know, so try to keep that
in mind, too!
PEP time!
There are a few things to mention about the use of binary operators, that
is, operators that influence both operands. As you know, readability matters in Python.
So, first, remember to surround a binary operator with a single space on both sides:
number= 30+12 # No!
number = 30 + 12 # It's better this way
Also, sometimes people use the break after binary operators. But this can hurt
readability in two ways:
# No: operators sit far away from their operands
income = (gross_wages +
taxable_interest +
(dividends - qualified_dividends) -
ira_deduction -
student_loan_interest)
Mathematicians and their publishers follow the opposite convention in order to solve
the readability problem. Donald Knuth explains this in his Computers and
Typesetting series: "Although formulas within a paragraph always break after binary
operations and relations, displayed formulas always break before binary operations".
Following this tradition makes the code more readable:
# Yes: easy to match operators with operands
income = (gross_wages
+ taxable_interest
+ (dividends - qualified_dividends)
- ira_deduction
- student_loan_interest)
In Python code, it is permissible to break before or after a binary operator, as long as
the convention is consistent locally. For new code, Knuth's style is suggested, according
to PEP 8.
multiply(1, 7)
Invoking print()
Hello, world!
Bye, then!
So, the first call prints one string, the second call of print without arguments prints, in
fact, an empty line, and the last call outputs our two messages as one expression. Are
you surprised by these results? Then you may learn how the print function works in
more detail from its documentation. The Python documentation contains all sorts of
information about the function of your interest, for example, which arguments it
expects.
Built-in functions
Functions can make life easier, provided one is aware of their existence. Many
algorithms are already written, so there is no need for reinvention, except perhaps for
educational purposes. The Python interpreter has a number of functions and types built
into it, so they are always available. Currently, the number of built-in functions amounts
to 69 (in the latest version Python 3.8). Some of them are used to convert the object
type, for example, str() returns a string, int() returns an integer, float() returns a
floating-point number. Others deal with numbers: you can round() them
and sum() them, find the minimum min() or the maximum max(). Still others give us
information about the object: its type() or length len(). Consider them in action:
number = "111"
# finding the length of an object
print(len(number)) # 3
# converting types
integer = int(number)
float_number = float(number)
print(str(float_number)) # "111.0"
# adding and rounding numbers
my_sum = sum((integer, float_number))
print(my_sum) # 222.0
print(round(my_sum)) # 222
# finding the minimum and the maximum
print(min(integer, float_number)) # 111
print(type(max(integer, float_number, my_sum))) # <class 'float'>
In our example, it is shown that len() counts the number of characters in the string (the
same goes for any sequence). Then we declare the
variables integer and float_number and write their sum into my_sum. By the way,
the sum() function also deals with sequences. The result is a floating-point number,
which becomes clear after printing my_sum. Furthermore, you can see how to find the
minimum and maximum values: the smallest number equals 111 and the largest
number 222.0 belongs to floats . There is far more to explore, but let's sum it up
Recap
The beauty of functions is that we can use them without clear insight into their inner
structure and how they manage to perform what we need. But if you want to put a
function to good use, make sure to check its documentation or try invoking the special
function help() with the name of the function in question wrapped in round brackets. It
may become necessary if, for example, the function does not return any value, writes
processed data to a file or prints the output on the screen.
functions are meant to be reusable, which means we are free to apply it multiple times
with different arguments,
to call a function write its name followed by parentheses and place the arguments within,
normally, a function has documentation, which sometimes might be of huge help.
Programs in which there's nothing to calculate are quite rare. Therefore, learning to program
with numbers is never a bad choice. Even more valuable skill we are about to learn is the
processing of user data. By means of it, you can create interactive and by far more flexible
applications. So let's get started!
Since you have become familiar with the input() function in Python, it's hardly new to
you that any data passed to this function is treated as a string. But how should we deal
with numerical values? As a general rule, they are explicitly converted to corresponding
numerical types:
integer = int(input())
floating_point = float(input())
Pay attention to current best practices: it's crucial not to name your variables as built-in
types (say, float or int). Yet another caveat is related to user mistakes. If a user writes an
inaccurate input, ValueError will occur. At the moment, we'll limit ourselves to this. But
not to worry, more information about errors is available in a dedicated topic. Now,
consider a more detailed and pragmatic example of handling numerical inputs.
magine you have a credit card with a free air miles bonus program (or maybe you already have
one). As a user, you are expected to input the amount of money you spend on average from this
card per month. Let's assume that the bonus program gives you 2 free air miles for every
dollar you spend. Here's a simple program to figure out when you can travel somewhere for
free:
Whenever you use an equal sign =, you actually assign some value to a name. For that
reason, = is typically referred to as an assignment operator. Meanwhile, there are other
assignment operators you can use in Python. They are also called compound
assignment operators, for they carry out an arithmetic operation and assignment in
one step. Have a look at the code snippet below:
# simple assignment
number = 10
number = number + 1 # 11
This code is equivalent to the following one:
# compound assignment
number = 10
number += 1 # 11
One can clearly see from the example that the second piece of code is more concise (for
it doesn't repeat the variable's name).
Naturally, similar assignment forms exist for the rest of arithmetic operations: -
=, *=, /=, //=, %=, **=. Given the opportunity, use them to save time and effort.
Consider this example where a user determines the value by which the counter is
increased:
counter = 1
step = int(input()) # let it be 3
counter += step
print(counter) # it should be 4, then
In case you need only non-negative integers from the user (we are increasing the
counter after all!), you can prevent incorrect inputs by using the abs() function. It
pertains to Python built-ins and returns the absolute value of a number (that is, value
regardless of its sign). Let's readjust our last program a bit:
counter = 1
step = abs(int(input())) # user types -3
counter += step
print(counter) # it's still 4
As you can see, thanks to the abs() function we got a positive number.
For now, it's all right that you do not know that much about mentioned in
passing errors, loops and built-in functions doing the math in Python. We will catch
up and make sure that you know these topics comprehensively. Keep learning with us!
Thus, we have shed some light on new details about integer arithmetic and the
processing of numerical inputs in Python. Feel free to use them in your future projects.
Eg.
# put your python code here
hour_1 = abs(int(input()))
mint_1 = abs(int(input()))
secd_1 = abs(int(input()))
hour_2 = abs(int(input()))
mint_2 = abs(int(input()))
secd_2 = abs(int(input()))
hour = hour_2 - hour_1
mint = mint_2 - mint_1
secd = secd_2 - secd_1
print(hour * 60 * 60 + mint * 60 + secd)
Theory: Basic string methods
As you already know, the string is one of the most important data types in Python. To
make working with strings easier, Python has many special built-in string methods. We
are about to learn some of them.
"Changing" a string
The first group of string methods consists of the ones that "change" the string in a
specific way, that is they return the copy with some changes made.
The syntax for calling a method is as follows: a string is given first (or the name of a
variable that holds a string), then comes a period followed by the method name and
parentheses in which arguments are listed.
str.replace(old, new[, count]) replaces all occurrences of old with the new.
The count argument is optional, and if specified, only the first count occurrences are
replaced in the given string.
str.upper() converts all characters of the string to the upper case.
str.capitalize() changes the first character of the string to the title case and the
rest to the lower case.
And here's an example of how these methods are used (note that we don't save the
result of every method):
message = "bonjour and welcome to Paris!"
print (message.upper()) # BONJOUR AND WELCOME TO PARIS!
# `message` is not changed
print(message) # bonjour and welcome to Paris!
title_message = message.title()
# `title_message` contains a new string with all words capitalized
print(title_message) # Bonjour And Welcome To Paris!
replaced_message = message.replace("o", "!")
# again, the source string is unchanged, only its copy is modified
print(replaced_message) # b!nj!ur and welc!me t! Paris!
# the string is the same as it was
print(message) # bonjour and welcome to Paris!
"Editing" a string
Often, when you read a string from somewhere (a file or the input) you need to edit it so
that it contains only the information you need. For instance, the input string can have a
lot of unnecessary whitespaces or some trailing combinations of characters. The
"editing" methods that can help with that are strip(), rstrip() and lstrip().
whitespace_string = " hey "
normal_string = "incomprehensibilities"
# delete spaces from the left side
whitespace_string.lstrip() # "hey "
# delete "i" or "s" or "is" from the left side
normal_string.lstrip("is") # "ncomprehensibilities"
# delete spaces from the right side
whitespace_string.rstrip() # " hey"
# delete "i" or "s" or "is" from the right side
normal_string.rstrip("is") # "incomprehensibilitie"
# no spaces from both sides
whitespace_string.strip() # "hey"
# delete trailing "i" or "s" or "is" from both sides
normal_string.strip("is") # "ncomprehensibilitie"
Keep in mind that the methods strip(), lstrip() and rstrip() get rid of all possible
combinations of specified characters:
word = "Mississippi"
print(word.lstrip("ips")) # "Mississippi"
print(word.rstrip("ips")) # "M"
print(word.strip("Mips")) # ""
Use them carefully, or you may end up with an empty string.
Conclusions
Thus, we have considered the main methods for strings. Here is a brief recap:
While working with string, you have to remember that strings are immutable, thus all
the methods that "change" them only return the copy of a string with necessary changes.
If you want to save the result of the method call for later use, you need to assign
this result to a variable (either the same or the one with a different name).
If you want to use this result only once, for example, in comparisons or just to print the
formatted string, you are free to use the result on spot, as we did within print().
Eg.
sentence = input().lower()
sentence = sentence.replace('!', '').replace('?', '')
sentence = sentence.replace('.', '').replace(',', '')
print(sentence)
Boolean type
The Boolean type, or simply bool, is a special data type that has only two possible
values: True and False. In Python, the names of boolean values start with a capital letter.
In programming languages, the boolean, or logical, type is a common way to represent
something that has only two opposite states like on or off, yes or no, etc.
If you are writing an application that keeps track of door openings, you'll find it natural
to use bool to store the current door state.
is_open = True
is_closed = False
print(is_open) # True
print(is_closed) # False
Boolean operations
There are three built-in boolean operators in Python: and, or and not. The first two
are binary operators which means that they expect two arguments. not is
a unary operator, it is always applied to a single operand. First, let's look at these
operators applied to the boolean values.
and is a binary operator, it takes two arguments and returns True if both arguments are
true, otherwise, it returns False.
a = True and True # True
b = True and False # False
c = False and False # False
d = False and True # False
a = True or True # True
b = True or False # True
c = False or False # False
d = False or True # True
to_be = True # to_be is True
not_to_be = not to_be # not_to_be is False
Logical operators have a different priority and it affects the order of evaluation. Here are
the operators in ascending order of their priorities: or, and, not. Having this in mind,
consider the following expression:
print (False or not False) # True
First, the part not False gets evaluated, and after evaluation, we are left with False or
True. This results in True, if you recall the previous section.
While dealing solely with the boolean values may seem obvious, the precedence
of logical operations will be quite important to remember when you start working
with so-called trutTruthy and falsy values
Though Python has the boolean data type, we often want to use non-boolean values in
a logical context. And Python lets you test almost any object for truthfulness. When
used with logical operators, values of non-boolean types, such as integers or strings, are
called truthy or falsy. It depends on whether they are interpreted as True or False.
print (0.0 or False) # False
print(False and "") # False
Generally speaking, and and or could take any arguments that can be tested for a
boolean value.
# `and` has a higher priority than `or`
truthy_integer = False or 5 and 100 # 100
Again, let's break the above expression into parts. Since the operator and has a higher
priority than or, we should look at the 5 and 100 part. Both 100 and 5 happen to be
truthy values, so this operation will return 100. You have never seen this before, so it's
natural to wonder why we have a number instead of the True value here. We'll cover this
surprising fact shortly. Coming back to the original expression, you can see that the last
part False or 100 does exactly the same thing, returns 100 instead of True.
tricky = not (False or '') # True
A pair of parentheses is a way to specify the order in which the operations are
performed. Thus, we evaluate this part of the expression first: False or ''. This
operand '' evaluates to False and or returns this empty string. Since the result of the
enclosed expression is negated, we get True in the end: not '' is the same as True. Why
didn't we get, say, a non-empty string? The not operator creates a new value, which by
default has the boolean type. So, as stated earlier, the unary operator always returns a
logical value.
Short-circuit evaluation
The last thing to mention is that logical operators in Python are short-circuited. That's
why they are also called lazy. That means that the second operand in such an
expression is evaluated only if the first one is not sufficient to evaluate the whole
expression.
For instance:
# division is never evaluated, because the first argument is True
lazy_or = True or (1 / 0) # True
# division is never evaluated, because the first argument is False
lazy_and = False and (1 / 0) # False
Those were the very basics of boolean values and logical operations in Python. It's
definitely good to know them right from the beginning!
Comparison operators
The result of applying these operators is always bool. The following sections focus on
the first six operators, but you can find more details about identity and membership
testing in the next topics.
Comparing integers
a = 5
b = -10
c = 15
result_1 = a < b # False
result_2 = a == a # True
result_3 = a != b # True
result_4 = b >= c # False
Any expression that returns integer is a valid comparison operand too:
calculated_result = a == b + c # True
Given the defined variables a, b and c, we basically check if 5 is equal to -10 + 15, which
is true.
Comparison chaining
Since comparison operations return boolean values, you can join them using logical
operators.
x = -5
y = 10
z = 12
result = x < y and y <= z # True
In Python, there is a fancier way to write complex comparisons. It is called chaining. For
example, x < y <= z is almost equivalent to the expression you saw in the last example.
The difference is that y evaluated only once.
result = 10 < (100 * 100) <= 10000 # True, the multiplication is evaluated once
Simple if statement
There are situations when your program needs to execute some piece of the code only if
a particular condition is true. Such a piece of the code should be placed within the body
of an if statement. The pattern is the same as in the English language: first comes the
keyword if , then a condition, and then a list of expressions to execute. The condition is
always a Boolean expression, that is, its value equals either True or False. Here is one
example of how the code with a conditional expression should look like:
biscuits = 17
if biscuits >= 5:
print("It's time for tea!")
Note that the condition ends with a colon and a new line starts with an indentation.
Usually, 4 spaces are used to separate different blocks of code. An if statement is
executed only if its condition holds (the Boolean value is True), otherwise, it's skipped.
Boolean values basically make it clear whether a piece of code needs to be executed or
not. Since comparisons result in bool, it's always a good idea to use them as a condition.
There is one pitfall, though. You should not confuse the comparison operator for
equality == with the assignment operator =. Only the former provides for a proper condition. Try
to avoid this common mistake in your code.
Next section
Nested if statement
rainbow = "red, orange, yellow, green, blue, indigo, violet"
warm_colors = "red, yellow, orange"
my_color = "orange"
if my_color in rainbow:
print("Wow, your color is in the rainbow!")
if my_color in warm_colors:
print("Oh, by the way, it's a warm color.")
The example above illustrates a nested if statement. If the variable my_color is a string
that contains the name of a color from the rainbow, we enter the body of the
first if statement. First, we print the message and then check if our color belongs to the
warm colors. The membership operator in simply shows whether my_color is a substring
of the respective string, rainbow or warm_colors. Just like arithmetic comparisons, it
returns a boolean value.
Wow, your color is in the rainbow!
Oh, by the way, it's a warm color.
When it comes to nested if statements, proper indentation is crucial, so do not forget
to indent each statement that starts with the if keyword.
Chapter 2 - LIST:
ORDERD COLLECTION OF DATA IN SQUARE BRACKET [ ] IS CALLED LIST
Eg. NUM=[6,5,11,12]
Word=[‘a’,’b’,’’anas’]
Mix= [anas,2.0,6]]
Keyword = list
Eg. Print(word[2])
‘c’.
Change data from (in) list.
To change any data In given list we can use
[6,5,three,12,14]
Eg.
l.append(“U.P”)
INSERT METHOD;
To add any data between given list or data we use insert function
Keyword: pop
l.pop()
Remove method
l.remove(“delhi”)
4 FEB 2020
List concetation
To add to two list we use list concertation
Eg.
L1=[1,2,3,]
L2=[4,5,6]
L3=L1+L2
Print(L3)
EXTEND METHOD
L1.extend(l2)
Print(l1)
[1,2,3,4,5,6]
COUNT FUNCTION
L=[“a”,”b”,”c”,”b”]
Keyword=print(l.count(“b”))
SORT FUNCTION
To sort list we use sort function
Keyword l.sort()
Print(l)
SORTED FUNCTION
Sorted function make copy and give a new copy list
Keyword: print(sorted(l))
L1=l.clear()
Keyword=input(“enter name”).split(“ “) (in space between “ “ we give value from which we have to
split)
Print(l)
Looping in list
While and for loop
Eg. For i in a…
Print(i)
Eg.
L=[[1,2,3],[4,5,6],[7,8,9]]
L[1]=[4,5,6]
L[1][1]=5
Or
For i in l:
Print(i)
DICTIONARY:
UNORDERD collection of data inside curly bracket {} in key and value pair is called dictionary.
Eg:
{“name”:”a”,”age”:18,”city”:”Bhopal”}
{k1:v1,k2:v2,k3:3}
Keyword = dict
To create dictionary
D1 = dict(name=”a”, age=18)
Eg:
d[“key “] ==”value”
To add data into dictionary:
d[“fav_song”]=[“a”,”b”]
d.pop(“key”)
key of dictionary must always be unique. Therefore key must be unique. And cannot repeate.
Looping in dictionary
Methods in dictionary
1. Keys()
Eg
For I in d
Print (i)
Print(d.keys())
For I in d.key()
Print(I)
Values()
Values method is used to print values from dictionary.
B=d.values()
Print(b)
For I in d.values()
Print(i)
Eg2
For I in d:
Print(d[i])
Eg.
C=d.items()
Print (c)
Output will be
For I in d.items():
Print(i)
Print(k,v)
Update method:
D1={“d”:4,”f”:5}
Keyword: d.update(d1)
Print(d)
Fromkeys method:
D={“a”:1,”b”:2,”c”:3}
{“a”:”na”,”b”:”na”,”c”:”na”}
My_dic=dict.fromkeys([“a”,”b”,”c”],”na”)
Dict.fromkeys([“a”,”b”,”c”],[“na,”na”])
Dict.fromkeys(“name”,[“na:na])
If condition on dictionary
If 20 in d.values():
Print(“true”):
Else:
Print(“false”):
8 FEB 2020
TUPLES:
TUPPLE IS A ORDERD COLLECTION OF IMMUTABLE DATA INSIDE PARANTHISIS () .
Eg.
Cake = (“c”,”a”,”k”,”e”)
Mix_tup=(1,2,3,”Faaiz”,true)
Tupple is immutable
Tupple is presented in ()
X=(1,2,3,4)
Y=(5,6,7,8)
Z=x+y
Print(z)
(1,2,3,4,5,6,7,8)
Multiplication:
Z=x*2
Print(z)
(1,2,3,4,1,2,3,4)
Sum function
Max function
Min function
Sorted function
Eg t=(“Faaiz”,)
Tupple unpacking:
Fi,f2,f3=fruits
T[3]==[3.0,true,5]
T[3].append/.pop/.clear
C=a+b
D=a*b
Return c,d
Print(fun(4,5))
Tuples are used to collect an immutable ordered list of elements. This means
that:
You can’t add elements to a tuple. There’s
no append() or extend() method for tuples,
You can find elements in a tuple since this doesn’t change the tuple.
17 FEB2020
List Comprihension:
18 feb 2020
DICTIONARY COMPRIHENSIOM;
Print({i:i**3 for I in range (1,11)}
19 feb 2020
Return args
Print(func(1,2,3,4,5,6))
Or print (fun())
* opertator is used to make flexible function. We can give variable number of argument in a
function through star operatot.
* operator return tuple.
To unpack we use *
Eg fun(*arg)
20 FEB 2020
KEYWORD ARGUMENT
Eg.
Def func(**keyargument)
Print(type(keyword))
Return keyword
Print(fun())
ARGUMENT NUMERLOGY
21 FEB 2020
ANONYMOUS FUNCTION:
Anonymos function is made by lambda key word. Lambda key word is combination of
Argument : expression.
Eg
Print(sqr)
22 FEB 2020
Built in function:
Map()
Filter()
Reduce().
Eg.
Map(function,sequence)
2. Filter
Filter(lambda a:a==a.uper() , l)
3. Reduce
24 FEB 2020
enumerate function
25 FEB 2020
IT IS USED TO SYNCHRONIZE OBJECT OF SAME INDEX NUMBER
Zip(obj1,obj2)
Zip(*args)
28 feb 2020
DECORATOR:
FUNCTION RETURNING FUNCTION:
DEF OUTER():
DEF INNER():
A=outer()
Print(a())
29 FEB 2020
OOPS:
Class: Class is a blue print of object. Class is a user define data type, which has data member and
member function, data member are the data variables and member function are the functions used to
manipulate these variables.
Class person:
Def __init__(self,first,lastage):
Self.first=first
Self.last=last
Self.age=age
P1=person(‘a’,’x’,25)
P2=person(‘b’,y’,30)
Class variable:
If any value is same for all the object in the class then it is defined as class variable.
@classmethod
Def count_instance(cls):
Inheritance:
In oops the property of inheritance ia acquired the properties and attributes of parent class to child
class.
There are different types of inheritance
*single heritance
Multilevel inheritance
Multiple heritance:
Super().__init__(b,m,p)
MRO
Method resolutuion order
Dunder method
FILE HANDLING:
Open method:
Read method:
f.read()
seek method
f.tell
Readlines
f.readline()
readlines
Close method
To close file
f.close()