﻿ Call a Function from an If-Statement Inside a Function - ITCodar

# Call a Function from an If-Statement Inside a Function

## Call a function from an if-statement inside a function

You're not returning anything. Capture the result of the functions and return that variable.

``function printRange(rangeStart, rangeStop) {    let summa = [];    for (i = rangeStart; i <= rangeStop; i++) {        summa.push(i);    }    let result2 = summa.join();    return result2;}function printRangeReversed(rangeStart, rangeStop) {    let summa = [];    for (i = rangeStart; i >= rangeStop; i--) {        summa.push(i);    }    let result3 = summa.join();    return result3;}function printAnyRange(rangeStart, rangeStop) {    let result = null;    if (rangeStart < rangeStop) result = printRange(rangeStart, rangeStop);    else result = printRangeReversed(rangeStart, rangeStop);            return result;}console.log(printAnyRange(1,5));console.log(printAnyRange(5,1));``

## Calling a function inside the condition of an if statement

Will the following add obj to words (edit: assuming obj is the right type AND the statement returns a boolean value

Assuming the code can run without errors (i.e. add() returns boolean), your `words.add()` method will be invoked in the if-statement.

Methods written within if-statement will be invoked and evaluated.

## How to call a function with return value inside an if statement in python

You need to create a tuple of a and b then you can compare using ==

Use this,

``if (a,b)==hi() : hello(a)``

Here is the full code which prints `asd`

``def hi():  return 10,20def hello(a):  if a:    print "asd"a,b = 10,20if (a,b)==hi() : hello(a)``

## Any way to put an if statement in the function call argument?

You can if you don't mind some ugliness... The * syntax turns a list of values into parameters, so you could use:

``foo(*[a] if a > b else [])``

Whether you should is something else :-)

## Running a function inside of an if statement

Some general observations:

• Functions, like any other object, need to be defined before they are
referenced/used. You aren't violating this, but you will be if you
fill in the rest of your while-loop. Ideally, you'll want a main
entry point for your program, so that it's clear in what order things
are being executed, and your functions are guaranteed to be defined
by the time flow-of-execution reaches the lines on which your functions are called.
• It would make sense to define one function for each corresponding
command type (except for quit). You were on the right track here.
• A couple questionable/redundant instances of f-strings (`f"{code}"` almost certainly doesn't do what you think it should.)
• Prefer `snake_case` over `camelCase` when writing Python source code.
• Your `V` command will terminate the loop (and the program)
prematurely. What if the user wants to print all courses, then a
description?

Here are my suggestions incarnate:

``def get_courses():    courses = {}    with open("assignments/assignment-19/courses.txt", "r") as file:        for line in file:            data = line.split(":")            code = data[0].strip()            class_name = data[1].strip()            courses[code] = class_name    return coursesdef display_courses(courses):    for key, value in courses.items():        print(f"{key}: {value}")def display_description(courses):    code = input("Enter course code: ").strip().lower()    if code in courses:        print(courses[code])    else:        print(f"Sorry, \"{code}\" is not in our system.")def main():    courses = get_courses()        while True:        command = input("(V)iew, (L)ookup or (Q)uit: ").lower()        if command == "v":            display_courses(courses)        elif command == "l":            display_description(courses)        elif commany == "q":            print("Goodbye!")            break        else:            print("Invalid command.")    # 'main' ends heremain()``

## Is it correct to execute a function inside IF else statement?

There is no wrong in executing a function inside if conditional statement.

For such case you can use ternary operator

``var i=-1; // Note var key word & initialized with some value  isCheck() === false ? (i=0):(i=someOtherVal)``

## is it bad practice to call a function from within an if condition?

There's nothing wrong with it. Though many C functions involve checking the result of parameters rather than the returned value and then you have no other option but to call the function on a line of its own.

Also, this is a common scenario:

``result_t result = func();if(result == ERR1)  ...else if(result == ERR2)  ...``

Here you can obviously not write

``if(func() == ERR1)  ...else if(func() == ERR2)  ...``

Because then you end up calling the function twice, which is inefficient, but could also give different results.

As for using return from a function as a way to quickly stop executing and go directly to the error handler, it's actually likely the best way of doing so in C. Other alternatives are using messy boolean flags in the loop, or the "on error goto" pattern (which is usually OK but comes with the mandatory, tiresome "goto considered harmful" debate).

As for picking up bad habits: not using const correctness of read-only parameters is a bad habit.