Movatterモバイル変換


[0]ホーム

URL:


Menu
×
See More 
Sign In
+1 Get Certified Upgrade For Teachers Spaces Get Certified Upgrade For Teachers Spaces
   ❮     
     ❯   

Python Tutorial

Python HOMEPython IntroPython Get StartedPython SyntaxPython OutputPython CommentsPython VariablesPython Data TypesPython NumbersPython CastingPython StringsPython BooleansPython OperatorsPython ListsPython TuplesPython SetsPython DictionariesPython If...ElsePython MatchPython While LoopsPython For LoopsPython FunctionsPython RangePython ArraysPython IteratorsPython ModulesPython DatesPython MathPython JSONPython RegExPython PIPPython Try...ExceptPython String FormattingPython NonePython User InputPython VirtualEnv

Python Classes

Python OOPPython Classes/ObjectsPython __init__ MethodPython self ParameterPython Class PropertiesPython Class MethodsPython InheritancePython PolymorphismPython EncapsulationPython Inner Classes

File Handling

Python File HandlingPython Read FilesPython Write/Create FilesPython Delete Files

Python Modules

NumPy TutorialPandas TutorialSciPy TutorialDjango Tutorial

Python Matplotlib

Matplotlib IntroMatplotlib Get StartedMatplotlib PyplotMatplotlib PlottingMatplotlib MarkersMatplotlib LineMatplotlib LabelsMatplotlib GridMatplotlib SubplotMatplotlib ScatterMatplotlib BarsMatplotlib HistogramsMatplotlib Pie Charts

Machine Learning

Getting StartedMean Median ModeStandard DeviationPercentileData DistributionNormal Data DistributionScatter PlotLinear RegressionPolynomial RegressionMultiple RegressionScaleTrain/TestDecision TreeConfusion MatrixHierarchical ClusteringLogistic RegressionGrid SearchCategorical DataK-meansBootstrap AggregationCross ValidationAUC - ROC CurveK-nearest neighbors

Python DSA

Python DSALists and ArraysStacksQueuesLinked ListsHash TablesTreesBinary TreesBinary Search TreesAVL TreesGraphsLinear SearchBinary SearchBubble SortSelection SortInsertion SortQuick SortCounting SortRadix SortMerge Sort

Python MySQL

MySQL Get StartedMySQL Create DatabaseMySQL Create TableMySQL InsertMySQL SelectMySQL WhereMySQL Order ByMySQL DeleteMySQL Drop TableMySQL UpdateMySQL LimitMySQL Join

Python MongoDB

MongoDB Get StartedMongoDB Create DBMongoDB CollectionMongoDB InsertMongoDB FindMongoDB QueryMongoDB SortMongoDB DeleteMongoDB Drop CollectionMongoDB UpdateMongoDB Limit

Python Reference

Python OverviewPython Built-in FunctionsPython String MethodsPython List MethodsPython Dictionary MethodsPython Tuple MethodsPython Set MethodsPython File MethodsPython KeywordsPython ExceptionsPython Glossary

Module Reference

Built-in ModulesRandom ModuleRequests ModuleStatistics ModuleMath ModulecMath Module

Python How To

Remove List DuplicatesReverse a StringAdd Two Numbers

Python Examples

Python ExamplesPython CompilerPython ExercisesPython QuizPython ServerPython SyllabusPython Study PlanPython Interview Q&APython BootcampPython CertificatePython Training

PythonFunctions


Python Functions

A function is a block of code which only runs when it is called.

A function can return data as a result.

A function helps avoiding code repetition.


Creating a Function

In Python, a function is defined using thedef keyword, followed by a function name and parentheses:

Example

def my_function():
  print("Hello from a function")

This creates a function namedmy_function that prints "Hello from a function" when called.

The code inside the function must be indented. Python uses indentation to define code blocks.


Calling a Function

To call a function, write its name followed by parentheses:

Example

def my_function():
  print("Hello from a function")

my_function()
Try it Yourself »

You can call the same function multiple times:

Example

def my_function():
  print("Hello from a function")

my_function()
my_function()
my_function()
Try it Yourself »


Function Names

Function names follow the same rules as variable names in Python:

  • A function name must start with a letter or underscore
  • A function name can only contain letters, numbers, and underscores
  • Function names are case-sensitive (myFunction andmyfunction are different)

Example

Valid function names:

calculate_sum()
_private_function()
myFunction2()

It's good practice to use descriptive names that explain what the function does.


Why Use Functions?

Imagine you need to convert temperatures from Fahrenheit to Celsius several times in your program. Without functions, you would have to write the same calculation code repeatedly:

Example

Without functions - repetitive code:

temp1 = 77
celsius1 = (temp1 - 32) * 5 / 9
print(celsius1)

temp2 = 95
celsius2 = (temp2 - 32) * 5 / 9
print(celsius2)

temp3 = 50
celsius3 = (temp3 - 32) * 5 / 9
print(celsius3)
Try it Yourself »

With functions, you write the code once and reuse it:

Example

With functions - reusable code:

def fahrenheit_to_celsius(fahrenheit):
  return (fahrenheit - 32) * 5 / 9

print(fahrenheit_to_celsius(77))
print(fahrenheit_to_celsius(95))
print(fahrenheit_to_celsius(50))
Try it Yourself »

Return Values

Functions can send data back to the code that called them using thereturn statement.

When a function reaches areturn statement, it stops executing and sends the result back:

Example

A function that returns a value:

def get_greeting():
  return "Hello from a function"

message = get_greeting()
print(message)
Try it Yourself »

You can use the returned value directly:

Example

Using the return value directly:

def get_greeting():
  return "Hello from a function"

print(get_greeting())
Try it Yourself »

If a function doesn't have areturn statement, it returnsNone by default.


The pass Statement

Function definitions cannot be empty. If you need to create a function placeholder without any code, use thepass statement:

Example

def my_function():
  pass
Try it Yourself »

Thepass statement is often used when developing, allowing you to define the structure first and implement details later.




×

Contact Sales

If you want to use W3Schools services as an educational institution, team or enterprise, send us an e-mail:
sales@w3schools.com

Report Error

If you want to report an error, or if you want to make a suggestion, send us an e-mail:
help@w3schools.com

W3Schools is optimized for learning and training. Examples might be simplified to improve reading and learning.
Tutorials, references, and examples are constantly reviewed to avoid errors, but we cannot warrant full correctness
of all content. While using W3Schools, you agree to have read and accepted ourterms of use,cookies andprivacy policy.

Copyright 1999-2025 by Refsnes Data. All Rights Reserved.W3Schools is Powered by W3.CSS.


[8]ページ先頭

©2009-2025 Movatter.jp