Python Programming – Conditional and Iterative Statements

Python Programming – Conditional and Iterative Statements

You can learn about Control Statements in Python Programs with Outputs helped you to understand the language better.

Python Programming – Conditional and Iterative Statements

Control statements define the direction of flow according to which execution of a program should take place. Statements that are executed one after the other or the statements that are executed sequentially are the normal flow-of-control statements in a program. Normally, the Python program begins with the first statement and is executed till the end (Sequence construct). [See Figure 5.1.] Control statements also implement decisions and repetitions in programs.

Python Programming – Conditional and Iterative Statements chapter 5 img 1

Construct Control statements are of the following two types:

  • Conditional branching or statement
  • Looping or iteration

In Conditional branching, a program decides whether or not to execute the next statement(s), based on the resultant value of the current expression. For example, go to IInd year if you pass Ist year exams, else repeat Ist year (See Figure 5.2).
In Looping, a program executes a set of instructions repeatedly till the given condition is true. Looping, for example, adds 1 to the number x till the current value of x becomes 100. It is also called iteration. Iteration is a process of executing a statement or a set of statements repeatedly until the specified condition is

Python Programming – Conditional and Iterative Statements chapter 5 img 2

Jump statement

All the control structures are explained further in the following sections.

Those statements which transfer which program con-trial, unconditionally within the program, from one place to another are called jump statements. These statements included the following:

(a) break statements
(b) continue statements
(c) pass statements

Break Statement

The break statement causes an immediate exit from the innermost loop structure. it transfers control out of while or for structure. It is mostly required when, due to some external condition, you need to exit from a loop. If you need to come out from a running program immediately without letting it perform any further operation in a loop, then you can break the statement. the break statement exits the current loop (for or while) and transfers control to the statement immediately following
the control structure.
Figure 5.51 shows the use of the break statement.

Example
Demo of a break statement.

# Demo of using break statement
count = 1
while(count > 0):
print (“Count :11, count) count += 1
#Breaks out of the while loop when counting>5
if(count>5):
break
print(“End of Program”)RUN
>>>
Count : 1
Count : 2
Count : 3
Count : 4
Count : 5
End of Program
>>>

Note that in the following example, the break statement causes the program to immediately exit the loop; so it will print COMP.

Example
Demo of a break statement.

# Demo of using break statement
for ch in ‘COMPUTER’:
if ch == ‘U’:
break
print(ch)RUN
>>>
C
0
M
P
>>>

pass STATEMENT

The pass statement in python is used when a statement is required syntactically, but you want any command or code to execute.
this sentiment is a null operation; nothing happens when it executes. The pass is also useful in places when your code will eventually go,
but it has not been written yet.
For example,

if ( condition ) :
pass

it can be used as a placeholder while you are writing code. For example, you may write an if statement and you want to try it, but you do not have the code for one of your blocks. considered the following:
name = input ( ‘ Enter your name: ‘)
Print (‘ welcome! ‘ )
e1if ( name== ‘ Remesh ‘ )
# not finished yet…
e1if ( name== ‘ Rohan ‘ )
print (‘ Access Denied ‘)
This code wlii not run because an empty block is illegal in python. To fix this simply add the pass statement to the middle block:
name=input(‘Enter your name: ‘)
if(name==’Ram’):
print(‘Welcome!’)
elif(name==’Ramesh’):
# Not finished yet…
pass
elif(name==’Rohan’):
print(‘Access Denied’)

సాయి మనస్సు మణిహారములు

Python Programming – Standard Data Types

Python Programming – Standard Data Types

You can learn about Introduction to Python Programming Programs with Outputs helped you to understand the language better.

Python Programming – Standard Data Types

The data stored in memory can be of many types. For example, a person’s age is stored as a numeric value, and his or her address is stored as alphanu¬meric characters. Python is known as a dynamically typed language, which means that you do not have to explicitly identify the data type when you ini¬tialize a variable. Python knows, based on the value it has been given, that it should allocate memory for a string, integer, or float. It has various standard types that are used to define the operations possible on them and the storage method for each of them. It has different data types such as Number, String, List, Tuple, and Dictionary.

Note that everything is an object in Python programming; data types are actually classes and variables are instances (objects) of these classes like most other languages.

Number

Number data types store numeric values. They are immutable (value of its object cannot be changed) data types, which means that changing the value of a number data type results in a newly allocated object. Number objects are created when you assign a value to them. For example,
num1 = 5
num2 = 7
Python automatically converts different types of numbers so that you (usually) do not need to think about the compatibility of different number types. For example, if you do a mathematical operation with both integers and floats, Python converts the integers into floats and gives the result as afloat. There are three numeric types in Python: int, float, and complex. Variables of numeric types are created when you assign a value to them. To verify the type of any object in Python, use the type() function:
X = 1 # int
y = 2.8 # float
z = 1j # complex
The three numerical types of Python are discussed below:

int (integer)

Positive or negative whole numbers (without a fractional part) are called integers. Integers are of two types Integers-(signed) and Booleans. int is the basic integer data type. It is a whole number, positive or negative, without decimals, of unlimited length. It cannot hold fractional values. Examples of integer are 5, 34, 92, -43, -3255522, etc. Do not use commas to separate digits and also integers should not have leading zeroes.
The boolean type can take only one of two values, True and False. These correspond to 1 and 0. This is the most appropriate return type for a function that uses its return value to express whether some condition holds true or not.

The following integer literals are recognized by Python:

a. Decimal Integer literals (base 10): An integer literal consists of a sequence of digits. For example, 245, -96, 53, etc.

b. Octal Integer literals (base 8): An octal value can contain digits 0 to 7. 8 and 9 are invalid dig-its an octal integer. To indicate an octal number, you will use the prefix Oo or OO (zero followed by either a lowercase or uppercase letter ‘o’). For example, 004, 0ol4, etc.

c. Hexadecimal Integer literals (base 16): To indicate hexadecimal literals, you will use the prefix ‘OX’ or ‘Ox’ (zero and uppercase or lowercase letter ‘X’).

float (floating point real values)

Numbers with fractions or decimal points are called floating-point numbers. For example, 0.34, .07, -12.9, 34.2963, etc. Float numbers can be positive or negative. They can also be used to represent a number in scientific dr exponent notation. For example, -3.0 X 105 is represented as -3.0e5.

complex (complex numbers)

A complex number is an extension of the familiar real number system in which all numbers are expressed as a sum of a real part and an imaginary part. A complex number consists of an ordered pair of real floating-point numbers denoted by a + bj, where a is the real part and b is the imaginary part of the complex number. The imaginary part is written with a j suffix, e.g., 3+lj. Python has built-in support for complex numbers.
For example,

>>> x=3+1j
>>> print( X . real , X . imag )
3.0 1.0
There may be times when you want to specify a type for a variable. This can be done with casting. Python is an object-orientated language, and it uses classes to define data types, including its primitive types. It provides a special function called type that tells us the data type of any value.

>>> type(72)
<class ‘ int ‘ >
>>>
>>> type(“string”)
<class ‘str’>
>>>
>>> type(98.7)
<class ‘float’>
>>>
<class ‘int’> indicates that the type of 72 is int. Simi-larly, <class ‘str’> and <class ‘float’> indicate that “string” and 98.7 are of type str and float, respectively.

  • In Python, the floating-point numbers have the precision of 15 digits, i.e., double precision.

Integers and floats are data types that deal with numbers. Sometimes you need to convert an integer to a float or vice-versa. To convert integer to float, use the float() function; and to convert a float to an integer, use the int( ) function. You can also convert numbers to strings by using the str( ) method.

Let’s Try

Write datatype for the following:

>>> type ( 4 )
>>> type ( 3 . 14 )
>>> type ( 2 . 0 )
>>> a= -53
>>> type ( a )

What is typecasting?

Typecasting is a process of explicitly specifying types of variables in a programming language.

Example 2.
Program demonstrating working of typecasting.

# Program demonstrating working of typecasting
x=10
y= “2”
z=int(y) # convert string to integer using int( )
sum=x+z
print(sum)RUN
>>>
12
>>>

Sometimes you need to convert data type. For example, if you want to add two numbers in which one value of a variable is an integer, and the second is a string. Then you need to use typecasting to convert string data type into an integer before you perform addition (See Figure 3.24). Casting in Python is done using constructor functions as given below: into – It constructs an integer number from an integer literal, afloat literal (by rounding down to the previous whole number), or a string literal (provided that the string represents a whole number). For example,

x = int ( 1 )       # X will be 1
y = int ( 2 . 8 )  # Y will be 2
z = int ( ” 3 ” )  # Z will be 3

float ( ) – It constructs a float number from an integer literal, afloat literal or a string literal (provided that the string represents a float or an integer). For 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( ) – It constructs a string from a wide variety of data types, including strings, integer literals, and float literals. For example,
x = str ( ” s1 ” )     # x will be ‘ s1’
y = str ( 2 )           # y will be ‘ 2 ‘
z = str ( 3 . 0 )     # z will be ‘ 3 . 0 ‘

  • Converting one data type to another data type is called typecasting.

Let’s Try

What will be the output of the following float casting operations?

# float casting operations
x=float ( 5 )
y=float ( 20 . 0 )
z=float ( ” 80 ” )
print ( X )
print ( Y )
print ( Z )

Let’s Try

What will be the output of the following int casting operations?

# int casting operations
x=int ( 5 )
y=int ( 20 . 0 )
z=int ( ” 80 ” )
print ( X )
print ( Y )
print ( Z )

Let’s Try

What will be the output of the following string casting operations?

# String casting operations
x=str ( 5 )
y=str ( 20 . 0 )
z=str ( ” 80 ” )
print ( X )
print ( Y )
print ( Z )

The range of Python numbers

The range of numbers supported by Python numeric data types is discussed below:

  1. Integer numbers can be of any length, only limited by available memory.
  2. Booleans can have only two permissible values True(1) or False(0).
  3. Float numbers can be of unlimited range, depending on machine architecture.
  4. Complex numbers range is the same as floating-point numbers because the real part and imaginary part both are represented internally as float values.

Real

Real numbers, or floating-point numbers, are represented in Python according to the IEEE 754 double-precision binary floating-point format, which is stored in 64 bits of information divided into three sections: sign, exponent, and mantissa.

Sets

Python has a data type called a set. Sets work like mathematical sets. They are a lot like lists with no repeats. Sets are denoted by curly braces.

String

Strings in Python are identified as a contiguous set of characters in between quotation marks. Python allows for either pair of single or double-quotes.

Example 3.
Program demonstrating working with string

str = ‘Hello Python’
print( str ) # Prints complete string
print( str [ 0 ] ) # Prints first character of the string
print( str [ 2 : 5 ] ) # Prints characters starting from 3rd to 5th
print( str [ 2 : ] ) # Prints string starting from 3rd character
print( str * 2 ) # Prints string two times
print( str + ” PROGRAMMING ” ) # Prints concatenated stringRUN
>>>
Hello Python
H
llo
llo Python
Hello PythonHello Python
Hello PythonPROGRAMMING
>>>

So ‘hello’ is the same as “hello”. A string can have any number of characters in it, including 0. The empty string is ” (two quote characters with nothing between them). The string with length 1 represents a character in Python. The plus ( + ) sign is the string concatenation operator, and the asterisk ( * ) is the repetition operator. Strings are defined using quotes (“, ‘, or ” ” ” ).

>>> st = “Hello World”
>>> st = ‘Hello World
>>> st = ” ” ” This is a multi-line string that uses triple quotes.” ” ”
Strings can be displayed on the screen using the print function. For example:
print(“hello”) # It will print hello

  • In Python, the # symbol is used to add comments. Everything from the # to the end of the line is ignored.

Like many other popular programming languages, strings in Python are arrays of bytes representing Unicode characters. However, Python does not have a character data type; a single character is simply a string with a length of one. For example ‘a’, ‘b’, ‘c’ are strings of length one. Square brackets can be used to access elements of the string.

  • In Python, there are no limits to the number of char¬acters you can put in a string. A string, having 0 characters, is known as an empty string.

a = “hello”
print(a[1]) # it will print e
Slicing is a mechanism used to select a range of items from sequence types like list, tuple, and string. It is beneficial and easy to get elements from a range by using slice way. It requires a : (colon) which sep¬arates the start and end index of the field in square brackets.

List

Python has a basic notation of a kind of data structure called a container, which is basically any object that can contain other objects. The two main kinds of containers are sequences (such as lists and tuples) and mappings (such as dictionaries).
Lists are the most versatile form of Python com¬pound data types. A list contains items separated by commas and enclosed within square brackets ([ ]). For example,
>>> li = [” abc “, 34, 4.34, 23]
To some extent, lists are similar to arrays in C. Difference between them is that all the items belonging to a list can be of different data types (heterogeneous). The values stored in a list can be accessed using the slice operator ( [ ] and [: ] ) with indexes starting at 0 at the beginning of the list and working their way to end-1. The plus ( + ) sign is the list concatenation operator, and the asterisk ( * ) is the repetition operator.

You can access individual members of a list in the following way:
>>> li = [ “abc” , 34 , 4 . 34 , 23 ]
>>> li [ 1 ] # Second item in the list.
34
Unlike strings which are immutable, it is possible to change individual elements and the size of the list.

Tuples

A tuple is like a list whose values cannot be modified once they have been created (enclosed in regular brackets). In other words, the tuple is immutable. Another way to think about tuples is to consider them to be a constant list. Tuples have elements that are indexed starting at 0. Items in a tuple are accessed using a numeric index.
>>> x = ( ‘ Vivek ‘ ,  ‘ Abhishek ‘ ,  ‘ Arti ‘ )
>>> print( x [ 2 ] )
Arti
>>> y = (1 , 9 , 2 )
>>> print ( y )
( 1 ,  9 ,  2 )
>>> print ( max ( y ) )
9

Dictionary

Dictionaries are Python’s most powerful data col-lection. Dictionaries store a mapping between a set of keys and a set of values. They allow us to do fast database-like operations in Python. They literals use curly braces and have a list of key : value pairs. You can make an empty dictionary also. Dictionaries are written like this:
>>> pword = { ‘Amit’ : ‘chuck’ , ‘Beena’ : ‘permit’, ‘Deepak’: ‘grant’}
>>> print(pword)
{ ‘Amit’ : ‘chuck’ , ‘Beena’ : ‘permit’, ‘Deepak’: ‘grant’}
>>> ooo = {  }
>>> print(ooo)
{ }

Dictionaries consist of pairs (called items) of keys and their corresponding values. In this example, the names are the keys and the passwords are the val¬ues. Each key is separated from its value by a colon (:); the items are separated by commas and the whole thing is enclosed in curly braces. An empty dictionary (without any items) is written with just two curly braces, like this: {}.

Sets

Python also includes a data type for sets. A set is an unordered collection with no duplicate elements. Basic uses include membership testing and eliminating duplicate entries. Set objects also support mathematical operations like union, intersection, difference, and symmetric difference.
Curly braces or the set( ) function can be used to create sets. To create an empty set, you have to use set( ), not { }; the latter creates an empty dictionary, a data structure that you discussed earlier, fruits = { ” apple ” ,  ” banana ” , ” cherry ” } print ( fruits )
{ ‘ cherry ‘ , ‘ banana ‘ , ‘ apple ‘ }
The setlist is unordered, so the items will appear in random order. The items in the set are not dis¬played in the order that they were defined. Sets, like dictionaries, do not maintain a logical ordering. The order in which items are stored is determined by Python, and not by the order in which they were provided. Therefore, it is invalid and makes no sense to access an element of the set by an index value.

  • A set is a collection that is unordered and unin¬dexed. In Python, sets are written with curly brackets.

సంతృప్తిని మించిన సంపద లేదు

Python Programming - If-Else Statement

Python Programming – If-Else Statement

You can learn about Control Statements in Python Programs with Outputs helped you to understand the language better.

Python Programming – If-Else Statement

The statement if also allows answering for the false value by using an else clause. The else statement con¬tains the block of code that executes if the conditional expression in the if statement evaluates to 0 or a false value. The else statement is an optional statement; if it is provided, in any situation one of the two blocks gets executed, not both.
The syntactic form of the if-else statement is as follows:

if (expression):
statements BLOCK 1
else:
statements BLOCK 2

When the expression evaluates to a non-zero value, the condition is considered to be true, and statements BLOCK 1 are executed; otherwise, statements BLOCK 2 are executed. Blocks can have multiple lines. As long as they are all indented with the same amount of space, they constitute one block. Figure 5.5 shows the flow diagram of the if-else statement.
For example,

Python Programming - If-Else Statement chapter 5 img 1

if 10>100:
print ( ” 10 is greater than 100 ” )
else:
print ( ” 10 is less than 100 ” )

Simple Programs

Example 2.
Program to print absolute value of a number provided by the user.

#Take a number from the user and print its absolute value.
num = eval ( input ( “Enter a number : “)
print (‘|’, num, ‘| = ‘ , (num if num <0 else num) , sep=’ ‘)RUN
>>>
Enter a number : -9
|-9| = 9
>>>
>>>
Enter a number : 9
|9| = 9
>>>

Example 3.
Program to check divisibility of a number.

# Program to check divisibility of a number
num1 = int(input(“Enter first number : “))
num2 = int(input(“Enter second number : “))
remainder = numl%num2
if remainder == 0:
print(“First number is divisible by second number”) else:
print(“First number is not divisible by second number”)RUN
>>>
Enter first number: 100
Enter second number: 2
The first number is divisible by the second number
>>>
>>>
Enter first number: 9
Enter second number: 2
The first number is not divisible by the second number
>>>

Example 4.
Program for tax calculation.

# Program for -tax calculation
name=input(“Enter the name of Employee :”)
salary=float(input(“Enter the salary :”))
if (salary>50000):
tax=0.10*salary
netsalary=salary-tax
print(“The net salary of “+name+” is”,netsalary)
else:
netsalary=salary
print(“No taxable Amount”)
print(“The net salary of “+name+ “is”,salary)RUN
>>>
Enter the name of Employee: Swati
Enter the salary: 60000
The net salary of Swati is 54000.0
>>>
>>>
Enter the name of Employee: Geeta
Enter the salary:45000
No taxable Amount
The net salary of Geeta is 45000.0
>>>

Example 5.
Program to print the largest number.

# Program to print the largest no.
num1 = int(input(“Enter first number: “))
num2 = int(input(“Enter second number: “))
num3 = int (input (“Enter third number: “))
max = num1
if num2 > max:
max= num2
if num3> max:
max=num3
print(“Largest number is: “, max)RUN
>>>
Enter first number: 27
Enter second number: 37
Enter third number: 17
Largest number is: 37
>>>

Let’s Try

Write a program to print the smallest number.
Suppose, you want to write a program that accepts a value of a variable from the user and prints whether the number is positive or negative using the if-else statement. The program is shown in Figure 5.10.

Example 6.
Program to Print negative or positive number.

# Demo of if-else statement
num = int(input(“Enter a number :”))
if (num < 0) :
print(“Number is negative.”)
else:
print(“Number is positive.”)RUN
>>>
Enter a number: 5
The number is positive.
>>>
Enter a number:-7
The number is negative.
>>>

Example 7.
Program to read two numbers and print quotient.

# Program to print quotient
dividend, divisor = eval(input(‘Please enter two numbers to divide: ‘))
if divisor != 0:
print(dividend, ‘/’, divisor. “=”, dividend/divisor)
else:
print(‘Division by zero is not allowed’)RUN
>>>
Please enter two numbers to divide : 8 , 2
8 / 2 = 4.0
>>>
Please enter two numbers to divide : 2 , 8
2 / 8 = 0.25
>>>
Please enter two numbers to divide: 8,0
Division by zero is not allowed
>>>

Example 8.
Program to display menu to calculate area of square or rectangle.

# Program to display menu to calculate area of square or rectangle
print(“1. Calculate area of a square “)
print(“2. Calculate area of rectangle “)
choice = int(input(“Enter your choice (1 or 2): “))
if (choice == 1):
side = float(input(“Enter side of a square : “))
area_square = side * side
print(“Area of a square is , areasquare)
else:
length = float(input(“Enter length of a rectangle : “))
breadth = float(input(“Enter breadth of a rectangle : “))
area_rectangle = length * breadth
print(“Area of a rectangle is , arearectangle)RUN
>>>
1. Calculate the area of a square
2. Calculate the area of a rectangle
Enter your choice (1 or 2): 2
Enter the length of a rectangle: 8
Enter breadth of a rectangle: 4
The area of a rectangle is: 32.0
>>>
>>>
1. Calculate the area of a square
2. Calculate the area of the rectangle
Enter your choice (1 or 2): 1
Enter side of a square: 2.5
The area of a square is: 6.25
>>>

Example 9.
Program to print larger number using swap

In the program shown in figure 5.13, the if statement rearranges any two values stored in x and y in such a way that the smaller number will always be in x and the largest number always in y. If the two numbers are already in the proper order, the compound statement will not be executed. You will always get the larger value first and then the smaller value.

# print larger number using swap
x=y=0
x=int(input (“Enter a number : “) )
if (num % 2 ==0):
print (num, ” is an even number. “)
else:
print (num , ” is an odd number . ” )RUN
>>>
Enter a number: 2
2 is an even number.
>>>
>>>
Enter a number: 5
5 is an odd number.
>>>

Example 10.
Program to print if the number is even or odd.

# Program to print no. is even or odd
num=int(input(“Enter a number: “))
if (num % 2 == 0):
print(num, “is an even number.”)
else:
print(num, “is an odd number.”)RUN
>>>
Enter a number: 2
2 is an even number.
>>>
>>>
Enter a number: 5
5 is an odd number.
>>>

Example 11.
Program to display the menu to calculate the sum or product of entered numbers.

# Program to display menu to calculate sum or product of entered numbers
numl = int(input(“Enter first number : “))
num2 = int(input(“Enter second number : “))
num3 = int(input(“Enter third number : “))
print(“1. Calculate sum”)
print(“2. Calculate product”)
choice = int(input(“Enter your choice (1 or 2): “))
if (choice == 1):
sum = num1+num2+num3
print(“Sum of three numbers are , sum) else:
product = numl*num2*num3
print(“Product of three numbers are : “.product )
RUN
>>>
Enter the first number: 2 Enter second number : 3 Enter third number: 4
1. Calculate the sum
2. Calculate the product
Enter your choice (1, or 2): 1
The sum of the three numbers are: 9
>>>
>>>
Enter first number: 2
Enter second number : 3
Enter third number: 4
1. Calculate the sum
2. Calculate the product
Enter your choice (1 or 2): 2
Product of three numbers are: 24
>>>
Python Programming - Date and Time Functions

Python Programming – Date and Time Functions

You can learn about Functions in Python Programs with Outputs helped you to understand the language better.

Python Programming – Date and Time Functions

Classes provide a number of functions to deal with dates, times, and time intervals. Date and DateTime are an object in Python, so when you manipulate them, you are actually manipulating objects and not strings or timestamps. Whenever you manipulate dates or times, you need to import the DateTime function. The DateTime module enables you to create the cus¬tom date objects, and perform various operations on dates like the comparison, etc. To work with dates as date objects, you have to import the DateTime module into the Python source code.

The concept of Ticks

In Python, the time instants are counted since 12:00 am, January 1, 1970. It is the beginning of an era. and is used to start counting time. This special moment is called an epoch. In Python, the time between the present moment and the special time above is expressed in seconds. That time period is called Ticks. A tick can be seen as the smallest unit to measure the time. The time ( ) function in the time module returns the number of seconds from 12 am on January 1, 1970, to the present.

Example
Demo to calculate the number of ticks using the time ( ) function

# Import time module
import time# prints the number of ticks spent since 12 AM, 1st January 1970
ticks = time.time ( )
print (“Number of ticks since 12:00am, January 1, 1970: “, ticks)RUN
>>>
1560653863.8000364
>>>

time ( )

To get how many ticks have passed since the epoch, you call the Python time ( ) method.
>>> import time
>>> time. time ( )
1514472378. 761928
A time object instantiated from the time class represents the local time.

Example
Demo of time ( ) function.

from datetime import time
# time(hour = 0, minute = 0, second = 0)
a = time ( )
print(“a =”, a)
# time(hour, minute and second)
b = time(9, 32, 52)
print(“b =”, b)
# time(hour, minute and second)
c = time(hour = 9, minute = 32, second = 52)
print(“c =”, c)
# time(hour, minute, second, microsecond)
d = time(9, 32, 52, 224565)
print(nd =”, d)RUN
>>>
a = 00:00:00
b = 09:32:52
c = 09:32:52
d = 09:32:52.224565
>>>

Example
Program to print hour, minute, second and microsecond.

# Print hour, minute, second and microsecond
from datetime import time
a = time(9, 32, 52)print(“hour =”, a.hour)
print(“minute =”, a.minute)
print(“second =”, a.second)
print(“microsecond =”, a.microsecond)RUN
>>>
hour = 9
minute = 32
second = 52
microsecond = 0
>>>

Once you create a time object, you can easily print its attributes such as hour, minute, etc. Note that you have not passed the microsecond argument, so, its default value 0 is printed.

local time ( )

local time ( ) returns the current time according to your geographical location, in a more readable format. Consider the following example.

Example
Demo of localtime ( ) function.

import time

#returns a time tuple

print(time.localtime(time.time( )))

RUN
>>>
time.struct_time(tm_year=2019, tm_mon=6, tm_mday=16, tm_hour=8, tm_min=28, tm_sec=59, tm_wday=6, tm_yday=167, tm_isdst=0)
>>>

asctime ( )

The time can be formatted by using the asctime ( ) function of the time module. It returns the formatted time for the time tuple being passed.
>>> import time
>>> time.asctime ( )
‘Sun Jun 16 11:18:09 2019’

clock ( )

It returns the number of seconds elapsed since the first call made to it. It returns the value as a floating number.
>>> time.clock ( )
1392.736455535
>>> time.clock ( )
1409.408693707

sleep ( )

The sleep ( ) method of time module is used to stop the execution of the script for a given amount of time. The output will be delayed for a number of seconds. Consider the following example.

Example
Demo of sleep ( ) function.

import time
for i in range(0,5):
print(i)
#Each element will be printed after 2 second
time.sleep(2)RUN
>>>
0
1
2
3
4
>>>

now ( )

The now ( ) method to create a DateTime object containing the current local date and time. The date contains the year, month, day, hour, minute, second, and microsecond.

Example
Demo of now ( ) function.

# Get Current Date and Time
import datetime;#returns the current datetime objectprint(datetime.datetime.now())RUN
>>>
2019-06-16 08:36:33.975566
>>>

today ( )

today ( ) method defined in the date class to get a date object containing the current local date.

Example
Demo of today ( ) function.

# Get Current Date

import datetime;
date_object = datetime.date.today ( )
print(date_object)
RUN
>>>
2019-06-16
>>>

Example
Demo of today ( ) function.

# Print today’s year, month and day
from datetime import date
today = date.today ( )
print(“Current year:”, today.year)
print(“Current month:”, today.month)
print(“Current day:”, today.day)RUN
>>>
Current year: 2019
Current month: 6
Current day: 16
>>>

date ( )

The date() is a constructor of the date class. It takes three arguments: year, month, and day.

Example
Demo of date ( ) function.

# Date object to represent a date
import datetime
d = datetime.date(2019, 7, 12)
print(d)RUN
>>>
2019-07-12
>>>

dir ( )

The dir ( ) function to get a list containing all attributes of a module.

Example
Demo of dir ( ) function.

import datetime
print(dir(datetime))RUN
>>>
[‘MAXYEAR’, ‘ M INYEAR’ , ‘ built ins ‘ , ‘ cached ‘ loader me_CAPI’, ‘ ‘, ‘ name ‘, ‘ package ‘, time’, ‘timedelta’, ‘timezone’ ‘ spec ‘, ‘ ‘tzinfo’]
>>>

timestamp ( )

You can also create date objects from a timestamp. You can convert a timestamp to date using from timestamp ( ) function.

Example
Demo of timestamp ( ) function.

from datetime import date
print(“Date timestamp)RUN
>>>
Date : 2021-07-14
>>>

strftime ( )

The strftime ( ) method takes one or more format codes and returns a formatted string based on it. A reference of some format codes are used in following example:

Example
Demo of strftime ( ) function.

import datetime
x = datetime.datetime . now ( )
print(x.year)
print(x.strftime(“%a”) )             #Weekday, short version i.e. Sun
print(x.strftime(“%A”) )            #Weekday, full version i.e. Sunday
print(x.strftime(“%w”) )            #Weekday as a number 0-6 i.e. 0
print(x.strftime(“%d”) )            #Day of month 01-31 i.e. 16
print(x.strftime(“%b”) )            #Month name, short version i.e. Jun
print(x.strftime(“%B”) )            #Month name, full version i.e. June
print(x.strftime(“%m”) )          #Month as a number 01-12 i.e. 06
print(x.strftime(“%y”) )           #Year, short version, without century i.e. 19
print(x.strftime(“%Y”) )           #Year, full version i.e., 2019
print(x.strftime(“%H”) )          #Hour 00-23 i.e. 11
print(x.strftime(“%I”) )           #Hour 00-12 i.e. 11
print(x.strftime(“%p”) )          #AM/PM i.e. AM
print(x.strftime(“%M”) )        #minute 00-59 i.e. 02
print(x.strftime(“%S”) )         #second 00-59 i.e. 59
print(x.strftime(‘%c”) )          #Local version of date and time i.e. sun Jun 16 11 : 02 : 59 2019
print(x.strftime(‘”%x”))        #Local version of date i.e. 06/16/19
print(x.strftime(“%X”))        #Local version of time i.e. 11:02:59RUN
>>>
2019
Sun
Sunday
0
16
Jun
June
06
19
2019
11
11
AM
02
59
Sun Jun 16 11:02:59 2019
06/16/19
11:02:59
>>>

Date Arithmetic

Example
Demo of Date Arithmetic.

import datetime
today = datetime.date.today ( )
print(‘Today :’, today)
oneday = datetime.timedelta(days=1)
print(‘One day :’, one_day)
yesterday = today – one_day
print (‘Yesterday:’, yesterday)
tomorrow = today + one_day
print (‘Tomorrow :’, tomorrow)RUN
>>>
Today : 2019-06-16
One day : 1 day, 0:00:00
Yesterday: 2019-06-15
Tomorrow : 2019-06-17
>>>

The calendar module

Python provides a calendar object that contains month ( ) function.

#Program to print the calendar of July 2019
print(calendar.month(2019,7))RUN
>>>
July 2019
Mo  Tu  We  Th  Fr  Sa  Su
1      2     3     4
5     6      7      8      9     10
11  12    13    14     15    16
17  18    19    20     21    22
23   24   25   26     27     28
29   30   31
>>>
>> print(calendar.month(2020,1))

January 2020
Mo  Tu  We  Th  Fr  Sa  Su
1      2    3     4    5   6     7
8      9   10  11   12  13  14
15   16  17   18   19  20  21
22   23  24   25   26  27  28
29   30 31

You can also print the calendar for the whole year. The partial ( ) method of the calendar module is used to print the calendar of the whole year. (See Figure 10.58).

# Printing the calendar of whole year
import calendar

#printing the calendar of the year 2019
calendar.parcel(2019)

isleap ( )

The isleap ( ) takes a 4-digit year as an argument, and returns True if it is a leap year. Otherwise, False.
>>> calendar.isleap(2019)
False
>>> calendar.isleap(2020)
True

Leapdays(y1 ,y2)
The leapdays ( ) returns the total number of leap days from year yl to year y2.
>>> calendar.leapdays(1990,2020)
7

firstweekday ( )

The firstweekday ( ) returns which day is currently set as the first day of the week.
>>> calendar.setfirstweekday(O)
>>> calendar.firstweekday ( )
0

Python Programming - Date and Time Functions chapter 10 img 1

Recursion

Recursion is the process of defining something in terms of itself. A physical world example would be to place two parallel mirrors facing each other. Any object in between them would be reflected recursively. You know that in Python, a function can call other functions. It is even possible for the function to call itself. These types of the construct are termed recursive functions.

For example, the factorial of 5 (denoted as 5!) is 1*2*3*4*5 = 120 is a recursive function to find the factorial of an integer. The factorial function is widely used in the combinatorial analysis (counting theory in mathematics), probability theory, and statistics. The factorial of n usually is expressed as n!. Factorial is defined as non-negative integers.

Example
Program to find factorial using recursion

def calc_fact(x):
if x == 1:
return 1
else:
return (x * calc_fact(x-1))num = 5
print(“The factorial of”, num, “is”, calcfact(num))RUN
>>>
The factorial of 5 is 120
>>>

In the above example, calc_fact ( ) is a recursive function as it calls itself. When you call this function with a positive integer, it will recursively call itself by decreasing the number. Each function calls multiples the number with the factorial of number 1 until the number is equal to one. The recursion ends when the number reduces to 1, which is called the base condition. Every recursive function must have a base condition that stops or terminates the recursion or else the function calls itself infinitely.

Example
Program to find the power of a number using recursion.

# To find the power of a number using recursion
def power(base,exp):
if (exp==1):
return base
if (exp!=1):
return (base*power(base,exp-1))
base = int(input(“Enter base: “))
exp = int(input(“Enter exponential value: “))
print (“Result:”,power(base,exp))RUN
>>>
Enter base: 4
Enter exponential value: 3
Result: 64
>>>

In the above example, power ( ) is a recursive function as it calls itself. When a user enters the base and exponential value, the numbers are passed as arguments to a recursive function to find the power of the number. The base condition is given that if the exponential power is equal to 1, the base number is returned. If the exponential power is not equal to 1, the base number multiplied with the power function is called recursively with the arguments as the base and power minus 1 and the final result is printed.

Advantages of Recursion

  1. Recursive functions make the code look clean and refined.
  2. A complex task can be broken down into simpler sub-problems using recursion.
  3. Sequence generation is easier with recursion than using some nested iteration

Disadvantages of Recursion

  1. Sometimes the logic behind recursion is difficult to follow through.
  2. Recursive calls are expensive (inefficient) as they take up a lot of memory and time.
  3. Recursive functions are hard to debug.

Recommended Reading On PTSP Notes

Must Read:

FEDERALBNK Pivot Point Calculator

Python Programming – Print Statement

Python Programming – Print Statement

You can learn about Introduction to Python Programming Programs with Outputs helped you to understand the language better.

Python Programming – Print Statement

print is a function that prints something on the screen. To print any message as it is on screen, just type print and that message or argument in (”) or (” “).
print (“Hello World”)
For example, in the above-mentioned program, “Hello World” is a string and print is a Python com¬mand to write a string in quotes on the console or terminal window.

  • print( ) statement without any argument will simply jump to the next line.

Now, let us consider some more examples of how to use the print command. Type the following print statements and run the program to see the output:

Example 4.
Program to display string using the print command.

print ( ” Hello, How are you? ” )
print ( ” I am learning Python language . ” )RUN
>>>
Hello, How are you?
I am learning Python language.
>>>

Let’s do something more advanced:

Example 5.
Program to display sum of two numbers using print command.

x = 2
y = 3
print (“Sum of”,x,”and”,y,”is”,x+y)
RUN
>>>
The Sum of 2 and 3 is 5
>>>

Note that whatever you write in (” “) or (‘ ‘) will be printed as it is and is not evaluated. So, ‘Sum of’ gets printed as it is without quotes and then the value of ‘X’ gets printed (i.e., 2); then ‘and’ is printed as it is. Then the value of y is printed (i.e., 3) and at the end, x+y is calculated and printed (i.e., 5).
Multiple values can be displayed by the single print() function separated by comma. Python will automatically insert spaces between them. The fol-lowing example displays values of name and age variables using the single print() function.
>>> name=”Aman”
>>> age=19
>>> print(“Name, name, “Age:”,age)
Name: Aman Age: 19
By default, a single space (‘ ‘) acts as a separator between values. However, any other character can be used by providing a sep, short for separator

parameter to change that space to something else. For example, using sep=’:’ would separate the argu¬ments by a colon and sep=’##’ would separate the arguments by two hash signs. In the following example is used as a separator character.
>>> name=”Aman”
>>> age=19
>>> print(name,age)
Aman 19
>>> print(name,age,sep=”,”)
Aman,19
The output of the print( ) function always ends with a newline character. The print( ) function has another optional parameter end, whose default value is “\n”. This value can be substituted by any other character such as a single space (‘ ‘) to display the output of the subsequent print( ) statement in the same line.

Let’s Try

Write the following print statements and check the output:
(a)

print (“You are Welcome!”)
print (“I am enjoying learning Python language.”)

(b)

num1 = 10
num2 = 7
print (“Sum of”,numl,”and”,num2,”is”,numl+num2)

(c)

n1 = 5
n2 = 3
print (“Product of”,n1,”and”,n2,”is”,n1*n2)

As print( ) is used to print output on the screen, to input data into a program, i.e., to get data from the user you use input(). This function reads a single line of text as a string. If the input function is called, the program flow will be stopped until the user has given input and pressed Enter key. The text of the optional parameter, i.e., the prompt, will be printed on the screen.

Let’s Try

person = input(‘Enter your name:’) person = input(‘Enter your name:’)
print(‘Hello’, person, ‘!’) print(‘Hello’, person, ‘!’, sep=”)

Read More:

ZYDUSLIFE Pivot Point Calculator

Python Programming – Accepting Input From The Console

Python Programming – Accepting Input From The Console

You can learn about Introduction to Python Programming Programs with Outputs helped you to understand the language better.

Python Programming – Accepting Input From The Console

In Python, input is used to request and get information from the user, and print is used to display information on the screen.

input ( )
In Python, input is accomplished by using an assignment statement combined with a special function called input( ). Syntax of input ( ) is as follows:
variable = input(<prompt>)
Here, the prompt is an expression that serves to ask the user for input; this is almost always a string literal (i.e., some text inside quotation marks). When Python encounters an input expression, it evaluates the prompt and displays the result of the prompt on the screen. It then pauses and waits for the user to type an expression and press the Enter key. The expression typed by the user is then evaluated to produce the result. As the input provided is evaluated, Python expects a valid expression. If the input provided is not correct then either syntax error or exception is raised by Python.

>>> name = input(‘Enter your name: ‘)
Enter your name: Vivek
>>> print(‘Hello’, name)

Note that a comma is used to separate the individual items being printed, causing a space to appear between each when displayed. Thus, the output of the print function, in this case, is Hello Vivek, and not HelloVivek. Let us take some more examples:
>>> x=input(“something:”)
something:10
>>> x
‘ 10 ‘
>>> x=input(“something:”)
something10’ # entered data is treated as string with or without ”
>>> x
‘ 10 ‘
>>> x = input(“x: “)
X : 34 .
type(x)
<class ‘str’> # input( ) function always returns a value of string type
>>> y = input(“y: “)
y: 42
type(y)
<class ‘str’>
>>> print(x + y)
3442
Here, the values entered (34 and 42) would be supplied by the user. Your program would then print out the value 3442, which is the concatenation, i.e., joining of two strings. In order to add them, you need to turn them into numbers. That can be done using int( ) or float( ).
>>> x = int(input(“x: “))
X: 34
type (x)
<class ‘int’>
>>> y = int(input(“y: “))
y: 42
type(y)
<class ‘int’>
>>> print(x + y)
76
Now, type the following:
>>> price=float ( input ( ‘ Enter price: ‘ ) )
Enter price: 12.50
>>> qty=int (input ( ‘ Enter quantity: ‘ ) )
Enter quantity: 3
>>> print(price * qty)
37.5

Let’s Try

Type the following code and write the output.

print(‘Enter an integer value:’)
X = input ( )
print( ‘ Enter another integer value: ‘ )
Y = input( )
num1 = int(x)
num2 = int(y)
print(num1, ‘+’, num2, ‘=’, num1 + num2)

Example 6
program demonstrate how to enter data using input command.

print ( ‘what is your name ‘)
Name = input()
print ( ‘ Hello! ‘ + name + ‘Nice to meet you ! ‘ )RUN
>>>
What is your name?
Priya
Hello! Priya nice to meet you!
>>>

Example 7.
Program to demonstrate input command with a message.

name = input ( ” Enter your name : ” )
print ( “you are Welcome “, name )RUN
>>>
Enter your name: Puja
You are welcome Puja
>>>

Example 8.
Program to accept student’s detail using the input function and display it.

name = input ( ” Enter student Name : ” )
marks = input ( ” Enter Total Marks : ” )
address = input ( ” Enter Address : ” )
Print ( ” printing student’s Details ” )
print ( ” Name ” , ” Marks ” , ” Address ” )
print ( name, marks , address )
RUN
>>>
Enter student Name: Dev
Enter Total Marks: 467
Enter Address: c2, Janak puri
printing student’s Details
Name Marks Address
Dev 467 c2, Janak puri
>>>

The input( ) function reads a line from input and uses this input string in your Python program, converts it into a string, and returns it. Then, you can

Let’s Try

Write the following code and check the output:
(a)

age = input ( ” Your age? ” )
print ( ” You are ” + age + ” years old.” )

(b)

emp_name = input ( ” Enter Employee Name : “)
salary = input ( ” Enter salary : ” )
print ( ” Employee Name “, ” salary “)
print ( emp_name, salary)

whatever you enter as input, the input function converts it into a string. Even if you enter an integer value, still input ( ) function will convert it into a string. You need to explicitly convert it into the integer in your code. Let’s understand this with an example.

Example 9.
Program to check input type in python.

# Program to check input type in Python
number = input (“Enter a number :”)
name = input(“Enter name :”)
print(“Printing type of input value”)
print (“Type of number”, type(number))
print (“Type of name”, type(name))
RUN
>>>
Enter a number:25
Enter name : Ansh
Printing type of input value
Type of number <class ‘str’>
Type of name <class ‘str’>
>>>

Note that in the above-mentioned program, both number and name variable types are str, i.e., string. You know that whatever you enter either any number (integer or float) or string as input, the input( ) function always converts it into a string. So, let’s understand how to accept integer value from a user in Python.
>>> num = input(‘Enter a number: ‘)
Enter a number: 10
>>> num
‘ 10 ‘
Here, you can see that the entered value 10 is a string, not a number. To convert this into a number, you can use int() or float() functions.
>>> int ( ‘ 10 ‘ )
10
>>> float ( ‘ 10 ‘ )
10 . 0
This same operation can be performed using the eval ( ) function.

Example 10.
Program to add two inputted numbers by converting both the numbers into an inttype using int( ).

# Program to add two inputted numbers
first_num = int ( input (“Enter first number : “) )
secondnum = int ( input (“Enter second number : “) )
sum = first_num + secondnum
print(“Addition of two number is: “, sum)RUN
>>>
Enter first number: 12
Enter second number: 10
The addition of two number is: 22
>>>

Note that in Figure 3.32 you have explicitly added a cast of an integer type to an input function, i.e., you converted input value to the integer type using int(). Now if you print the type of first_num, you will get the type as “int”.
>>> type(first_num)
<class ‘ int’ >
You can also accept float value from a user in Python and convert user input into float number using the float( ) function.

Let’s Try

Write the following code in python and check the output:

# program to accept float value from the user
float_num = float ( input ( ” Enter any float number : ” ) )
print ( ” input float number is : ” , float_num )
print ( ” type is : ” , type ( float_num) )

write the following codes in python and run the program assuming a=2 and b=4. Also, write the reason behind the first program producing incorrect output.

Let’s Try

Write the following code in Python and check the output:

# Program to accept float value from the user
float_num = float (input(“Enter any float number :”) )
print (“Input float number is: “, float_num )
print (“Type is:”, type(float_num) )

Write the following codes in Python and run the son behind the first program producing incorrect programs assuming a=2 and b=4. Also, write the rea- output.

a = input()a = int(input())
b = input()b = int(input())
s = a + bs = a + b
print(s)print(s)

eval ( )

eval() function is used to evaluate the value of a string. It takes a string as an argument, evaluates this string as number, and returns the numeric result. It can evaluate even expressions, provided the input is a string:

>>> eval ( ‘ 27 ‘ )
27
>>> eval ( ‘ 27 . 67 ‘ )
27 . 67
>>> eval ( ‘ 5+2 ‘ )
7
>>> eval ( “7*4+2” )
30

Example 11.
Program to convert given temperature in celsius into Fahrenheit.Use eval ( )for input.

#program to convert temperature in celsius into Fahrenheit
temp = eval (input ( ‘ Enter a temperature in celsius : ‘ ) )
print ( ‘ In Fahrenheit, that is ‘ , 9/5*temp+32)RUN
>>>
Enter a temperature in Celsius : 0
In Fahrenheit, that is 32. 0
>>>

Example 12.
program to calculate average of two inputted numbers. Use eval ( ) to output numbers.

#program to calculate average of two inputted numbers
num1 = eval ( input ( ‘ Enter the first number : ‘) )
num2 = eval ( input ( ‘ Enter the second number : ‘ ) )
print ( ‘ The average of the numbers you entered is ‘ , (num1+num2)/2)RUN
>>>
Enter the first number: 65
Enter the first number: 72
The average of the number you entered is 68 . 5
>>>

Refer More:

ZEEL Pivot Point Calculator

Python Programming – Simple Python Programs

Python Programming – Simple Python Programs

You can learn about Introduction to Python Programming Programs with Outputs helped you to understand the language better.

Python Programming – Simple Python Programs

Program to ac,d two numbers given by the user.

# Program to add two numbers given by user
print ( ‘ Please enter an integer value: ‘ )
x = input ( )
print ( ‘ Please enter another integer value: ‘ )
y = input ( )
numl = int(x)
mm2 = int (y)
print (numl, ‘ + ‘, mm2, ‘=’, num1 + num2)
Introduction to Python 77
Module 3: M3-R5
RUN
>>>
Please enter an integer value:
56
Please enter another integer value: 32
56 + 32 = 88
>>>

Program to display moths and days for enterd no.of days.

# Program to display moths and days for enterd no.of days.
a days = int(input(“Enter days: “))
months = days / 30
days = days5% 30
print ( ”Months = ”, int ( Month) , ”Days = ”, days)RUN
>>>
Enter days: 365
Months = 12 days
>>>

Program to find selling price.

#Program to find selling price
costprice=int ( input ( ” Enter Cost Price: ” ) )
profit=int ( input ( ” Enter profit: ” ) )
sellingprice = costprice+profit
print (“Selling price: “,sellingprice)RUN
>>>
Enter Cost Price: 100
Enter profit: 20
Selling price: 120
>>>

program to calculate Bonus, Commission and Gross salary.

# Program to calculate Bonus, Commission and Gross salary
basic_salary = 1500
bonus_rate = 200
commision_rate = 0.02
sold = int(input(“Enter the number of inputs sold: “))
price = float(input(“Enter the total prices: “))
bonus = (bonus_rate * sold)
commission = (commision_rate * sold * price)
print(“Bonus = %6.2f” % bonus)
print(“Commision = %6.2f” % commission)
print(“Gross salary = %6.2” % (basic_salary + bonus + commission) )RUN
>>>
Enter the number of inputs sold: 2
Enter the total prices: 5
Bonus = 400.00
Commission = 0.20
Gross salary = 1900.20
>>>

Program to convert the time given into minutes in hours and minutes.

# Program to convert the time given in minutes in hours and minutes
time = int(input(“Enter time in minutes: “))
hours= time/60
minutes = time%60
print(“Hours : “, round(hours))
print(“Minutes minutes)RUN
>>>
Enter time in minutes: 70
Hours: 1
Minutes: 10
>>>
  • Python 2 has two versions of input functions, input( ), and raw_input(). The input( ) function treats the received data as a string if it is included in quotes ” or otherwise the data is treated as a number. In Python 3, raw_input() function is deprecated. Further, the received data is always treated as a string.

Refer More:

WIPRO Pivot Point Calculator

Python Programming – Expressions

Python Programming – Expressions

You can learn about Operators in Python Programs with Outputs helped you to understand the language better.

Also Read: Java Program to Convert Kilogram to Pound and Pound to Kilogram

Python Programming – Expressions

The expression consists of a combination of values, which can be constant values, such as a string (” Shiva ” ) or a number (12), and operators, which are symbols that act on the values in some way. The following are the examples of expression:
10 – 4
11 * ( 4 + 5 )
X – 5
a / b
In other words, the expression consists of one or more operands and one or more operators linked together to compter a value. for example:
a = 5 # assume a = 5
a + 2

is a larger expression that results in the sum of the value in the variable a is also an expression as is the constant 2 since they both represent the value. expression value, in turn, can act as Operands for Operators. For example, 9+6and 8+5+2 are two expressions that will result in a value of 15. taking another example, 6.0/5+(8-5.0) is an expression in which values of different data types are used. these types of expressions are also known as mixed types of expression. when mixed types expressions are evaluated, python promotes the result of the lower data type of higher data type, i.e., to float. So, the result of the above-mentioned expression will be 4.2. There is known as implicit typecasting. Implicit typecasting is done without any intimation to the user. sometimes, you may want to perform a type of conversion ourselves. the programmer may instruct the Python interpreter to convert one type of data to another type, which is known as explicit conversion.
the float() function convert an int into float. python also provides int () and long () functions () that can be used to coverlet numbers into ints and longs,respectvly.
for example,

>>> float (22)
22.0
>>> int(4.8)
4

Expression can also contain another expression. When you have an expression consisting of subexpression(s), Python decides the order of operations based on the precedence of the operator. When an expression contains two different kinds of operators, the order in which the operators should be applied

is known as Operator Precedence. A higher precedence operator is applied before a lower precedence operator. When an expression contains two operators with the same precedence, the order in which the operators should be applied first is known as Associativity. Operator associativity determines the order of evaluation when the operators are of the same precedence and are not grouped by parentheses.
An operator may be left-associative or right-associative. In the left-associative, the operator appearing on the left side will be evaluated first, while in the right-associative, the operator appearing on the right will be evaluated first. In Python ‘=’ and ‘**’ are right-associative. The following list describes the basic rules of operator precedence in Python:

(a) Expressions are evaluated from left to right.

(b) Exponentiation, multiplication, and division are performed before addition and subtraction.

(c) Expressions in parentheses are evaluated first. Parentheses can be used to group terms in an expression to provide control over the order in which the operations are performed.

(d) Mathematical expressions are performed before Boolean expressions ( and, or, not). Table 4.5 summarizes the precedence of operators from higher precedence to lower precedence.
When at least one of the operands is itself an expression (as in 2 * 7 + 5), the expression is a com¬pound expression. Python follows the standard mathematical order of operations, so 2 * 7 + 5 is equivalent to (2*7) + 5.

Operator NameOperators Symbols
Exponentiation**
Unary plus and minus+, –
Multiply, divide, modulus, floor division*,/,%,//
Addition and subtraction+, –
Relational (comparison) operators<,<=,>,>=
Equality operators==, !=
Assignment operators%=, /=,//=, -=, +=, *=
Logical operatorsnot, and, or

Let’s Try

Evaluate the following expression with precedence of operator:

x = 2* 3/ 5 + 10 //3 -1x = 3* 3/ 2 + 9 //3 – 2
print(x)print(x)
Introduction to Python Programming – Algorithms

Introduction to Python Programming – Algorithms

You can learn about Introduction to Programming Using Python Programs with Outputs helped you to understand the language better.

Also Read: Python Programming Examples with Output

Introduction to Python Programming – Algorithms

Algorithms

A set of instructions that describes the steps to be followed to carry out an activity is called an algorithm or procedure for solving a problem. If the algorithm is written in the computer programming language, then such a set of instructions is called a program. The task of writing the computer program involves going through several stages. So, programming requires more than just writing programs. That means it requires writing algorithms, as well as testing the program for all types of errors.

  • The algorithm is a stepwise presentation of the program in simple English.

Characteristics of Algorithm

(a) Language independent.
(b) Simple, complete, unambiguous, step-by-step program flow.
(c) No standard format or syntax required.
(d) Helpful to understand problems and plan out solutions.

Developing or Writing the Algorithms

The process of developing an algorithm (to solve a specific problem) is a trial-and-error process that may need numerous attempts. Programmers will make some initial attempts at a solution and review it to test its correctness. The errors they discover will usually lead to insertions, deletions, or modifications in the existing algorithm. It may even lead to scrapping the old one and creating a new.

  • Euclid’s algorithm is used to find the Greatest Common Divisor (GCD) of two given integer values. GCD is also known as the Greatest Common Factor (GCF) or Highest Common Factor (HCF).
Python Programming - Numbers

Python Programming – Numbers

Python Programming – Numbers

A number is an object in Python, and it is created when some value is assigned to it. The number data type is used to hold numerical data. Python language supports four different numeric data types as described below:

• int (signed integers): Alike C/C++/Java, Python supports integer numbers, which are whole numbers positive as well as negative having no decimal point.

• long (long integers): Similar to integers but with limitless size. In Python long integers are followed by a lowercase or uppercase L.

• float (floating point real values): Alike C/C++/Java, Python supports real numbers, called floats. These numbers are written with-a decimal point or sometimes in a scientific notation, with exponent e such as 5.9e7 i.e. 5.9xl07, where e represents the power of 10.

• complex (complex numbers) : Unlike C/C++/Java, Python supports complex data type. It holds complex numbers of the form x+iy, where x and y are floating-point numbers and i is iota representing the square root of -1 (imaginary number). Complex numbers have two parts where x is known as the real part and y is called the imaginary, part as it is with iota.

Unlike C/C++/Java, in Python, the variable declaration is not mandatory. The programmer just assigns the value to a variable and that variable exists with the data type based on the value assigned. For example, Code: 5.1 (interactive mode) represents, an illustration of a number data type that how a variable holds a certain type of data and it exists.

Code: 5.1. Illustration of number data type.

>>>i = 123456789                                        # variable i is assigned an integer value
>>>i
123456789
>>> f = 9.8765432112345679564               # variable f is assigned a floating
#point value
>>>f
9.876543211234567
>>> c = 5+9j                                       # variable c is assigned a
#complex number value
>>>c
5+9j

The data type determination, reference deletion, and different types of numbers are already discussed in Chapter 2 under Section 2.8.1.

Number Type Conversion

Python has the in-built feature to convert the data types of an expression containing different data types into a common type for evaluation. However, in order to fulfill the requirements of an operator or a function argument, sometimes the programmer needs to convert a data type to another type forcibly. This can be achieved by type conversion functions as listed in Table 5.1.

Conversion functionRole
int(x)converts x to a plain integer
long(x)converts x to a long integer
float(x)converts x to a floating-point number
complex(x)converts x to a complex number with real part x and imaginary part zero
complex(x, y)converts x and y to a complex number with real part x and imaginary part y. where x and y are numeric expressions

Python Mathematical Functions

Since we are working on numbers, Python language contains a rich set of built-in mathematical, and trigonometric, and random number functions, which operate on numbers input by the user. The mathematical functions are listed in Table 5.2. with a description of each of them. The programming example, representing the use of mathematical functions is given in Code: 5.2. The programmer needs to import the math namespace for executing mathematical functions.

Mathematical function

Computes/Returns

abs(x)The absolute value of x, which is a positive value
fabs(x)The absolute value of x
sqrt(x)The square root of x, where x>0
pow(x, y)The value of xy
ceil(x)The smallest integer not less than x
floor(x)The largest integer not greater than x
round(x, fn])x rounded to n digits from the decimal point.
exp(x)The exponent of x, i.e., ex
log(x)The natural logarithm of x, where x>0
Logl0(x)The base-10 logarithm of x, where x>0
cmp(x, y)0 if x=y, -1 if x<y, and 1 if x>y, (compares the values of x and y)
modf(x)The fractional and integer parts of x in a two-item tuple. Both parts have the same sign as x. The integer part is returned as afloat
max(xl, x2, …)The largest value among its parameters
min(xl, x2, …)The smallest value among its parameters

Code: 5.2. Programming illustration of Python mathematical functions.

# This program represents the use of Python mathematical functions

import math
x=-10.5
y=abs(x)
print(‘abs(x)={0}\format(y))

x=9.5
y=math.fabs(x)
print(‘fabs(x)= {0} ‘.format(y))

x=256
y=math.sqrt(x)
print(‘sqrt(x)= {0} ‘.format(y))

x=2
y=16
z=math.pow(x, y)
print(‘pow({0}, {l})={2}’.format(x,y,z))

x=4.31
y=math.ceil(x)
print(‘ceil(x)= {0} ‘.format(y))

x=4.31
y=math.floor(x)
print(‘floor(x)= {0}format(y))

x=10.5628468
y=round(x, 3)
print(’round({0}, 3)={l}’.format(x, y))

x=2
y=math.exp(x)
print(‘exp(x)={0}’.format(y))

x=20
y=math.log(x)
print(‘log(x)= {0} ’.format(y))

x=20
y=math.loglO(x)
print(‘log 10(x)={0}’. format(y))

x=10
y=20
z=cmp(x,y)
print(‘cmp({0}, {l})={2}’.format(x, y, z))

x=12.4354683
y=math.modf(x)
print(‘modf(x)= {0} ’.format(y))

y=max(-10, 23,54,21,0)
print(‘max(-10, 23, 54, 21, 0)={0}’.format(y))

y=min(-10, 23, 54, 21, 0)
print(‘min(-10, 23, 54,21, 0)={0}’.format(y))

Output:
abs(x)=10.5
fabs(x)=9.5
sqrt(x)=16.0
pow(2, 16)=65536.0
ceil(x)=5
floor(x)=4
round(l0.5628468, 3)=10.563
exp(x)=7.38905609893065
log(x)=2.995732273553991
log10(x)=l.3010299956639813
cmp(10, 20)= -1
modf(x)=(0.435468300000000l4,12.0)
max(-10,23, 54, 21, 0)=54
min(-10, 23, 54,21, 0)=-10

Note:

Mathematical functions abs( ), round( ), and cmp( ) do not require to import math namespace.

Also Read: How to find the smallest number in an array java

Python Trigonometric Functions

Python language provides a set of trigonometric functions listed in Table 5.2. with the description of each. The programming code to characterize the use of trigonometric functions is given in Code: 5.3.

Trigonometric function

Returns

sin(x)Sine of x in radians
cos(x)Cosine of x in radians
tan(x)Tangent of x in radians
asin(x)Arc sine of x in radians
acos(x)Arc cosine of x in radians
atan(x)Arc tangent of x in radians
atan2(y, x)Atan(y/x) in radians
degrees(x)Converts an angle x from radians to degrees
radians(x)Converts an angle x from degrees to radians
hypot(x, y)Computes the Euclidean distance, i.e., sqrt(x*x+y*y)

Code: 5.3. Programming illustration of Python trigonometric functions.

# This program illustrates the use of trigonometric functions

import math

x=30
y=math.radians(x)
print(‘radians( {0} )= {1} ‘.format(x, y))

x=1.57
y=math.degrees(x)
print(‘degrees( {0} )= {1} ‘.format(x, y))

x=0.5235987755982988
y=math.sin(x)
print(‘sin({0})={l}’.format(x, y))

x=0.5235987755982988
y=math.cos(x)
print(‘cos({0})={l}’.format(x, y))

x=0.5235987755982988
y=math.tan(x)
print(‘tan({0})={l}’.format(x, y))

x=0.5235987755982988
y=math.sin(x)
print(‘sin({0})={l}’.format(x, y))

x=0.5235987755982988
y=math.acos(x)
print(‘acos( {0} )= {1}fomat(x, y))

x=0.5235987755982988
y=math.atan(x)
print(‘atan( {0})={ 1} ‘.format(x, y))
x=3
y=4
z=math.atan2(y, x)
print(‘atan2({0}, {l})={2}’.format(x, y, z))

x=3
y=4
z=math.hypot(x, y)
print(‘hypot({0}, {l})={2}’.format(x, y, z))

Output:
radians(30)=0.5235987755982988
degrees(1.57)=89.95437383553924
sin(0.5235987755982988)=0.49999999999999994
cos(0.5235987755982988)=0.8660254037844387
tan(0.5235987755982988)=0.5773502691896257
asin(0.5235987755982988)=0.5510695830994463
acos(0.5235987755982988)=l.0197267436954502
atan(0.5235987755982988)=0.48234790710102493
atan2(3,4)=0.9272952180016122
hypot(3, 4)=5.0

Python Random Number Functions

Random numbers are very useful in numerous computer science problems such as simulators, games, security, privacy, testing applications, etc. Python language provides a set of random number functions to handle various computer science problems as described above. The list of random number functions is given in Table 5.4. The programmer needs to import a random module before calling any of the random number functions. The programming example, representing the use of random number functions is given in Code 5.4.

Random number function

Returns

Random ( )A random number r such that, 0 < r < 1
uniform(x, y)The random float r such that x < r < y
seed(x)It sets the starting integer value used in generating random numbers. This function is called before calling any other random number function.
choice(seq)A random item from a string, list, or tuple
shuffle(list)Randomizes the items in a list.
randfange(start, stop, step)A randomly selected item from a specified range.

Code: 5.4 Programming illustration of Python random number functions.

# This program illustrates the use of trigonometric functions

import random

r1 =random.random( )
print(“randomnumber l={0}”.format(rl))

r2=random.random( )
print(“random number 2={0} “.format(r2))

r1 =random.uniform( 10, 20)
print(“imiform random number l={0}”.format(r1))

r1=random.uniform(10,20)
print(“uniform random munber 2={0}”.format(r1))

random.seed(15)
r1 =random.random( )
print(“random number with seed 15={0}”.format(r1))

list=[70,20, 30,40, 50]
r1=random.choice(list)
print(“uniform random number l={0}”.format(r1))

str=’Hello Python’
r1=random.choice(str)
print(“uniform random number from string={0}”.format(r1))

list=[70, 20, 30,40, 50]
r1 =random. shuffle(list)
print(“shuffled list={0} “.format(list))

rl=random.randrange(10, 100, 3)
print(“random number from a range={0} “,format(rl))

rl=Thndom.randrange(10, 100, 4)
print(“random number from a range={0}”.format(rl))

Output:
random number 1=0.1113694067277533
random number 2=0.2822991673774605
uniform random number 1=18.907430735664263
uniform random number 2=10.620373343283184
random number with seed 15=0.965242141552123
uniform random number 1=70
uniform random number from string=t
shuffled list=[40, 30, 50,20, 70]
random number from a range=13
random number from a range=94

Python Mathematical Constants

Unlike, C/C++/Java, Python language provides built-in mathematical constants pi and e, which exhibit fixed values while performing mathematical computations. A program to illustrate mathematical constants is given in Code 5.5. Note that, the programmer requires to import a math module for fetching the values of pi and e.

Code: 5.5 Programming illustration of Python mathematical constants.

# Representation of mathematical constants pi and e

import math

print(‘pi= {0} ‘.format(math.pi))
print(‘e={0}’.format(math.e))

Output
pi=3.141592653589793
e=2.718281828459045

Python Tutorial