Featured
- Get link
- X
- Other Apps
Program
In todays post lets some basic programs
Program to add two numbers:
b=20
c=a+b
print(c)
Output: 30
The above example program is about addition of two given number which everyone is well known about that
Program to print sum of n numbers:
temp = num
sum = 0
if num<=0:
print("enter positive number")
else:
while num>0:
sum = sum+num
num = num-1
print("sum of ", temp,"number is",sum)
Output:
sum of 5 number is 15
The above example is to add sum of n numbers in this program first it gets a number(num) from user here the temp is used to hold the value of num. If the given number negative number it informs the user to print a positive number. If the number is positive it goes inside the while loop and calculate the sum and finally print the sum
Program to print sum of given n number:
sum = 0
for i in range(0,n):
num = int(input("enter the number:"))
sum = sum+num
print("total:",sum)
Output:
Enter the number:2
Enter the number:3
total:5
The before program is same as the above program here the program gets the number which is to be added from the user itself. The calculation is based on the input value
Program to swap two variables:
print("before swapping")
print(a,b)
a,b = b,a
Print("after swapping")
print(a,b)
Output:
20,10
Swapping is very simple in python. Swappyin nothing but changing a value of variable to another variable.
Program to describe usage of global variable:
def sample ():
x = 100
print(x)
sample()
print(x)
Output:
200
In this program the variable x is declared two times one is inside a function and another above the program as globally. The variable x=100 cannot be used outside of the function where as the variable x=200 can be used anywhere of the program.
To make it more clear and understandable go to the python console page and try the code with different variable and values or try the program in your editor. If you have any doubt feel free to comment!!!!!
- Get link
- X
- Other Apps
Comments
Post a Comment