[go: up one dir, main page]

0% found this document useful (0 votes)
139 views27 pages

Operation Priority

1. There are different types of operations that have a specified priority order in Python. Operations with higher priority are performed before those with lower priority. 2. When operations have the same priority, they are performed from left to right. 3. Functions are blocks of code that perform a specific task and can be reused. To call a function, write its name followed by parentheses containing any arguments. 4. Python has many built-in functions for common tasks like converting types, math operations, getting lengths and types.

Uploaded by

MohdFaaiz
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
139 views27 pages

Operation Priority

1. There are different types of operations that have a specified priority order in Python. Operations with higher priority are performed before those with lower priority. 2. When operations have the same priority, they are performed from left to right. 3. Functions are blocks of code that perform a specific task and can be reused. To call a function, write its name followed by parentheses containing any arguments. 4. Python has many built-in functions for common tasks like converting types, math operations, getting lengths and types.

Uploaded by

MohdFaaiz
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 27

Operation priority

To sum up, there is a list of priorities for all considered operations:

1. parentheses
2. power
3. unary minus
4. multiplication, division, and remainder
5. addition and subtraction

Sometimes operations have the same priority:

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:

 the operators are not in one column,  


 each operator has moved away from its operand and onto the previous line:

#  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.

Theory: Invoking a function


Even though invoking functions in Python is not about casting a spell or the like, it does
sometimes work wonders. Let's start with the concept. Basically, a function is a
structured fragment of code we may want to use in more than one place and more than
one time. For another thing, functions allow us to read both our code and that of
someone else way better. Haven't they become your favorite yet?

Here is a simple function call:

multiply(1, 7)

Here multiply is the name of the function, and numbers in parentheses (1, 7) are


its arguments. What is an argument? Well, it's just a value, that will be used inside the
body of the function. Let's go deeper into it!

Invoking print()

To call, or invoke, a function in your program, simply write its name and add


parentheses after it. That's all it takes! Fun fact - if you've ever typed an expression like
this print("Hello, world!"), you already know a little about functions. In this tiny
example, however, we see the message "Hello, world!" in the parentheses after the
name of the print function. What does it mean? This string is just an argument. And
more often than not, functions do have arguments. As for the print function, we may as
well use it with no argument at all or even with multiple arguments:
print ("Hello, world!")
print()
print("Bye,", "then!")
And here is the output:

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.

Let's make a brief summary:

 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.

Theory: Program with numbers

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!

Reading numbers from user input

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.

Free air miles

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:

Advanced forms of assignment

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.

One possible application of compound assignment comes next.


Counter variable

In programming, loops are used alongside with special variables called counters.


A counter counts how many times a particular code is run. It also follows that counters
should be integers. Now we are getting to the point - you can use the
operators += and -= to increase or decrease the counter respectively.

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.

An important thing to remember, however, is that the string is an immutable data type! It


means that you cannot just change the string in place, so most string methods return a copy of
the string (with several exceptions). To save the changes made to the string for later use you
need to create a new variable for the copy that you made or assign the same name to the
copy. So what to do with the output of the methods depends on whether you are going to
use the original string or its copy later.

"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.

Here’s a list of common string methods of that kind:

 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.lower() converts all characters of the string to the lower case.

 str.title() converts the first character of each word to upper case.

 str.swapcase() converts upper case to lower case and vice versa.

 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().

 str.lstrip([chars]) removes the leading characters (i.e. characters from the left


side). If the argument chars isn’t specified, leading whitespaces are removed.

 str.rstrip([chars]) removes the trailing characters (i.e. characters from the right


side). The default for the argument chars is also whitespace.

 str.strip([chars]) removes both the leading and the trailing characters. The


default is whitespace.

The chars argument, when specified, is a string of characters that are meant to be


removed from the very end or beginning of the word (depending on the method you're
using). In the examples below, it is the first and the last character of the normal_string.
See how these methods are used:

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

 or is a binary operator, it returns True if at least one argument is true, otherwise, it


returns False.

a  = True or True    # True
b = True or False   # True
c = False or False  # False
d = False or True   # True

 not is a unary operator, it reverses the boolean value of its argument.

to_be  = True           # to_be is True
not_to_be = not to_be  # not_to_be is False

The precedence of boolean operations

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.

The following values are evaluated to False in Python:

 constants defined to be false: None and False,


 zero of any numeric type: 0, 0.0,
 empty sequences and containers: "", [], {}.

Anything else generally evaluates to True. Here is a couple of examples:

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.

Now we can demonstrate more clearly the difference in operator precedence:

#  `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.

The operators or and and return one of their operands, not necessarily of the boolean type.


Nonetheless, not always returns a boolean value.

Another tricky example is below:

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.

 x and y returns x if x is falsy; otherwise, it evaluates and returns y.

 x or y returns x if x is truthy; otherwise, it evaluates and returns y.

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

Comparison or relation operations let you compare two values and determine the


relation between them. There are ten comparison operators in Python:

 < strictly less than


 <= less than or equal
 > strictly greater than
 >= greater than or equal
 == equal
 != not equal
 is object identity
 is not negated object identity
 in membership
 not in negated membership.

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

In this topic, we will cover only integer comparison.

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

Sometimes a condition happens to be too complicated for a simple if statement. In this


case,  you can use so-called nested if statements. The more if statements are nested,
the more complex your code gets, which is usually not a good thing. However, this
doesn't mean that you need to avoid nested if statements at whatever cost. Let's take a
look at the code below:

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.

Here is what we will see in our case:

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

List can be of any data type int, string, float.

Eg. NUM=[6,5,11,12]

Word=[‘a’,’b’,’’anas’]

Mix= [anas,2.0,6]]

Keyword = list

ACCESS data from list


We can print any data from list with the help of indexing

Eg. Print(word[2])

‘c’.
Change data from (in) list.
To change any data In given list we can use

Num [2] =”three”

We will get new list

[6,5,three,12,14]

Multiple data indexing;

ADD DATA INTO LIST :


We can add data into list with the help of append

Eg.

l.append(“M.P”) note : name.append() here name is a address

l.append(“U.P”)

INSERT METHOD;
To add any data between given list or data we use insert function

l.insert(1,”delhi”) note: name.insert()

DELETE DATA FROM LIST:


TO delete any data from list we use pop method

Keyword: pop

l.pop()

It also save delete data in it.

Remove method

To remove data without indexing

l.remove(“delhi”)

delhi will be removed

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)

Sort function make changes in its original list

SORTED FUNCTION
Sorted function make copy and give a new copy list

Keyword: print(sorted(l))

Copy function and clear function


L1=l.copy()

L1=l.clear()

SPLIT FUNCTION (METHOD)


To get list from string we use split method

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)

To find random function from list

From import random choice

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}

Due unordered data collection indexing is not possible.

Keyword = dict

To create dictionary

D={“name”:”a” , “age” : 18 , “city” = “ Bhopal”

D1 = dict(name=”a”, age=18)

We cannot give list or dictionary in key.

Eg:

How to access data from dicitionary:

d[“key “] ==”value”
To add data into dictionary:

d[“fav_song”]=[“a”,”b”]

To delete data from dictionary:

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()

It is used to print keys from dictionary

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])

3.ITEMS for unpacking


First in changes dictionary in tuple. Pair of key and value in tuple.

Eg.

C=d.items()
Print (c)

Output will be

For I in d.items():

Print(i)

For k,v in d.items():

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 () .

Indexing is possible in indexing and slicing.

Eg.

Cake = (“c”,”a”,”k”,”e”)

Mix_tup=(1,2,3,”Faaiz”,true)

Tupple is immutable

Tupple is presented in ()

No append , no.pop , no reverse ,

Execution of tupple is faster than list.

Tupples are secure than list.

We use tupple were our data is fixed

Some common operation in tupple.


Addition:

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)

Some function in tupple


Count function
Len function

Sum function

Max function

Min function

Sorted function

Tupple with one element:


To make tupple of one elment we have to give , at last

Eg t=(“Faaiz”,)

Tupple without () parenthesis:


Eg: fruits=”apple”,”orange”.

Tupple unpacking:
Fi,f2,f3=fruits

List inside tupple:


T=(‘apple’,1,2,[3.0,true,5],8)

T[3]==[3.0,true,5]

T[3].append/.pop/.clear

Function returning two values:


Def fun(a,b):

C=a+b

D=a*b

Return c,d

Print(fun(4,5))

Lists Versus Tuples

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’t remove elements from a tuple. Tuples have


no remove() or pop() method,

 You can find elements in a tuple since this doesn’t change the tuple.

 You can also use the in operator to check if an element exists in the


tuple.

17 FEB2020
List Comprihension:

Print([i**2 for I in range (1,n+1])

18 feb 2020

DICTIONARY COMPRIHENSIOM;
Print({i:i**3 for I in range (1,11)}

For unpacking we use .items()

19 feb 2020

Variable number of arguments:

Def fun(* args)

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

Keyword argument can aonly be used with ** operator.

Eg.

Def func(**keyargument)

Print(type(keyword))

Return keyword

Print(fun())

Keypoint : ** opertator return data in dictionary

ARGUMENT NUMERLOGY

Func (r , *a , d=”b” , **k)

21 FEB 2020
ANONYMOUS FUNCTION:

Anonymos function is made by lambda key word. Lambda key word is combination of

Argument : expression.

Eg

Sqr= lambda a:a**2

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

from functools import reduce .

24 FEB 2020
enumerate function

Is used to determine indexing position of of a data in item:

It is always used with for loop:

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():

PRINT(“THIS IS INNER FUNCTION”) {if we did nt call inner at return the

RETURN INNER we have to call it at print }

A=outer()

Print(a())
29 FEB 2020
OOPS:

Object oriented programing:

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.

Classes define attributes and behavior of our object.

Object is instance of class

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)

*AS SOON AS WE MAKE OBJECT , init METHOD IS CALLED.

We can create a new instance using existring instance.

Class variable:

If any value is same for all the object in the class then it is defined as class variable.

It will be defined before the __int__ method and used as in class.variable.

@classmethod

Def count_instance(cls):

Return(f”total instance of person class is {person.c}”)

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:

Is used for opening the file.

Read method:

Is used for reading the file.

f.read()

seek method

f.seek( ) is used to move cursior in a desire position

f.tell

it is used to tell the position of cursior.

Readlines

To read line by line

f.readline()

readlines

f.readlines() is used to put line in List.

Close method

To close file

f.close()

You might also like