Problem Solving and Python Programming: UNIT II: Data Types, Expressions, Statements

Illustrative Python Programs

Data Types, Expressions, Statements

1. Exchange the Values of Two Variables, 2. Circulate the Values of n Variables, 3. Distance between Two Points, 4. Test for Leap Year

Illustrative Programs    AU : Dec.-19, Marks 4


1. Exchange the Values of Two Variables

1. Program to exchange the values of two variables without using function

Step 1: We will write the program in script mode. The name of the following file is

swap.py

a = 10

b = 20

print("Before Swapping the values are as follows...")

print(a)

print(b)

temp = a

a = b

b = temp print("After Swapping the values are as follows...")

print(a)

print(b)

Step 2:

Output

 

2. Program to exchange the values of two variables by using function.

Step 1: We will write the program in script mode. The name of the following file is

swap.py

def swap(a,b):

temp = a

a = b

b = temp

print(a)

print(b)

Output


2. Circulate the Values of n Variables

We circulate the values of n variable with the help of list. Suppose list a is created as [1, 2, 3, 4], then these 4 variables can be rotated as follows -


The program for the above activity can be written using function as follows:

Step 1: Create a function for circulating the values. Save this function in some file.


Step 2: Run the above script using F5 key. The output can be obtained as follows:


 

3. Distance between Two Points

Step 1: The formula for calculating distance between two points is,


import math

print("Enter value of x1")

x1=int(input())

print("Enter value of x2")

x2=int(input())

print("Enter value of yl")

yl=int(input())

print("Enter value of y2")

y2 = int(input())

dist = math.sqrt( (x2 - x1)**2 + (y2 - y1)**2)

print("The distance between two points is: ",dist)

Step 2: Just run the above code by pressing F5 key and the output will be


 

4.  Test for Leap Year

def Leap(year):

if year % 4 == 0 and year %100 != 0 or year % 400 = = 0:

print ("\nIs a leap-year")

else:

print ("\nIs not a leap-year")

Output


Program Explanation :

In above program, we have to check multiple conditions within one If Statement, we used Logical AND and Logical OR operators. These conditions are –

1: ( year%400 =0) OR

2: ( year%4 == 0 ) AND

3: ( year%100 == 0))

If these conditions are true then the year value is a leap year value otherwise not.

Review Question

1. Write a Python function to swap the values of two variables.

AU : Dec.-19, Marks 4

 

Problem Solving and Python Programming: UNIT II: Data Types, Expressions, Statements : Tag: Engineering Python : Data Types, Expressions, Statements - Illustrative Python Programs