Python Function With Parameters, No Return

In the previous example, you have seen that python can take no parameter and return some value. In this example, you will learn that a function can take some parameter and output the results without returning the value.


Python Program To Reverse a String

In this example, we will accept a string as parameter and then reverse the string and print the output to the console. The function does not return anything.

## Program to reverse a string
my_string = "Great Country!"
# Function Definition
def reverse_string(s):
     for i in range(len(s)-1, -1, -1):
             print(s[i], end= " ")
# Function Call

There are a few things worth mentioning here. The function use the len() function which returns the length of the string. The len(s)-1 gives the index of the last character of the my_string.The index of first character is 0.

== RESTART: C:/Python_projects/Functions/ ==
! y r t n u o C   t a e r G 

Lets understand why range(len(s)-1, -1, -1) is going to work. The range function starts with len(s)-1 and goes up to -1. But it does not include -1 because range does not include the upper limit. Therefore, all characters starting with 12(because there are 13 characters in the string) to 0 are printed in reverse order.

Note that the last -1 in the range() function indicate that the function is decrementing. In the next article, we will discuss about functions that do take parameters and also return a value.


Ads Blocker Image Powered by Code Help Pro

Ads Blocker Detected!!!

We have detected that you are using extensions to block ads. Please support us by disabling these ads blocker.

Powered By
Best Wordpress Adblock Detecting Plugin | CHP Adblock