Home | | Problem Solving and Python Programming | Python Basic Programs

Data, Expressions, Statements | Problem Solving and Python Programming - Python Basic Programs | Problem Solving and Python Programming : Data, Expressions, Statements

Chapter: Problem Solving and Python Programming : Data, Expressions, Statements

Python Basic Programs

Problem Solving and Python Programming : Data, Expressions, Statements

Programs

 

1. Python program to swap two variables

# To take input from the user

x = input('Enter value of x: ')

y = input('Enter value of y: ')

#x = 5

#y = 10

# create a temporary variable and swap the values

x = x + y

y = x - y

x = x + y

print 'The value of x after swapping:’,x

print 'The value of y after swapping:’,y

 

2. Python Program to calculate the square root

# Note: change this value for a different result

num = 8

# uncomment to take the input from the user

#num = float(input('Enter a number: '))

num_sqrt = num ** 0.5

print('The square root of %0.3f is %0.3f'%(num ,num_sqrt))

 

3. Distance between two points

import math

p1 = [4, 0]

p2 = [6, 6]

distance = math.sqrt( ((p1[0]-p2[0])**2)+((p1[1]-p2[1])**2) )

print(distance)

 

4. Write a function that draws a grid like the following:

+ - - - - + - - - - +

|            |             |

|            |             |

|            |             |

|            |             |

+ - - - - + - - - - +

|            |             |

|            |             |

|            |             |

|            |             |

+ - - - - + - - - - +

 

def print_border():

print ("+", "- " * 4, "+", "- " * 4, "+")

 

def print_row():

print ("|", " " * 8, "|", " " * 8, "|")

 

def block():

print_border()

print_row()

print_row()

print_row()

print_row()

 

block()

block()

print_border()

 

5. Adding two numbers using user defined function.

# Program to illustrate

# the use of user-defined functions

def add_numbers(x,y):

sum = x + y

return sum

num1 = 5

num2 = 6

print("The sum is", add_numbers(num1, num2))

 

6. Program to circulate the values of n variables

from collections import deque

lst=[1,2,3,4,5]

d=deque(lst)

print d

d.rotate(2)

print d

Output:[3,4,5,1,2]

 

(OR)

list=[10,20,30,40,50]

n=2 #Shift 2 location

list[n:]+list[:n]

 

Output: [30,40,50,10,20]

 

Tags : Data, Expressions, Statements | Problem Solving and Python Programming , Problem Solving and Python Programming : Data, Expressions, Statements
Study Material, Lecturing Notes, Assignment, Reference, Wiki description explanation, brief detail
Problem Solving and Python Programming : Data, Expressions, Statements : Python Basic Programs | Data, Expressions, Statements | Problem Solving and Python Programming

Related Topics

Problem Solving and Python Programming : Data, Expressions, Statements


Privacy Policy, Terms and Conditions, DMCA Policy and Compliant

Copyright © 2018-2024 BrainKart.com; All Rights Reserved. Developed by Therithal info, Chennai.