Determining Number Within Range

PythonPythonBeginner
Practice Now

This tutorial is from open-source community. Access the source code

Introduction

In Python, we can check if a given number falls within a specified range using arithmetic comparison. This is a common task in programming and can be useful in many different applications.


Skills Graph

%%%%{init: {'theme':'neutral'}}%%%% flowchart RL python(("`Python`")) -.-> python/BasicConceptsGroup(["`Basic Concepts`"]) python(("`Python`")) -.-> python/ControlFlowGroup(["`Control Flow`"]) python(("`Python`")) -.-> python/DataStructuresGroup(["`Data Structures`"]) python(("`Python`")) -.-> python/FunctionsGroup(["`Functions`"]) python/BasicConceptsGroup -.-> python/comments("`Comments`") python/BasicConceptsGroup -.-> python/booleans("`Booleans`") python/ControlFlowGroup -.-> python/conditional_statements("`Conditional Statements`") python/DataStructuresGroup -.-> python/tuples("`Tuples`") python/FunctionsGroup -.-> python/function_definition("`Function Definition`") python/FunctionsGroup -.-> python/default_arguments("`Default Arguments`") subgraph Lab Skills python/comments -.-> lab-13655{{"`Determining Number Within Range`"}} python/booleans -.-> lab-13655{{"`Determining Number Within Range`"}} python/conditional_statements -.-> lab-13655{{"`Determining Number Within Range`"}} python/tuples -.-> lab-13655{{"`Determining Number Within Range`"}} python/function_definition -.-> lab-13655{{"`Determining Number Within Range`"}} python/default_arguments -.-> lab-13655{{"`Determining Number Within Range`"}} end

Number in Range

Write a function in_range(n, start, end = 0) that takes in three parameters:

  • n: a number to check if it falls within the range
  • start: the start of the range
  • end: the end of the range (optional, default value is 0)

The function should return True if the given number n falls within the specified range, and False otherwise. If the end parameter is not specified, the range is considered to be from 0 to start.

def in_range(n, start, end = 0):
  return start <= n <= end if end >= start else end <= n <= start
in_range(3, 2, 5) ## True
in_range(3, 4) ## True
in_range(2, 3, 5) ## False
in_range(3, 2) ## False

Summary

In this challenge, you learned how to check if a given number falls within a specified range using arithmetic comparison in Python. This is a useful skill that can be applied in many different programming applications.

Other Python Tutorials you may like