Tag Archives: basic python

Python- Function

We use the def keyword to create a user-defined function.

eg: def function_name( parameters ) :

eg: There are two functions in this program. One which returns a value and the other which does not return a value.

def calculate_sum( num1, num2 ):
total = num1 + num2
print (“First number is :”, num1)
print (“Second number is : “, num2)
print (“The total sum is “, total)
return total ;

def calculate_diff (num1, num2):
print (“Function without return”)
print (“First number is :”, num1)
print (“First number is :”, num2)
print (“Difference between num1 and num2 is :”, num2-num1)

total = calculate_sum(10,20)
print (“We can return the value as well :”, total)

calculate_diff(20,40)

 

————————————————————————————

 

The output will be shown as :

 

First number is : 10
Second number is : 20
The total sum is 30
We can return the value as well : 30
Function without return
First number is : 20
First number is : 40
Difference between num1 and num2 is : 20

Advertisements

Python- The Strings

Strings in Python can be created by enclosing characters in either single quotes ‘example ‘  or in double quotes “example”

It’s easy to declare a string as shown below:

str1 = ‘hello world’

str2 =  “hello world”

 

 

To concatenate two strings we can use the ‘+’  operator

 

 

You can use brackets for slicing the string between indexes:

 

When you run the final program, you should get the output as below:

Python- The Loops

The while loop 

To test the while loop copy the code as below:

lv_counter = 0
while (lv_counter < 10):
print(“The counter value is: “,lv_counter)
lv_counter = lv_counter + 1

 

Make sure to ident the block as shown below

 

Once you run the program, you should get the output as shown below

The for loop

You can iterate over a range of number or strings or lists.

for number in range(1,10):
print (“Current number is : “,number)

for letter in ‘Tutorial’:
print(“Current letter is :”,letter)

places = [‘Dhaka’,’Islamabad’,’Thimpu’,’New Delhi’]
for place in places:
print(“You are in this city now :”,place)

In the same file created above, add the above lines as shown below”:

 

Once you’ve run the program, you should see the output as shown below: