COMPUTER NOTES (Lect

Download as pdf or txt
Download as pdf or txt
You are on page 1of 11

COMPUTER NOTES (lecture-6,7,8,9,10,11,12,13,14,15,16,17)

GETTING STARTED WITH PYTHON

FILE EXTENSION

1. .py - regular python scripts


2. .ipynb - jupyter notebook file
3. .pyc - compiled scripts(bytecode)
4. .pyo - optimized pye bytecode file

There are two ways to use the python interpreter-

1. INTERACTIVE MODE- interactive mode allow us to execution of individual statement


instantaneously.
2. SCRIPT MODE- this mode allow us to write more than one instructions in a file called python
source code file that can be executed.

INTERACTIVE MODE-

`to work in the interactive mode, we can simply type a python statement on the >>> promt directly.
as soon as we press enter, the interpreter executes the statement and displays the results(S)
working in the interactive mode in convenient for testing a single line code for instant execution.
but in the interactive mode, we cannot save the statements for future use and we have to retype the
statements to run them again**

SCRIPT MODE-

in the script mode we can write a python program in a file,save it and them use the interpreterto
exexute it.
python scripts are saved as files where file name has extension .py
by default, the python scripts are saved in the python installation folder.

ARITHMETIC OPERATORS - operands on which operation performed

symbol operation example


+ addition x+y
- subtraction x-y
* multiplication x*y
/ division x/y
% modulus x%y
** exponentiation x**y
// floor division x//y

[e.g 12/5=2.4 ,12//5=2(quotient), 12%5=2( remainder), 2^5=2**5=32.]

STATEMENTS-

statements are instructions written in the source code for execution.


there are different types of statments in the python programming language like ;

1. assingment statements.
2. conditional statements.
3. looping statements,etc.

in general, the interpreter reads and execute the statements line by line i.e sequentially and mostly.
python statements are written in such a format that one statement in only written in a single line.
the interpreter considers the 'new line character' as the terminator of one instructions.
but,writing multiple statements per line and multi-line statements is also possible.

MULTIPLE STATEMENTS PER LINE-


writing multiple statements in a single line is also possible, multiple statements are seprated using
semicolons(;) symbol.
MULTI-LINE STATEMENTS (LINE CONTINUATION)-

some statements may become very long and may force us to scroll the sreen left and right frequently.
we can fir our code in such a way that we do not have to scroll here and there.
python allows us to write a single statement in multiple lines, also known as line continuation.
line continuation enhances readablility as well.

IMPLICIT LINE CONTINUATION-

this is the most straight forward technique in writing a statement that spans multiple lines.
any statement containing opening parentheses '(', brackets'[', or curly braces'{' is presumed to be in
complete ultil all matching parentheses, square brakcets, curlty braces have been encountered.
until then, the statement can be implicitly continued across lines without raising an error.

EXPLICIT LINE CONTINUATION-

explicit line joining is used mostly when implicit line joinig is not applicable. in this method, you have
to use a charactger that helps the interpreter to understand that the particular statements is spannig
more than one lines.
backslash(\) is used to indicate that a statements spans more than one line. the point is to be noted that
"__" must be the last character in that line, even white space in not allowed.

COMMENTS- (defn**_**)

**comments are used to add a remark or anote in the source code.**


they are added with the purpose of making the source code easier for humans to understand.
they are used primarily to document the meaning and purpose of source code and its input and output
requirements,so that we can remember later how its function and how to use it.
for large and complex software ,it may require programmers to work in teams and sometimes, a
program written by one promgrammer is required to be used or maintained by another programmer.
in such situations, documentations in the form of comments are needed to understand the working of
the program.

NOTE- comments are not executed by interpreter,interpreter ignores the comments and does not count them
in commands.

1. single line comments


2. multi line string as a comment

SINGLE LINE COMMENTS :

python single line comments starts with hashtag symbol with no white spaces(#) and lasts till the end
of the line.
if the comment exceeds one line then put a hashtag on the next line and continue the comment.
python's single-line comments are proved useful for supplying short explanations for variables,
function declarations, and expressions.

MULTI-LINE STRING AS A COMMENT : (double inverted commas three times without space)

python multiline comment is a piece of text enclosed in a delimiter(""") on each end of the comment.
there should be no white space between delimeter(""").
they are useful when the comment text does not fit into one line,therefore need to span across lines.
nulti-line comments or paragraphs serve as documentation for others reading your code.

WHITE SPACES :

whitespace is mostly ignored,adn mostly not required, by the python interpreter.


when it is clear where one token ends and the next one starts whitespaces can be ommited.
this is usually the case wehn specail non-alphanumeric characters are involded.
whitespaces are necessary in seperating the keywords from the variables or other keywords.

WHITESPACES AS INDENTATION :

a block is a combination of statements.


bloack can be regarded as the grouping of statements for a specific purpose.
most of the programming languages like c,c++, java use braces{ } to define a block of code.
one of the distictive features of python is its use of indentation to highlighting the blocks of code.

MEANING OF INDENTATION :

whitespaces before a statement can have a different meaning.


whitespaces before a statement have significant role and are used in indentation.
all statements with the same distances to the right belong to the same block of code. if a block has to
be deeply nested, it is simply indented further to the right.

KEYWORDS :

the keywords are some predefined and reserved words in python that have special meanings.
keywords are udes to define the syntax of the coding.
the keyword cannot be used as an identifier, function, and variable name.
**all the keywords in python are written in lower case-except True, False and None.**
for python 3.9.7, there are 35 kwywords in total and may change slightly with versions.

IDENTIFIERS :
the indentifier is a name used to identify a variable, function , class, module, etc.
it helps to differentiate one entity from another.

RULES FOR WRITING IDENTIFIERS :

1. identifiers can be a combination of letters in lowercase( a to z) or uppercase (A to Z) or digits (0 to 9)


or an underscore (_).** space not allowed ** e.g vardan, vardan_garg.
2. an indentifier cannot start with a digit. e.g- 7vardan(not allowed)
3. keywords cannot be same as identifiers.
4. we can't use special symmbols like !,@,#,$,%, etc. in our identifier. e.g- vardan@garg
5. an identifier can be of any length(however, it is preferred to keep it short and meaningful).

P.T.R :

python is a case sensitive language.


python is an interprated language.
always guve the indentifiers a name that makes sense.
multiple words can be separated using an underscore

VARIABLES :

a variable is a named location used to store data in the memory.


it is helpful to think of variables as a container that holds data tha can be changed later in the program.

NOTE : in python, we can't actually assign values to the variables. instead, python gives the reference of the
object (value) to the variable.
ASSIGNING VALUES TO VARIABLES IN PYTHON :

declaring and assigning value to a variable. (a=7)


changing the value of a variable.( a=10 changed)
assigning multiple values to multiple variables.( a,b,c = 1,2,3)
same value to multiple variables.(a=b=c=7)

CONSTANTS :

a constant is a type of variable whose value cannot be changed.


it is helpful to think of constants as a container that hold information which cannt be changed later.
use capital letters if possible to declare a constant.

NOTE : in reality, we don't use constants in python.naming them in all capital letters is a conversation to
sepereate them from variables , however , it does not actually prevent assingment.
PCONST LIBRARY : practically(27:18 lecture 11)
NOTE :

in pythons we can use an assignment statement to create new variables and assign specific values to
them.
variable declaration is implicit in python, means variablesn are automatically declared and defined
when they are assigned a value the first time.
variables must always be assigned values before they are used in expressions as otherwise it will lead
to an error in the program.**(question)
wherever a variable name occurs in an expression, the interpreter replaces it with the value of that
particular variable.

LITERALS : literal is a row data given in a variable or constant.


e.g => a=7 ( a =variable, = operator, 7= literal)
IN PYTHON THERE ARE VARIOUS TYPES OF LITERALS

1. numeric literals
2. string literals
3. boolean literals
4. special literals
5. literal collections.

NUMERIC LITERALS :

numeric literals can belong to 3 different numerical types;

1. integer-binary literal,octal literal,decimal literal and hexadecimal literal.


2. float-decimal, scientific form (e in place of 10)
3. complex-(lecture-12; 30:00)

numeric literals are immutable(unchangeable).

STRING LITERALS :

a string literal is a sequence of characters surrounded by quotes. we can use bith single, double, or
triple quotes for a string.
and, a character literal is a single character surrounded by single or double quotes.
we'll see-

1. single line string


2. character
3. multiline string
4. unicode
5. raw string.

BOOLEAN LITERALS : a boolean literals can have any of the two values ;

1. true
2. false.

SPECIAL LITERALS :

python contains one special literals i.e none.


we use it to specify that the field has not been created.

LITERAL COLLECTIONS :

1. list literals
2. tuple literals
3. dict literals
4. set literals

DATA TYPES :

data types are the classification or categorization of data items.


it represents the kind of value that tells what operartions can be performed on a particular data.
since everything is an object in python programming data types are actually classes and variables are
instance(object) of these classes.

NUMERIC :

in python,numeric data type represent the data which has numeric value.
numeric value can be integer, floating number or even complex numbers.
these values are defined as int, float and complex class in python.

TYPES OF NUMERIC DATA TYPES IN PYTHON -

INTEGERS

1. This value is represented by int class.


2. it contains positive or negative whole number.(without fraction or deciaml).
3. in pyhton there is no limit to how long an integer value can be.**

FLOAT

1. this value is represented by float class.


2. it is a real number with floating point representation.
3. it is specified by a decimal point.
4. a floating-point number is accurate up to 15 decimal places.**

COMPLEX NUMBERS

1. complex number is represented by complex class. it is specified as(real part) + (imaginary part)j. for
example- 2+3j.

BOOLEAN :

data type with one of the two built-in values, true or false.
boolean objects that are equal to true and truthy(true), and those equal to false are falsy(false).
but non-boolean objects can be evaluated in boolean context as well and determined to be true or false.
it is denoted by the class bool.

NOTE => true and false with capital 'T' and 'F' are valid booleans otherwise python will throw an error.
SEQUENCE TYPE :

in python, sequence is the ordered collection of similar or different data types


sequences allows to store multiple values in an organized and efficient fashion.

there are several sequence types in python -

1. string
2. list
3. tuple.

SEQUENCE TYPE- STRING :

a string is a collection of one or more characters put in a single quote, double-quote or triple quote.
in python there is no character data type, a character is a string of length one.
it is represented by str class.

SEQUENCE TYPE-LIST :

list are just like arrays, declared in other languages whcih is a ordered collection of data.
it is very flexible as the items in a list do not need to be of the same type

CREATING LIST -list in pythons can be created by just placing the seuqnce inside the square brackets[ ]
TUPLE :

tuple is also an ordered collection of python objects. the only difference between tuple and list is that
tuples are immutable i.e. tuples cannot be modified after it is created.
it is represented by tuple class.

CREATING TOUPLE -tuples are created by placing a sequence of values seperated by 'comma' with or
without the use of parantheses( ) for grouping of the data sequence.

NOTE => tuples can also be created with a single element, but it is a tricky.having one element in the
parantheses is not sufficient, there must be a trailing 'comma' to make it a tuple.
NOTE =>creation of python tuple without the use of parantheses is known as tuple packing.

SETS :

in python, set is an unordered collection of data type that is iterable, mutable, and has no duplicate
elements.
the order of elements in a set is undefined though it may consist of various elements.
type of elements is a set need not be the same , various mixed-up data type values can also be passed
to the set.

CREATING SETS :

sets can be created by using built-in set ( ) function with an iterable object.
a sequence by placing the sequence crly braces,seperated by 'comma'.

DICTIONARY :(important for ques in exam)

dictionary in python is an unordered collection of data values, used to store data values like a map ,
which unlike other data types that hold only single value as an element.
dictionary holds (key:value)pair.
key-value is provided in the dictionary to make it more optimized.
each key-value pair in a dictionary is seperated by a colon(:)
each key is seperated by a comma(,).

CREATING DICTIONARY :
dictionary can be created by placing a sequence of elements eithing curly { } braces, seperated by
'comma'.
values in a dictionary can be of any datatype and can be duplicated, whereas keys can't be repeated and
must be immutable.
dictionary can also be created by the built-in function dict().
an empty dictionary can be created by just placing it to curly braces{}.

NOTE => Dictionary keys are case sensitive, same name but different cases of key will be treated distinctly.
type( ) and isinstance( ) functions :
(e.g) x=[1,2,3,4,5]
print(type(x))
(e.g) x = 2
isinstance(x, class)
MUTABLE AND IMMUTABLE DATA TYPES :

sometimes we may require to change or update the values of certain variables used in a program.
however, for certain data types, python does not allow us to change the values once a variable of that
type has been created and assigned values.
variables whose values can be changed after they are created and assigned are called mutables.
variables whose value cannot be changed after they are created and assigned are called immutable.
when an attempt is made to update the value of an immutable variable, the old variable is destroyed
and a new variable is created by the same name in mermory.

IMMUTABLE - integers, float, boolean, complex, strings, tuples, sets


MUTABLE - lists, dictionary.
DECIDING USAGE OF PYTHON DATA TYPES :

it is preferred to use lists when we need a simple iterable collection of data that may go for frequent
modifications.

for example- if we store the names of students of a class in a list, then it is easy to update the list when some
new students join or leave the course.

tuples are used when we do not need any change in the data.

for example- names of months in a year.

when we need uniqueness of elements and to avoid duplicacy it is preferable to use sets.

for example- list of artefacts in a musuem


if our data is being constantly modified or we need a fast lookup based on a custom key or we need a
logical association between the key-value pair, it as advised to use dictionaries.

for example- a mobile phone book is a good application of dictionary.{[ lecture 13 coding]}
#1:14:00#
TYPE CONVERSION:

type conversion is the method to convert the variable's dta types into a certain data types in order to
perform the operation required by the users.

two types of conversion in python-

1. implicit type conversion


2. explicit type conversion.

IMPLICIT TYPE CONVERSION:

1. in implicit type conversion, python automatically converts one data type to another data type.this
process doesn't need any user involvement.
2. data type conversion happen during complitation or on run time.

EXPLICIT TYPE CONVERSION:

1. in explicit type conversion,users convert the data types of an object to required data type.
2. this type of conversion is also called typecasting because the user casts (changes) the dta type of the
objects.

conversions from video 09:00 to 57:26(from book


**imp ascii conversion
dict conversion
string conversion**

PTR :-

python avoids the loss of data in implicit type conversions.


in explicit type casting, loss of data may occur as we enforce the object to a specific data type.

You might also like