Python Fundamentals

Python Character Set: Character set is asset of valid characters that a language can recognize.  A character can represents any letter, digit, or any other sign. Following are some of the python character set.

LETTERS                               A to Z and a to z

DIGITS                                   0 -9

SPECIAL SYMBOLS            space ,+ -* ^ \ [] {} = != < > . ‗ ‗ ; : & #, under score(_)

WHITE SPACE                     Blank space , horizontal tab ( – > ), carriage return , Newline, Form feed.

OTHER CHARACTERS      Python can process all ASCII and Unicode characters as part of data or  literals.

Tokens: The smallest individual unit in a program is known as token or lexical unit. A token can be any keyword, Identifier, Literals, Punctuators, and Operators.

1) Keywords: They are the words used by Python interpreter to recognize the structure of program. As these words have specific meaning for interpreter, they cannot be used for any other purpose.

A partial list of keywords in Python 3.6.x is

and del from not
while as elif global
or with assert else
if pass yield break
except import print class
exec in raise continue
finally is return def
for lambda try

2) Identifiers:  Identifiers are names given to identify something. Identifiers are fundamental building blocks of a program and are used as general terminology for the names given to different part of the program that is variables, objects, classes, functions, lists, dictionaries etc.

There are some rules you have to follow for naming identifiers:

  • The first character of the identifier must be a letter of the alphabet (uppercase ASCII or lowercase ASCII or Unicode character) or an underscore (‘_’).
  • The rest of the identifier name can consist of letters (uppercase ASCII or lowercase ASCII or Unicode character), underscores (‘_’) or digits (0-9).
  • Identifier names are case-sensitive.

For example, myname and myName are not the same.

Note the lowercase n in the former and the uppercase N in the latter.

  • Examples of valid identifier names are i, __my_name, name_23. Examples of ‘’invalid” identifier names are 2 things, this is spaced out, my-name, >a1b2_c3 and “this_is_in_quotes”.
  • An identifier must not be a keyword of Python.

3) Literals / Values: The data items which never change their value throughout the program run. There are several kind of literals:

  1. String Literals
  2. Numeric Literals
  3. Boolean Literals
  4. Special Literal None
  5. Literal Collections

1. String Literals: It is a sequence of letters surrounded by either by single or double or triple quotes. g  “abc” , ‘a’ , “raman”.

2. Numeric Literals: The numeric literals in Python can belong to any of the following different numerical types:

  • integer literals (both int and long): Integer constant (literal) must have at least one digit and must not contain any decimal point. It may contain either (+) or (-) sign. A number with no sign is assumed to be positive. Commas cannot appear in an integer constant.

For example: 12344, 41, +68, -23

 

  • Floating Point Literals: A real constant (literal) in fractional form must have at least one digit before a decimal point and at least one digit after the decimal point. It may also have either + or – sign preceding it. A real constant with no sign is assumed to be positive.

For example: 2.0 , 18.6 , -23.9 , +89.66

  • A real literal may be represented in Exponent form having Matissa and exponent with base 10 (E). Mantissa may be a proper real numbers while exponent must be integer.

The following are valid real in exponent form-

152E05, 1.52E07, 0.152E08, -0.12E-3, 1.5E+8

The following are invalid real exponent numbers-

172.E5, 1.7E, 0.17E2.3, 17,22E05, .25E-7

  • Complex number:

Complex number in python is made up of two floating point values, one each for              real and imaginary part. For accessing different parts of variable (object) x; we                will use x.real and x.image. Imaginary part of the number is represented by ‘j’                  instead of ‘i’, so 1+0j denotes zero imaginary part.

        For example

>>> x = 1+0j

>>> print x.real,x.imag

1.0 0.0

       Example

>>> y = 9-5j

>>> print y.real, y.imag

9.0 -5.0

3. Boolean Literals: A Boolean literals in Python is used to represent one of the two Boolean values that is True or A Boolean literal can either have value as True or as false.

A. Special Literal None:

  • None is a special type in Python that represents nothingness. For example, it is used to indicate that a variable has no value if it has a value of None.
  • The None literal is used to indicate something that has not yet been created. It is also used to indicate the end of lists.

          Python supports literal collections also such as tuples and list etc. these will                be discussed in next blog.

4. Punctuators:  The following nine ASCII characters are the separators:

( ) { } [ ] ; , . \ # @ : = ‘ “

5. Operators: Operators are special symbols that perform specific operations on one, two, or three operands, and then return a result.

Unary Operator:
Description Symbol Example 1 Example 2

unary plus

+

If x=10, then +x means 10 If x=-10, then +x means -10

unary minus

If x=10, then -x means -10 If x=-10, then +x means 10
Arithmetic Operator:

Addition

+

>>>10+5

15

>>>’Hello’+’Amjad’

HelloAmjad

Subtraction

>>>10-5

5

>>>30-70

-40

Multiplication

*

>>>10*5

50

>>>’Hello’*3

HelleoHelloHello

Division

/

>>>17/5

3

>>>17/5.0

3.4

>>>17.0/5

3.4

>>28/3

9

>>28/7.0

4.0

Remainder / Modulo

%

>>>16%5

1

>>>13%5

3

Exponent

**

>>>2**3

8

>>>16**0.5

4

Floor division (integer division)

//

>>>7.0//2

3.0

>>>5//2

2

 

Bitwise Operator:

We assume the operation1is X and Operation2 is Y for better understanding of these operators

Operation Operator Use Description

Bitwise AND

&

X & Y The AND operator compare two bits and generate a result of 1 if both bits are 1; otherwise, it return 0.

Bitwise exclusive OR (XOR)

^

X^Y The EXCLUSIVE – OR operator compare two bits and returns 1 if either of the bits are 1 and gives 0 if both bits are 0 and 1.

Bitwise OR

|

X | Y The OR operator compare two bits and generate a result of 1 if both bits are complementary; otherwise, it return 0.

Bitwise Complement

~

~X The COMPLEMENT operator is used to invert all of the bits of the operands.

Identity operator:

Is the identity same?

is

X ix Y Return True if both its operands are pointing to same object (i.e, both referring to same memory location), returns false otherwise

Is the identity not same?

is not

X is not Y Return True if both its operands are pointing to different object (i.e, both referring to different memory location), returns false otherwise

Relational Operator:

Less than

<

>>>5<7

True

>>>7<5

False

>>> 5<7<10

True

>>> 5<7 and 7<10

True

>>>’Hello’ < ‘Amjad’

False

>>>’Amjad’ < ‘Hello’

True

Greater than

<

>>>7>5

True

>>>10<10

False

>>>’Hello’ > ‘Amjad’

True

>>>’Amjad’ > ‘Hello’

False

Less than or equal to

>=

>>> 2<=6

True

>>> 6<=4

False

 <<< ‘Hello’ <=’Amjad’

False

>>>’Amjad’<=’Hello’

True

Greater than or equal to

>=

>>> 2>=6

False

>>> 6>=4

True

 <<< ‘Hello’ >=’Amjad’

True

>>>’Amjad’>=’Hello’

False

Equal to

==

>>> 5==5

True

>>>10==11

False

>>>’Hello’==’Hello

True

>>>’Hello’==’Good Bye’

False

Not equal to

!= , < >

>>>10!=11

True

>>>10!=10

False

>>>’Hi!=’HI’

True

>>>’HI’!=’HI’

False

 

Assignment Operators: and Shorthand Assignment Operators

We assume the value of variable p as 10 for better understanding of these operators

=

Assignment It is use to assign the value to the variable a=6 A will become 6
/=

Assign quotient

Divided and assign back the result to left operand >>> p/=2 p will become 5
+=

Assign sum

Added and assign back the result to left operand >>> p+=2 p will become 12

*=

Assign product multiplied and assign back the result to left operand >>> p*=2 p will become 20
%= Assign remainder Taken modulus using two operands and assign the result to left operand >>> p%=2 p will become 0

-=

Assign difference subtracted and assign back the result to left operand >>> p-=2 p will become 8

**=

Assign Exponent Performed exponential(power) calculation on operators and assign value to the left operand >>> p**=2 p will become 100

//=

Assign floor division Performed floor division on operators and assign back the result to left operand >>> p//=2 p will become 5

Logical Operators:

and Logical AND X and Y If  both the operand is true, then the condition becomes True
or orLogical OR X or Y If any one of the operand is true, then the condition becomes True
not Logical NOT not X Reverses the state of the operand/ condition.
Membership Operators:
in Whether variable in sequence The in operator tests if a given value is contained in a sequence or not and return True or False Accordingly >>>3 in [1,2,3,4]

True

not in Whether variable not in sequence The not in operator tests if a given value is contained in a sequence or not and return True or False Accordingly >>>6 not in [1,2,3,4,5]

True (Because the value 6 is not in the sequence.)

>>>4 not in [1,2,3,4,5,6]

False

Structure of the Python’s Program

structureofprogram

So the above sample program contains various components:

  1. Expressions
  2. Statements
  3. Comments
  4. Function
  5. Blocks and indentation

1. Expressions:

An expression is any legal combination of symbols that represents a value.

For example

  1. c=a+b
  2. s>0

2. Statement:

A statement is a programming instruction that does something.

For example

  1. print (“The sum is:”,c)
  2. if s>0:

3.Comments:

Comments are any text to the right of the # symbol and are 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’)

Use as many useful comments as you can in your program to:

  • explain assumptions
  • explain important decisions
  • explain important details
  • explain problems you’re trying to solve
  • explain problems you’re trying to overcome in your program, etc.

 Code tells you how, comments should tell you why.

Two types of comments:

Single line Comment: # marks start of single line comment that must not be inside a string literal. All characters after the #

and up to the physical line end are part of the comment, and the Python interpreter ignores them.   Example

def getline():

return sys.stdin.readline()    # Get one line and return it

Multi – Line Comment:     Comments can be break up into multiple lines by inserting a multiline string with ”’as the delimiter one each end.

Example

def getline():

return sys.stdin.readline()            ”’this function

gets one line

and returns it’’’

4. Function:

A function is a group of statements that exist within a program for the purpose of performing a specific task and it can be reused (executed again) by specifying its name in the program, where needed.

How to define and Call a function in python:

A user-defined Python function is created or defined by the def statement followed by the function name and parentheses (()) as shown in the syntax given below:

Syntax:

def function_Name (comma_separated_list_of_parameters):

statements

NOTE: Statement below def begin with four spaces. This is called indentation. It is a requirement of Python that the code following a colon must be indented.

For Example

def sum ():                          #function definition of sum()

a=int (input ())

b=int (input ())

c=a+b

print(“The sum is “,c)

return c

print (“Enter any valid two integers”)

s=sum()            # Calling above defined function sum()

5. Block and Indentation:

A group of statements which are part of another statement or a function are called block or code – block or suite in Python.

Consider the following Example:

if n1<n2:

Tmp =n1

n1=n2

n2=Tmp

print “I Understand Block”

One of the most remarkable difference between Python and other most common programming  languages like C, C++, C#, Java will be encounter programmer’s is that in Python indentation is  very  important and there are no braces to indicate blocks of code for class and function definitions  or  flow control. There are no end/begin delimiters like {}.

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.

Python uses indentation to create blocks of code. Statements at same indentation level are part of same block / suite.

Statements requiring suite / code bloc have a colon (:) at their end.

You cannot unnecessarily indent a statement; Python will raise error for that.

Another Example:

Picture1

 Variables:

Variables are exactly what the name implies – their value can vary, i.e., you can store anything using a variable. Variables are just parts of your computer’s memory where you store some information.

Named labels, whose values can be manipulated during program run, are called Variables.

Creating a Variable:

Python variables are created by assigning value of desired type to them, example: to create a numeric variable, assign a numeric value to variable_name; to create a sting variable, assign a string value to variable_name and so on.

Example:

X=10.8                                    # variable created of numeric (floating point) type

Y = 90                                     # variable created of numeric (integer) type

Name = “My Name”           # variable created of string type

Multiple Assignments:

  1. Assigning same value to multiple variables:

x = y = z = 100

It will assign value 100 to all three variables x, y and z.

  1. Assigning multiple value to multiple variables

p, q, r = 10, 20, 30

It will assign the value order wise that is value 10 assign to variable p, value 20 assign to variable q and value 30 assign to variable r.

IMPORTANT NOTE:

A variable is defined only when you assign some value to it. Using an undefined variable in an expression / statement cause error.

Example:
print (a)
              # Error name ‘a’ not defined

a = 20                                   

 print (a)

correct code:

a=10

print (a)

a = 20

print a)

While writing Python statements, keep the following points in mind:

  1. Write one python statement per line (Physical Line). Although it is possible to write two statements in a line separated by semicolon.
  2. Comment starts with “#” outside a quoted string and ends at the end of a line. Comments are not part of statement. They may occur on the line by themselves or at the end of the statement. They are not executed by interpreter.
  3. For a long statement, spanning multiple physical lines, we can use ‘/’ at the end of physical line to logically join it with next physical line. Use of the ‘/’ for joining lines is not required with expression consists of ( ), [ ], { }
  4. When entering statement(s) in interactive mode, an extra blank line is treated as the end of the indented block.
  5. Indentation is used to represent the embedded statement(s) in a compound/ Grouped statement. All statement(s) of a compound statement must be indented by a consistent no. of spaces (usually 4)
  6. White space in the beginning of line is part of indentation, elsewhere it is not significant.

Input and Output

A Program needs to interact with end user to accomplish the desired task, this is done using Input-Output facility. Input means the data entered by the user (end user) of the program. While writing algorithm(s), getting input from user was represented by Take/Input. In python, we have raw-input() and input ( ) function available for Input.

                        Picture1

If prompt is present, it is displayed on the monitor after which user can provide the data from keyboard. The function takes exactly what is typed from keyboard, convert it to string and then return it to the variable on LHS of “=”.

Example (in interactive mode)

>>>x=raw_input (“Enter your name: “)

Enter your name: ABC

x is a variable which will get the string (ABC), typed by user during the execution of program. Typing of data for the raw_input function is terminated by „enter‟ key. We can use raw_input() to enter numeric data also. In that case we typecast, i.e., change the datatype using function, the string data accepted from user to appropriate Numeric type.

Example

y=int(raw_input(“enter your roll no”))

enter your roll no. 5

will convert the accepted string i.e. 5 to integer before assigning it to ‘y’.

input()

Syntax for input() is:

Input ([prompt])

            Optional

If prompt is present, it is displayed on monitor, after which the user can provide data from keyboard. Input takes whatever is typed from the keyboard and evaluates it. As the input provided is evaluated, it expects valid python expression. If the input provided is not correct then either syntax error or exception is raised by python.

Example

x= input (“enter data:”)

Enter data: 2+1/2.0

Will supply 2.5 to x input ( ), is not so popular with python programmers as:

  1. i) Exceptions are raised for non-well formed expressions.
  2. ii) Sometimes well formed expression can wreak havoc.

Output is what program produces. In algorithm, it was represented by print. For output in Python we use print. We have already seen its usage in previous examples. Let’s learn more about it.

Important Link 

Python: More on input( ) function

Print Statement

Syntax:

print (expression/constant/variable)

Print evaluates the expression before printing it on the monitor. Print statement outputs an entire (complete) line and then goes to next line for subsequent output (s). To print more than one item on a single line, comma (,) may be used.

Example

>>> print (“Hello”)

Hello

>>> print (5.5)

5.5

>>> print (4+6)

10

Try this on the computer and evaluate the output generated

>>>print (3.14159* 7**2)

>>>print (“I”, “am” + “class XI”, “student”)

>>>print (“I’m”)

>>>print (“class XI student”)

>>print( “I’m “, 16, “years old”)

Important Link

Python: More on Print( ) function

Difference between input ( ) and raw_input ( ) method

input() raw_input()
Converts the user input to the right   matching python

type (int, str, list, tuple, dict etc.,)

For instance in the statement below:

a = input(‘Enter a value: ‘)

print type(a)

if user entered 1 then it is int

if user entered ‘Python’ then it is str

if user entered [1,2,3] then it is dict

Converts the user input always to string.

For instance in the statement below

a = raw_input(‘Enter a value: ‘)

print type(a)

Regardless of value entered by the type is always

string

Use when you write program quickly for yourself or for expert users since  you would not  need to any type conversion. Use when you write program for non expert users since you can handle exceptions  when converting from string to your  expected type.
Removed in Python 3 Renamed as input in Python 3
>>> n = input(“Please enter a value: “)

Please enter a value: 23

>>> n

23         # value returned as int

>>> n = raw_input(“Please enter a value: “)

Please enter a value: 23

>>> n

’23’       # value returned as str

Leave a comment