Python Function With Parameters, No Return


 28 total views

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.


Python Programming: Using Problem Solving Approach

Python Programming is designed as a textbook to fulfil the requirements of the first-level course in Python programming. It is suited for undergraduate degree students of computer science engineering, information technology as well as computer applications. This book will enable students to apply the Python programming concepts in solving real-world problems. The book begins with an introduction to computers, problem solving approaches, programming languages, object oriented programming and Python programming. Separate chapters dealing with the important constructs of Python language such as control statements, functions, strings, files, data structures, classes and objects, inheritance, operator overloading and exceptions are provided in the book. Each chapter ends with objective-type questions, review questions, programming and debugging exercises to facilitate revision and practice of concepts learnt.