0% found this document useful (0 votes)
4 views

2. Fundamentals

Uploaded by

hola99328
Copyright
© © All Rights Reserved
Available Formats
Download as DOC, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
4 views

2. Fundamentals

Uploaded by

hola99328
Copyright
© © All Rights Reserved
Available Formats
Download as DOC, PDF, TXT or read online on Scribd
You are on page 1/ 11

Language Fundamentals:

Identifiers a name in Python program is called identifier.


It can be class name or function name or module name or variable name.

a = 10 Rules to define identifiers in Python:

1. The only allowed characters in Python are alphabet symbols (either lower case
or upper case)

 digits (0 to 9)

 underscore symbol(_)

By mistake if we are using any other symbol like $ then we will get syntax
error.

cash = 10 √

 ca$h =20

2. Identifier should not starts with digit

 123total

 total123

3. Identifiers are case sensitive. Of course Python language is case sensitive


language.

 _total=10

 TOTAL=999

 print(total) #10

 print(TOTAL) #999
Note:

1. If identifier starts with _ symbol then it indicates that it is private(protected).

2. If identifier starts with __(two under score symbols) indicating that strongly
private identifier.

3.If the identifier starts and ends with two underscore symbols then the identifier
is language defined special name, which is also known as magic methods.

Eg: __add__

Reserved Words(Keyword):
In Python some words are reserved to represent some meaning or functionality.
Such type of words are called Reserved words.

There are 33 reserved words available in Python.

True,False,None

 and, or ,not,is

 if,elif,else

 while,for,break,continue,return,in,yield

' try,except,finally,raise,assert

 import,from,as,class,def,pass,global,nonlocal,lambda,del,with

Note:

1. All Reserved words in Python contain only alphabet symbols.

2. Except the following

3 reserved words, all contain only lower case alphabet symbols.

 True

 False
 None

Eg:

a= true

a=True √

>>> import keyword

>>> keyword.kwlist ['False', 'None', 'True', 'and', 'as', 'assert', 'break', 'class',
'continue', 'def', 'del', 'elif', 'else', 'except', 'finally', 'for', 'from', 'global', 'if',
'import', 'in', 'is', 'lambda', 'nonlocal', 'not', 'or', 'pass', 'raise', 'return', 'try', 'while',
'with', 'yield']

Comments:
Comments are any text to the right of the # symbol and is mainly useful as notes
for the reader of the program.

For example:

print('hello world') # Note that print is a function

or:

# Note that print is a function print('hello world')

Literal Constants:
An example of a literal constant is a number like 5 , 1.23 , or a string like 'This is a
string' or "It's a string!" .

It is called a literal because it is literal - you use its value literally.

The number 2 always represents itself and nothing else - it is a constant because
its value cannot be changed. Hence, all these are referred to as literal constants.
Numbers:
Numbers are mainly of two types - integers and floats.

An example of an integer is 2 which is just a whole number.

Examples of floating point numbers (or floats for short) are 3.23 and 52.3E-4 . The
E notation indicates powers of 10. In this case, 52.3E-4 means 52.3 * 10^-4^ .

Note: There is no separate long type. The int type can be an integer of any size.

Strings:
A string is a sequence of characters. Strings are basically just a bunch of words.
You will be using strings in almost every Python program that you write, so pay
attention to the following part.

Single Quote You can specify strings using single quotes such as 'Quote me on
this' . All white space i.e. spaces and tabs, within the quotes, are preserved as-is.

Double Quotes Strings in double quotes work exactly the same way as strings in
single quotes. An example is "What's your name?" .

Triple Quotes You can specify multi-line strings using triple quotes - ( """ or ''' ).
You can use single quotes and double quotes freely within the triple quotes.

'''This is a multi-line string. This is the first line.

This is the second line. "What's your name?,"

I asked. He said "Bond, James Bond." '''

Strings Are Immutable This means that once you have created a string, you
cannot change it.
The format method Sometimes we may want to construct strings from other
information.

This is where the format() method is useful. Save the following lines as a file
str_format.py :

age = 20

name = 'amit'

print('{0} was {1} years old’.format(name, age))

print('Why is {0} playing with that python?'.format(name))

Output: $ python str_format.py

piemr was 20 years old when he wrote this book

Why is piemr playing with that python?

# decimal (.) precision of 3 for float '0.333'

print('{0:.3f}'.format(1.0/3))

# fill with underscores (_) with the text centered

# (^) to 11 width '___hello___'

print('{0:_^11}'.format('hello'))

# keyword-based 'Swaroop wrote A Byte of Python'

print('{name} wrote {book}'.format(name='Swaroop', book='A Byte of Python'))

Escape Sequences:
Suppose, you want to have a string which contains a single quote ( ' ), how will
you specify this string?

For example, the string is "What's your name?" You cannot specify 'What's your
name?'

Because Python will be confused as to where the string starts and ends. So, you
will have to specify that this single quote does not indicate the end of the string.
This can be done with the help of what is called an escape sequence.

You specify the single quote as \' : notice the backslash. Now, you can specify the

string as 'What\'s your name?' .

An example is: 'This is the first line\nThis is the second line'

Raw String If you need to specify some strings where no special processing
such as escape sequences are handled, then what you need is to specify a raw
string by prefixing r or R to the string.

An example is: r"Newlines are indicated by \n"

Logical And Physical Line: A physical line is what you see when you write
the program. A logical line is what Python sees as a single statement. Python
implicitly assumes that each physical line corresponds to a logical line.

If you want to specify more than one logical line on a single physical line, then you
have to explicitly specify this using a semicolon ( ; ) which indicates the end of a
logical line/statement.

For example:

i=5

print(i)
is effectively same as

i = 5;

print(i);

which is also same as

i = 5;

print(i);

and same as

i = 5;

print(i)

Indentation: Whitespace is important in Python. Actually, whitespace at the


beginning of the line is important. This is called indentation.

Leading whitespace (spaces and tabs) at the beginning of the logical line is used to
determine the indentation level of the logical line, which in turn is used to
determine the grouping of statements.

This means that statements which go together must have the same indentation.
Each such set of statements is called a block.

We will see examples of how blocks are important in later chapters. One thing
you should remember is that wrong indentation can give rise to errors.

For example:

i = 5 # Error below! Notice a single space at the start of the line

print('Value is', i)

print('I repeat, the value is', i)

def my_function(): # This is a function definition. Note the colon (:)


a=2 # This line belongs to the function because it's indented
return a # This line also belongs to the same function
print(my_function()) # This line is OUTSIDE the function block
or

if a > b: # If block starts here


print(a) # This is part of the if block
else: # else must be at the same level as if
print(b) # This line is part of the else block

Operators and Expressions: Most statements (logical lines) that you write
will contain expressions. A simple example of an expression is 2 + 3.

An expression can be broken down into operators and operands. Operators are
functionality that do something and can be represented by symbols such as + or
by special keywords.

Operators require some data to operate on and such data is called operands. In
this case, 2 and 3 are the operands.
>>> 2 + 3

>>> 3 * 5

15

>>>

Here is a quick overview of the available operators:

+ (plus) Adds two objects

3 + 5 gives 8 . 'a' + 'b' gives 'ab' .


- (minus) Gives the subtraction of one number from the other;

if the first operand is absent it is assumed to be zero. -5.2 gives a negative number
and 50 - 24 gives 26 .

* (multiply) Gives the multiplication of the two numbers or returns the string
repeated that many times.

2 * 3 gives 6 .

'piemr' * 3 gives ' piemr piemr piemr ' .

** (power) Returns x to the power of y

3 ** 4 gives 81 (i.e. 3 * 3 * 3 * 3 )

/ (divide) Divide x by y 13 / 3 gives 4.333333333333333

// (divide and floor) Divide x by y and round the answer down to the nearest
whole number 13 // 3 gives 4 -13 // 3 gives -5

% (modulo) Returns the remainder of the division 13 % 3 gives 1 . -25.5 % 2.25


gives 1.5 .

<< (left shift) Shifts the bits of the number to the left by the number of bits
specified. (Each number is represented in memory by bits or binary digits i.e. 0
and 1) 2 << 2 gives 8 . 2 is represented by 10 in bits. Left shifting by 2 bits gives
1000 which represents the decimal 8 .

>> (right shift) Shifts the bits of the number to the right by the number of bits
specified. 11 >> 1 gives 5 . 11 is represented in bits by 1011 which when right
shifted by 1 bit gives 101 which is the decimal 5 .

& (bit-wise AND) Bit-wise AND of the numbers 5 & 3 gives 1 .

| (bit-wise OR) Bitwise OR of the numbers 5 | 3 gives 7

^ (bit-wise XOR) Bitwise XOR of the numbers 5 ^ 3 gives 6

~ (bit-wise invert) The bit-wise inversion of x is -(x+1) ~5 gives -6 .


< (less than) Returns whether x is less than y. All comparison operators return
True or False .

> (greater than) Returns whether x is greater than y 5 > 3 returns True . If both
operands are numbers, they are first converted to a common type. Otherwise, it
always returns False .

<= (less than or equal to) Returns whether x is less than or equal to y x = 3; y = 6; x
<= y returns True

>= (greater than or equal to) Returns whether x is greater than or equal to y x = 4;
y = 3; x >= 3 returns True

== (equal to) Compares if the objects are equal x = 2; y = 2; x == y returns True x =


'str'; y = 'stR'; x == y returns False x = 'str'; y = 'str'; x == y returns True

!= (not equal to) Compares if the objects are not equal x = 2; y = 3; x != y returns
True

not (boolean NOT) If x is True , it returns False . If x is False , it returns True . x =


True; not x returns False .

and (boolean AND) x and y returns False if x is False , else it returns evaluation of y
x = False; y = True; x and y returns False since x is False. In this case, Python will
not evaluate y since it knows that the left hand side of the 'and' expression is
False which implies that the whole expression will be False irrespective of the
other values. This is called short-circuit evaluation.

or (boolean OR) If x is True , it returns True, else it returns evaluation of y x =


True; y = False; x or y returns True . Short-circuit evaluation applies here as well.

Special operators:
Python defines the following 2 special operators
1. Identity Operators
2. Membership operators

1. Identity Operators
We can use identity operators for address comparison. 2 identity operators are
available
1. is
2. is not
Eg:
a=10
b=10
print(a is b) True
x=True
y=True
print( x is y) True

2. Membership operators:
We can use Membership operators to check whether the given object present in
the given collection. (It may be String, List, Set, Tuple or Dict) in  Returns True if
the given object presents in the specified Collection not in  Returns True if the
given object not present in the specified Collection

Eg:
x="hello learning Python is very easy!!!"
print('h' in x) True
print('d' in x) False
print('d' not in x) True
print('Python' in x) True

You might also like