Advertisement

Tuesday, December 3, 2019

The range( ) function

  • It generates a list of numbers, which is generally used to iterate over with for loop. 
  • range( ) function uses three types of parameters, which are: 
  • start: Starting number of the sequence.
  • stop: Generate numbers up to, but not including last number.
  • step: Difference between each number in the sequence. 

Python use range( ) function in three ways: 

  1. range(stop)
  2. range(start, stop)
  3. range(start, stop, step) 

Note: 


  • All parameters must be integers. 
  • All parameters can be positive or negative.

1. range(stop): By default, It starts from 0 and increments by 1 and ends up to stop, but not including stop value. 
Example: 
for x in range(4): 
print(x) 
Output: 

2. range(start, stop): It starts from the start value and up to stop, but not including stop value. 
Example: 
for x in range(2, 6): 
print(x) 
Output: 
3. range(start, stop, step): Third parameter specifies to increment or decrement the value by adding or subtracting the value. 
Example: 
for x in range(3, 8, 2): 
print(x) 
Output: 
7

Explanation of output: 

3 is starting value, 8 is stop value and 2 is step value. First print 3 and increase it by 2, that is 5, again increase is by 2, that is 7. The output can’t exceed stop-1 value that is 8 here. So, the output is 3, 5, 8. 

Difference between range( ) and xrange( ):


Loops in Python

Another one of the control flow statements is loops. 
  • Execute a set of statements that are repeated until a particular condition is satisfied.
  • Loops are used when we want to repeat a block of code to run a number of times.


Basically there are two types of loops in python programming


  1. for loop
  2. while loop 

For loop

For loop is a control flow statement in which the control of the program is continuously transferred to the beginning to execute the body of for loop for a fixed number of times.

Syntax of for loop
                            for a in sequence:
                            body of for
  1. The for loop iterate over a given sequence (it may be list, tuple or string). 
  2. Note: The for loop does not require an indexing variable to set beforehand, as the for command itself allows for this. 

Example
primes = [2, 3, 5, 7] 
for x in primes: 
print(x)

while loop

  • With the help of while loop we can execute a set of statements as long as a condition is true. 
  • It requires to define an indexing variable.

Syntax of While Loop
                while test_expression:
                body of while

Example
To print table of number 2
                        i=2
                        while i<=20:
                        print(i)
                        i+=2

Note:- While other languages contain conditions and increment expression in the syntax of for loop, in Python, the iteration and incremented value are controlled by generating a sequence. 

The range( ) function:

Friday, November 29, 2019

Flow Control in Python.

In this session of flow control and looping in python we will learn about working of loop and controlling the flow of statements, there has always been a series of statements faithfully executed by Python in exact top-down order. What if you wanted to change the flow of how it works? 



  • For example, you want the program to take some decisions and do different things depending on different situations, such as printing 'Good Morning' or 'Good Evening' depending on the time of the day?

According to the above situation it can be categorized into three parts.
  • Decision Making and branching (Conditional Statement)
  • Looping or Iteration
  • Jumping statements


Decision making is about deciding the order of execution of statements based on certain conditions. Decision structures evaluate multiple expressions which produce TRUE or FALSE as outcome.

There are three types of conditions in python:
  1. if statement
  2. if-else statement
  3. elif statement

if statement: 

  • It is a simple if statement. When condition is true, then code which is associated with if statement will execute.


Example:


a=40
b=20
if a>b:
print(“a is greater than b”)

2. if-else statement: 

  • When the condition is true, then code associated with if statement will execute, otherwise code associated with else statement will execute.
Example:

a=10
b=20
if a>b:
print(“a is greater”)
else:
print(“b is greater”)

3. elif statement: 

  • It is short form of else-if statement. If the previous conditions were not true, then do this condition". It is also known as nested if statement.
Example:

a=input(“Enter first number”)
b=input("Enter Second Number:")
if a>b:
print("a is greater")
elif a==b:
print("both numbers are equal")
else:
print("b is greater")

Tuesday, November 19, 2019

Variable in Python.


Variable/Label in Python


  • Definition: Named location that refers to a value and whose value can be used and processed during program execution.
  • Variables in python do not have fixed locations. The location they refer to changes every time their values change.

Creating a variable: 

  • A variable is created the moment you first assign a value to it. 
  • Example: x = 5 y = “hello” Variables do not need to be declared with any particular type and can even change type after they have been set. 
  • It is known as dynamic Typing. x = 4 # x is of type int x = "python" # x is now of type str print(x) 

Rules for Python variables: 

  • A variable name must start with a letter or the underscore character.
  • A variable name cannot start with a number.
  • A variable name can only contain alpha-numeric characters and underscore (A-z, 0-9, and _ ).
  • Variable names are case-sensitive (age, Age and AGE are three different variables)
  • Python allows assign a single value to multiple variables. Example: x = y = z = 5 You can also assign multiple values to multiple variables. 
  • For example −

x , y , z = 4, 5, “python”
4 is assigned to x, 5 is assigned to y and string “python” assigned to variable z respectively.
x=12
y=14
x,y=y,x
print(x,y)
Now the result will be
14 12

Lvalue and Rvalue:


  • An expression has two values. Lvalue and Rvalue.
  • Lvalue: the LHS part of the expression.
  • Rvalue: the RHS part of the expression.
  • Python first evaluates the RHS expression and then assigns to LHS.

Example:
p, q, r= 5, 10, 7
q, r, p = p+1, q+2, r-1
print (p,q,r)
Now the result will be:
6  6  12
Note: Expressions separated with commas are evaluated from left to right and assigned in same order.

  • If you want to know the type of variable, you can use type( ) function :

Syntax:
        type (variable-name)
  Example:
                     x=6
                     type(x)
The result will be:
<class ‘int’>

  • If you want to know the memory address or location of the object, you can use id( ) function.

Example:
>>>id(5)
1561184448
>>>b=5
>>>id(b)
1561184448

  • You can delete single or multiple variables by using del statement. 
Example:
del x
del y, z

Input from a user:


  • input( ) method is used to take input from the user.

Example: 
print("Enter your name:") x = input( ) print("Hello, " + x)
  • input() function always returns a value of string type.

Type Casting:

  • To convert one data type into another data type. Casting in python is therefore done using constructor functions.
int( ) - constructs an integer number from an integer literal, a float literal or a string literal. 
Example: 
                  x = int(1) # x will be 1 
                  y = int(2.8) # y will be 2 
                  z = int("3") # z will be 3.
float( ) - constructs a float number from an integer literal, a float literal or a string literal. Example: 
                   x = float(1) # x will be 1.0 
                   y = float(2.8) # y will be 2.8 
                   z = float("3") # z will be 3.0 
                   w = float("4.2") # w will be 4.2.

str( ) - constructs a string from a wide variety of data types, including strings, integer literals and float literals. 
Example: 
                   x = str("s1") # x will be 's1' 
                   y = str(2) # y will be '2' 
                   z = str(3.0) # z will be '3.0'


Reading a number from a user:

x= int (input(“Enter an integer number”))
2.8 OUTPUT using print( ) statement:
Syntax:
print(object, sep=<separator string >, end=<end-string>)

  • object : It can be one or multiple objects separated by comma.
  • sep : sep argument specifies the separator character or string. It separate the objects/items. By default sep argument adds space in between the items when printing.
  • end : It determines the end character that will be printed at the end of print line. By default it has newline character( ‘\n’ ).

Example:
x=10
y=20
z=30
print(x,y,z, sep=’@’, end= ‘ ‘)
Output:
10@20@30

Basic terms of a Python Programs.


  1. Blocks and Indentation
  2. Statements
  3. Expressions
  4. Comments

1. Blocks and Indentation:

  • Python provides no braces to indicate blocks of code for class and function definition or flow control.
  • Maximum line length should be maximum 79 characters.
  • Blocks of code are denoted by line indentation, which is rigidly enforced.
  • The number of spaces in the indentation is variable, but all statements within the block must be indented the same amount.

for example –
if True:
print(“True”)
else:
print(“False”)
2. Statements

  • A line which has the instructions or expressions.

3. Expressions:

  • A legal combination of symbols and values that produce a result. Generally it produces a value.

4. Comments: 

  • Comments are not executed. 
  • Comments explain a program and make a program understandable and readable. 
  • All characters after the # and up to the end of the physical line are part of the comment and the Python interpreter ignores them.
There are two types of comments in python:

  • Single line comment.
  • Multi-line comment.

Single line comment: 

  • This type of comments start in a line and when a line ends, it is automatically ends. Single line comment starts with # symbol.
  • Example: if a>b: # Relational operator compare two values.

Multi-Line comment: 

  • Multi line comments can be written in more than one lines. 
  • Triple quoted ‘ ’ ’ or “ ” ”) multi-line comments may be used in python. 
  • It is also known as docstring.

Example:
‘’’ This program will calculate the average of 10 values.
First find the sum of 10 values
and divide the sum by number of values
‘’’
Multiple Statements on a Single Line:
  • The semicolon ( ; ) allows multiple statements on the single line given that neither statement starts a new code block.
  • Example:-

          x=5; print(“Value =” x)

Python Fundamentals.

Python Character Set :

  • It is a set of valid characters that a language recognize.
  • Letters: A-Z, a-z
  • Digits : 0-9
  • Special Symbols
  • White space

Tokens

Token: Smallest individual unit in a program is known as token.
There are five types of token in python:
1. Keyword
2. Identifier
3. Literal
4. Operators
5. Punctuators

1. Keyword: 


  • Reserved words in the library of a language. 
  • There are 33 keywords in python.

  • All the keywords are in lowercase except 03 keywords (True, False, None).

2. Identifier: 

  • The name given by the user to the entities like variable name, class-name, function-name etc.

Rules for identifiers: 

  • It can be a combination of letters in lowercase (a to z) or uppercase (A to Z) or digits (0 to 9) or an underscore.
  • It cannot start with a digit.
  • Keywords cannot be used as an identifier.
  • We cannot use special symbols like !, @, #, $, %, + etc. in identifier.
  • _ (underscore) can be used in identifier.
  • Commas or blank spaces are not allowed within an identifier. 

3. Literal: 

  • Literals are the constant value. Literals can be defined as a data that is given in a variable or constant.

A. Numeric literals: Numeric Literals are immutable. Eg. 5, 6.7, 6+9j
B. String literals: String literals can be formed by enclosing a text in the quotes. We can use both single as well as double quotes for a String. Eg: "Aman" , '12345'

  • Escape sequence characters:


C. Boolean literal: A Boolean literal can have any of the two values: True or False.
D. Special literals: Python contains one special literal i.e. None. 
None is used to specify to that field that is not created. It is also used for end of lists in Python. 
E. Literal Collections: Collections such as tuples, lists and Dictionary are used in Python.

4. Operators: 

  • An operator performs the operation on operands. Basically there are two types of operators in python according to number of operands:

A. Unary Operator
B. Binary Operator
A. Unary Operator: Performs the operation on one operands.

Example:

+ Unary plus
- Unary minus
~ Bitwise complement
not Logical negation

B. Binary Operator: Performs operation on two operands.

5. Separator or punctuator :

      , ; , ( ), { }, [ ]
2.3 Mantissa and Exponent Form:
A real number in exponent form has two parts:
  • mantissa
  • exponent

Mantissa : It must be either an integer or a proper real constant.
Exponent : It must be an integer. Represented by a letter E or e followed by integer value.






Python Program to Transpose a Matrix.

# Program to transpose a matrix using a nested loop
X = [[12,7],
    [4 ,5],
    [3 ,8]]
result = [[0,0,0],
         [0,0,0]]
# iterate through rows
for i in range(len(X)):
   # iterate through columns
   for j in range(len(X[0])):
       result[j][i] = X[i][j]
for r in result:
   print(r)


Python Program to Count the Number of Each Vowel.

# Program to count the number of each vowels
# string of vowels
vowels = 'aeiou'
ip_str = 'Hello, have you tried our tutorial section yet?'
# make it suitable for caseless comparisions
ip_str = ip_str.casefold()
# make a dictionary with each vowel a key and value 0
count = {}.fromkeys(vowels,0)
# count the vowels
for char in ip_str:
   if char in count:
       count[char] += 1
print(count)


Python Program to Sort Words in Alphabetic Order.

# Program to sort alphabetically the words form a string provided by the user
my_str = "Hello this Is an Example With cased letters"
# To take input from the user
#my_str = input("Enter a string: ")
# breakdown the string into a list of words
words = my_str.split()
# sort the list
words.sort()
# display the sorted words
print("The sorted words are:")
for word in words:
   print(word)


Python Program to Add Two Matrices.

# Program to add two matrices using nested loop
X = [[12,7,3],
    [4 ,5,6],
    [7 ,8,9]]
Y = [[5,8,1],
    [6,7,3],
    [4,5,9]]
result = [[0,0,0],
         [0,0,0],
         [0,0,0]]
# iterate through rows
for i in range(len(X)):
   # iterate through columns
   for j in range(len(X[0])):
       result[i][j] = X[i][j] + Y[i][j]
for r in result:
   print(r)