Home | | Problem Solving and Python Programming | Example Python Programs: Control Flow, Functions

# Example Python Programs: Control Flow, Functions

Problem Solving and Python Programming : Control Flow, Functions

ILLUSTRATIVE PROGRAMS:

## Square root using newtons method:

def newtonsqrt(n):

root=n/2

for i in range(10):

root=(root+n/root)/2

print(root)

n=eval(input("enter number to find Sqrt: "))

newtonsqrt(n)

### Output:

enter number to find Sqrt: 9

3.0

## GCD of two numbers

n1=int(input("Enter a number1:"))

n2=int(input("Enter a number2:"))

for i in range(1,n1+1):

if(n1%i==0 and n2%i==0):

gcd=i

print(gcd)

### output

Enter a number1:8

Enter a number2:24

8

## Exponent of number

def power(base,exp):

if(exp==1):

return(base)

else:

return(base*power(base,exp-1))

base=int(input("Enter base: "))

exp=int(input("Enter exponential value:"))

result=power(base,exp)

print("Result:",result)

### Output:

Enter base: 2

Enter exponential value:3

Result: 8

## sum of array elements:

a=[2,3,4,5,6,7,8]

sum=0

for i in a:

sum=sum+i

print("the sum is",sum)

the sum is 35

## Linear search

a=[20,30,40,50,60,70,89]

print(a)

search=eval(input("enter a element to search:"))

for i in range(0,len(a),1):

if(search==a[i]):

print("element found at",i+1)

break

else:

### output

[20, 30, 40, 50, 60, 70, 89]

enter a element to search:30

element found at 2

## Binary search

a=[20, 30, 40, 50, 60, 70, 89]

print(a)

search=eval(input("enter a element to search:"))

start=0

stop=len(a)-1

while(start<=stop):

mid=(start+stop)//2

if(search==a[mid]):

print("elemrnt found at",mid+1)

break

elif(search<a[mid]):

stop=mid-1

else:

start=mid+1

else:

### output

[20, 30, 40, 50, 60, 70, 89]

enter a element to search:30

element found at 2

Study Material, Lecturing Notes, Assignment, Reference, Wiki description explanation, brief detail
Problem Solving and Python Programming : Control Flow, Functions : Example Python Programs: Control Flow, Functions |