www.w3schools.com
Open in
urlscan Pro
192.229.133.221
Public Scan
URL:
https://www.w3schools.com/python/python_functions.asp
Submission: On May 22 via manual from DE — Scanned from DE
Submission: On May 22 via manual from DE — Scanned from DE
Form analysis
1 forms found in the DOMPOST exercise.asp?filename=exercise_functions1
<form autocomplete="off" id="w3-exerciseform" action="exercise.asp?filename=exercise_functions1" method="post" target="_blank">
<h2>Test Yourself With Exercises</h2>
<div class="exercisewindow">
<h2>Exercise:</h2>
<p>Create a function named <code class="w3-codespan">my_function</code>.</p>
<div class="exerciseprecontainer">
<pre><input name="ex1" maxlength="17" style="width: 180px;">:
print("Hello from a function")
</pre>
</div>
<br>
<button type="submit" class="w3-btn w3-margin-bottom">Submit Answer »</button>
<p><a target="_blank" href="exercise.asp?filename=exercise_functions1">Start the Exercise</a></p>
</div>
</form>
Text Content
Tutorials Exercises Certificates Services Menu Search field × Log in Sign Up ★ +1 My W3Schools Get Certified Spaces Plus Get Certified Spaces Plus My W3Schools Tutorials Exercises Certificates Services Spaces Get Certified Plus Logout × TUTORIALS Tutorials filter input × HTML AND CSS Learn HTML Tutorial Reference Learn CSS Tutorial Reference Learn RWD Tutorial Learn Bootstrap Overview Learn W3.CSS Tutorial Reference Learn Sass Tutorial Reference Learn Colors Tutorial Reference Learn Icons Tutorial Reference Learn SVG Tutorial Reference Learn Canvas Tutorial Reference Learn Graphics Tutorial Learn Character Sets Reference Learn How To Tutorial DATA ANALYTICS Learn AI Tutorial Learn Generative AI Tutorial Learn ChatGPT-3.5 Tutorial Learn ChatGPT-4 Tutorial Learn Google Bard Tutorial Learn Machine Learning Tutorial Learn DSA Tutorial Learn Data Science Tutorial Learn NumPy Tutorial Learn Pandas Tutorial Learn SciPy Tutorial Learn Matplotlib Tutorial Learn Statistics Tutorial Learn Excel Tutorial Learn Google Sheets Tutorial WEB BUILDING Create a Website HOT! Create a Server NEW Where To Start Web Templates Web Statistics Web Certificates Web Development Code Editor Test Your Typing Speed Play a Code Game Cyber Security Accessibility Join our Newsletter JAVASCRIPT Learn JavaScript Tutorial Reference Learn React Tutorial Learn jQuery Tutorial Reference Learn Vue Tutorial Reference Learn AngularJS Tutorial Reference Learn JSON Tutorial Reference Learn AJAX Tutorial Learn AppML Tutorial Reference Learn W3.JS Tutorial Reference WEB BUILDING Create a Website HOT! Create a Server NEW Where To Start Web Templates Web Statistics Web Certificates Web Development Code Editor Test Your Typing Speed Play a Code Game Cyber Security Accessibility Join our Newsletter BACKEND Learn Python Tutorial Reference Learn SQL Tutorial Reference Learn MySQL Tutorial Reference Learn PHP Tutorial Reference Learn Java Tutorial Reference Learn C Tutorial Learn C++ Tutorial Reference Learn C# Tutorial Learn R Tutorial Learn Kotlin Tutorial Learn Go Tutorial Learn Django Tutorial Reference Learn PostgreSQL Tutorial Learn TypeScript Tutorial Learn ASP Tutorial Reference Learn Node.js Tutorial Reference Learn Raspberry Pi Tutorial Learn Git Tutorial Learn MongoDB Tutorial Learn AWS Cloud Tutorial Learn XML Tutorial Reference DATA ANALYTICS Learn AI Tutorial Learn Generative AI Tutorial Learn ChatGPT-3.5 Tutorial Learn ChatGPT-4 Tutorial Learn Google Bard Tutorial Learn Machine Learning Tutorial Learn DSA Tutorial Learn Data Science Tutorial Learn NumPy Tutorial Learn Pandas Tutorial Learn SciPy Tutorial Learn Matplotlib Tutorial Learn Statistics Tutorial Learn Excel Tutorial Learn Google Sheets Tutorial WEB BUILDING Create a Website HOT! Create a Server NEW Where To Start Web Templates Web Statistics Web Certificates Web Development Code Editor Test Your Typing Speed Play a Code Game Cyber Security Accessibility Join our Newsletter × EXERCISES Excercises filter input × HTML AND CSS HTML Exercise Quiz CSS Exercise Quiz Bootstrap 3 Exercise Quiz Bootstrap 4 Exercise Quiz Bootstrap 5 Exercise Quiz DATA ANALYTICS DSA Exercise Quiz NumPy Exercise Quiz Pandas Exercise Quiz SciPy Exercise Quiz Excel Exercise What is an Exercise? What is a Quiz? JAVASCRIPT JavaScript Exercise Quiz React Exercise Quiz jQuery Exercise Quiz Vue Exercise Quiz BACKEND Python Exercise Quiz SQL Exercise Quiz MySQL Exercise Quiz PHP Exercise Quiz Java Exercise Quiz C Exercise Quiz C++ Exercise Quiz C# Exercise Quiz R Exercise Quiz Kotlin Exercise Quiz Django Exercise Quiz PostgreSQL Exercise Quiz TypeScript Exercise Quiz Git Exercise Quiz Go Exercise MongoDB Exercise AWS Cloud Exercise Quiz DATA ANALYTICS DSA Exercise Quiz NumPy Exercise Quiz Pandas Exercise Quiz SciPy Exercise Quiz Excel Exercise What is an Exercise? What is a Quiz? × CERTIFICATES Filter field for certifications × HTML AND CSS HTML Certificate Course CSS Certificate Course Bootstrap 3 Certificate Course Bootstrap 4 Certificate Course Bootstrap 5 Certificate DATA ANALYTICS DSA Certificate Data Analytics Course NumPy Certificate Course Pandas Certificate Course Excel Certificate Social Media Course What is a Certificate? PROGRAMS Full Access Best Value! Front End Certificate Course Web Dev. Certificate Course Web App Certificate Course Web Design Certificate Course JAVASCRIPT JavaScript Certificate Course React Certificate Course jQuery Certificate Course Vue Certificate PROGRAMS Full Access Best Value! Front End Certificate Course Web Dev. Certificate Course Web App Certificate Course Web Design Certificate Course PROGRAMS Full Access Best Value! Front End Certificate Course Web Dev. Certificate Course Web App Certificate Course Web Design Certificate Course BACKEND Python Certificate Course SQL Certificate Course MySQL Certificate PHP Certificate Course Java Certificate Course C Certificate C++ Certificate Course C# Certificate Course R Course Django Certificate TypeScript Certificate Course XML Certificate Course Cyber Security Certificate Course Accessibility Certificate Course Python Apps on AWS Course AWS Training Courses DATA ANALYTICS DSA Exam Data Analytics Course NumPy Course Pandas Course Excel Certificate Social Media Course What is a Certificate? × ALL OUR SERVICES Services filter input × W3Schools offers a wide range of services and products for beginners and professionals, helping millions of people everyday to learn and master new skills. FREE TUTORIALS Enjoy our free tutorials like millions of other internet users since 1999 REFERENCES Explore our selection of references covering all popular coding languages CREATE A WEBSITE Create your own website with W3Schools Spaces - no setup required EXERCISES Test your skills with different exercises QUIZZES Test yourself with multiple choice questions GET CERTIFIED Document your knowledge LOG IN / SIGN UP Create a free W3Schools Account to Improve Your Learning Experience PATHFINDER & MY LEARNING Track your learning progress at W3Schools and collect rewards UPGRADE Become a PLUS user and unlock powerful features (ad-free, hosting, support,..) WHERE TO START Not sure where you want to start? Follow our guided path CODE EDITOR (TRY IT) With our online code editor, you can edit code and view the result in your browser VIDEOS Learn the basics of HTML in a fun and engaging video tutorial TEMPLATES We have created a bunch of responsive website templates you can use - for free! WEB HOSTING Host your own website, and share it to the world with W3Schools Spaces CREATE A SERVER Create your own server using Python, PHP, React.js, Node.js, Java, C#, etc. HOW TO'S Large collection of code snippets for HTML, CSS and JavaScript CSS FRAMEWORK Build fast and responsive sites using our free W3.CSS framework BROWSER STATISTICS Read long term trends of browser usage TYPING SPEED Test your typing speed AWS TRAINING Learn Amazon Web Services COLOR PICKER Use our color picker to find different RGB, HEX and HSL colors. CODE GAME W3Schools Coding Game! Help the lynx collect pine cones SET GOAL Get personalized learning journey based on your current skills and goals NEWSLETTER Join our newsletter and get access to exclusive content every month JOBS Hire top tech talents. Streamline your hiring process for the perfect team fit CONTACT US About sales: sales@w3schools.com About errors: help@w3schools.com CLASSROOM Get in touch for using W3Schools Plus and certifications as an educational institution × ❮ HTML CSS JAVASCRIPT SQL PYTHON JAVA PHP HOW TO W3.CSS C C++ C# BOOTSTRAP REACT MYSQL JQUERY EXCEL XML DJANGO NUMPY PANDAS NODEJS R TYPESCRIPT ANGULAR GIT POSTGRESQL MONGODB ASP AI GO KOTLIN SASS VUE DSA GEN AI SCIPY AWS CYBERSECURITY DATA SCIENCE ❯ PYTHON TUTORIAL Python HOME Python Intro Python Get Started Python Syntax Python Comments Python Variables Python Variables Variable Names Assign Multiple Values Output Variables Global Variables Variable Exercises Python Data Types Python Numbers Python Casting Python Strings Python Strings Slicing Strings Modify Strings Concatenate Strings Format Strings Escape Characters String Methods String Exercises Python Booleans Python Operators Python Lists Python Lists Access List Items Change List Items Add List Items Remove List Items Loop Lists List Comprehension Sort Lists Copy Lists Join Lists List Methods List Exercises Python Tuples Python Tuples Access Tuples Update Tuples Unpack Tuples Loop Tuples Join Tuples Tuple Methods Tuple Exercises Python Sets Python Sets Access Set Items Add Set Items Remove Set Items Loop Sets Join Sets Set Methods Set Exercises Python Dictionaries Python Dictionaries Access Items Change Items Add Items Remove Items Loop Dictionaries Copy Dictionaries Nested Dictionaries Dictionary Methods Dictionary Exercise Python If...Else Python While Loops Python For Loops Python Functions Python Lambda Python Arrays Python Classes/Objects Python Inheritance Python Iterators Python Polymorphism Python Scope Python Modules Python Dates Python Math Python JSON Python RegEx Python PIP Python Try...Except Python User Input Python String Formatting FILE HANDLING Python File Handling Python Read Files Python Write/Create Files Python Delete Files PYTHON MODULES NumPy Tutorial Pandas Tutorial SciPy Tutorial Django Tutorial PYTHON MATPLOTLIB Matplotlib Intro Matplotlib Get Started Matplotlib Pyplot Matplotlib Plotting Matplotlib Markers Matplotlib Line Matplotlib Labels Matplotlib Grid Matplotlib Subplot Matplotlib Scatter Matplotlib Bars Matplotlib Histograms Matplotlib Pie Charts MACHINE LEARNING Getting Started Mean Median Mode Standard Deviation Percentile Data Distribution Normal Data Distribution Scatter Plot Linear Regression Polynomial Regression Multiple Regression Scale Train/Test Decision Tree Confusion Matrix Hierarchical Clustering Logistic Regression Grid Search Categorical Data K-means Bootstrap Aggregation Cross Validation AUC - ROC Curve K-nearest neighbors PYTHON MYSQL MySQL Get Started MySQL Create Database MySQL Create Table MySQL Insert MySQL Select MySQL Where MySQL Order By MySQL Delete MySQL Drop Table MySQL Update MySQL Limit MySQL Join PYTHON MONGODB MongoDB Get Started MongoDB Create DB MongoDB Collection MongoDB Insert MongoDB Find MongoDB Query MongoDB Sort MongoDB Delete MongoDB Drop Collection MongoDB Update MongoDB Limit PYTHON REFERENCE Python Overview Python Built-in Functions Python String Methods Python List Methods Python Dictionary Methods Python Tuple Methods Python Set Methods Python File Methods Python Keywords Python Exceptions Python Glossary MODULE REFERENCE Random Module Requests Module Statistics Module Math Module cMath Module PYTHON HOW TO Remove List Duplicates Reverse a String Add Two Numbers PYTHON EXAMPLES Python Examples Python Compiler Python Exercises Python Quiz Python Server Python Bootcamp Python Certificate PYTHON FUNCTIONS ❮ Previous Next ❯ -------------------------------------------------------------------------------- A function is a block of code which only runs when it is called. You can pass data, known as parameters, into a function. A function can return data as a result. -------------------------------------------------------------------------------- CREATING A FUNCTION In Python a function is defined using the def keyword: EXAMPLEGET YOUR OWN PYTHON SERVER def my_function(): print("Hello from a function") -------------------------------------------------------------------------------- CALLING A FUNCTION To call a function, use the function name followed by parenthesis: EXAMPLE def my_function(): print("Hello from a function") my_function() Try it Yourself » -------------------------------------------------------------------------------- ARGUMENTS Information can be passed into functions as arguments. Arguments are specified after the function name, inside the parentheses. You can add as many arguments as you want, just separate them with a comma. The following example has a function with one argument (fname). When the function is called, we pass along a first name, which is used inside the function to print the full name: EXAMPLE def my_function(fname): print(fname + " Refsnes") my_function("Emil") my_function("Tobias") my_function("Linus") Try it Yourself » Arguments are often shortened to args in Python documentations. -------------------------------------------------------------------------------- -------------------------------------------------------------------------------- PARAMETERS OR ARGUMENTS? The terms parameter and argument can be used for the same thing: information that are passed into a function. From a function's perspective: A parameter is the variable listed inside the parentheses in the function definition. An argument is the value that is sent to the function when it is called. -------------------------------------------------------------------------------- NUMBER OF ARGUMENTS By default, a function must be called with the correct number of arguments. Meaning that if your function expects 2 arguments, you have to call the function with 2 arguments, not more, and not less. EXAMPLE This function expects 2 arguments, and gets 2 arguments: def my_function(fname, lname): print(fname + " " + lname) my_function("Emil", "Refsnes") Try it Yourself » If you try to call the function with 1 or 3 arguments, you will get an error: EXAMPLE This function expects 2 arguments, but gets only 1: def my_function(fname, lname): print(fname + " " + lname) my_function("Emil") Try it Yourself » -------------------------------------------------------------------------------- ARBITRARY ARGUMENTS, *ARGS If you do not know how many arguments that will be passed into your function, add a * before the parameter name in the function definition. This way the function will receive a tuple of arguments, and can access the items accordingly: EXAMPLE If the number of arguments is unknown, add a * before the parameter name: def my_function(*kids): print("The youngest child is " + kids[2]) my_function("Emil", "Tobias", "Linus") Try it Yourself » Arbitrary Arguments are often shortened to *args in Python documentations. -------------------------------------------------------------------------------- KEYWORD ARGUMENTS You can also send arguments with the key = value syntax. This way the order of the arguments does not matter. EXAMPLE def my_function(child3, child2, child1): print("The youngest child is " + child3) my_function(child1 = "Emil", child2 = "Tobias", child3 = "Linus") Try it Yourself » The phrase Keyword Arguments are often shortened to kwargs in Python documentations. -------------------------------------------------------------------------------- ARBITRARY KEYWORD ARGUMENTS, **KWARGS If you do not know how many keyword arguments that will be passed into your function, add two asterisk: ** before the parameter name in the function definition. This way the function will receive a dictionary of arguments, and can access the items accordingly: EXAMPLE If the number of keyword arguments is unknown, add a double ** before the parameter name: def my_function(**kid): print("His last name is " + kid["lname"]) my_function(fname = "Tobias", lname = "Refsnes") Try it Yourself » Arbitrary Kword Arguments are often shortened to **kwargs in Python documentations. -------------------------------------------------------------------------------- DEFAULT PARAMETER VALUE The following example shows how to use a default parameter value. If we call the function without argument, it uses the default value: EXAMPLE def my_function(country = "Norway"): print("I am from " + country) my_function("Sweden") my_function("India") my_function() my_function("Brazil") Try it Yourself » -------------------------------------------------------------------------------- PASSING A LIST AS AN ARGUMENT You can send any data types of argument to a function (string, number, list, dictionary etc.), and it will be treated as the same data type inside the function. E.g. if you send a List as an argument, it will still be a List when it reaches the function: EXAMPLE def my_function(food): for x in food: print(x) fruits = ["apple", "banana", "cherry"] my_function(fruits) Try it Yourself » -------------------------------------------------------------------------------- RETURN VALUES To let a function return a value, use the return statement: EXAMPLE def my_function(x): return 5 * x print(my_function(3)) print(my_function(5)) print(my_function(9)) Try it Yourself » -------------------------------------------------------------------------------- THE PASS STATEMENT function definitions cannot be empty, but if you for some reason have a function definition with no content, put in the pass statement to avoid getting an error. EXAMPLE def myfunction(): pass Try it Yourself » -------------------------------------------------------------------------------- POSITIONAL-ONLY ARGUMENTS You can specify that a function can have ONLY positional arguments, or ONLY keyword arguments. To specify that a function can have only positional arguments, add , / after the arguments: EXAMPLE def my_function(x, /): print(x) my_function(3) Try it Yourself » Without the , / you are actually allowed to use keyword arguments even if the function expects positional arguments: EXAMPLE def my_function(x): print(x) my_function(x = 3) Try it Yourself » But when adding the , / you will get an error if you try to send a keyword argument: EXAMPLE def my_function(x, /): print(x) my_function(x = 3) Try it Yourself » -------------------------------------------------------------------------------- KEYWORD-ONLY ARGUMENTS To specify that a function can have only keyword arguments, add *, before the arguments: EXAMPLE def my_function(*, x): print(x) my_function(x = 3) Try it Yourself » Without the *, you are allowed to use positionale arguments even if the function expects keyword arguments: EXAMPLE def my_function(x): print(x) my_function(3) Try it Yourself » But when adding the *, / you will get an error if you try to send a positional argument: EXAMPLE def my_function(*, x): print(x) my_function(3) Try it Yourself » -------------------------------------------------------------------------------- COMBINE POSITIONAL-ONLY AND KEYWORD-ONLY You can combine the two argument types in the same function. Any argument before the / , are positional-only, and any argument after the *, are keyword-only. EXAMPLE def my_function(a, b, /, *, c, d): print(a + b + c + d) my_function(5, 6, c = 7, d = 8) Try it Yourself » -------------------------------------------------------------------------------- RECURSION Python also accepts function recursion, which means a defined function can call itself. Recursion is a common mathematical and programming concept. It means that a function calls itself. This has the benefit of meaning that you can loop through data to reach a result. The developer should be very careful with recursion as it can be quite easy to slip into writing a function which never terminates, or one that uses excess amounts of memory or processor power. However, when written correctly recursion can be a very efficient and mathematically-elegant approach to programming. In this example, tri_recursion() is a function that we have defined to call itself ("recurse"). We use the k variable as the data, which decrements (-1) every time we recurse. The recursion ends when the condition is not greater than 0 (i.e. when it is 0). To a new developer it can take some time to work out how exactly this works, best way to find out is by testing and modifying it. EXAMPLE Recursion Example def tri_recursion(k): if(k > 0): result = k + tri_recursion(k - 1) print(result) else: result = 0 return result print("\n\nRecursion Example Results") tri_recursion(6) Try it Yourself » -------------------------------------------------------------------------------- TEST YOURSELF WITH EXERCISES EXERCISE: Create a function named my_function. : print("Hello from a function") Submit Answer » Start the Exercise -------------------------------------------------------------------------------- ❮ Previous Next ❯ ★ +1 W3schools Pathfinder Track your progress - it's free! Log in Sign Up COLOR PICKER -------------------------------------------------------------------------------- SPACES UPGRADE AD-FREE NEWSLETTER GET CERTIFIED CONTACT US × 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 TOP TUTORIALS HTML Tutorial CSS Tutorial JavaScript Tutorial How To Tutorial SQL Tutorial Python Tutorial W3.CSS Tutorial Bootstrap Tutorial PHP Tutorial Java Tutorial C++ Tutorial jQuery Tutorial TOP REFERENCES HTML Reference CSS Reference JavaScript Reference SQL Reference Python Reference W3.CSS Reference Bootstrap Reference PHP Reference HTML Colors Java Reference Angular Reference jQuery Reference TOP EXAMPLES HTML Examples CSS Examples JavaScript Examples How To Examples SQL Examples Python Examples W3.CSS Examples Bootstrap Examples PHP Examples Java Examples XML Examples jQuery Examples GET CERTIFIED HTML Certificate CSS Certificate JavaScript Certificate Front End Certificate SQL Certificate Python Certificate PHP Certificate jQuery Certificate Java Certificate C++ Certificate C# Certificate XML Certificate FORUM ABOUT CLASSROOM 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 our terms of use, cookie and privacy policy. Copyright 1999-2024 by Refsnes Data. All Rights Reserved. W3Schools is Powered by W3.CSS. DER SCHUTZ IHRER PRIVATSPHÄRE LIEGT UNS AM HERZEN! Beim Besuch unserer Website können ausgewählte Unternehmen auf bestimmte Informationen auf Ihrem Gerät und auf dieser Webseite zugreifen und diese verwenden, um relevante Anzeigen oder personalisierte Inhalte zu schalten. Bitte beachten Sie, dass Anzeigen dazu beitragen, dass unser Dienst weiterhin kostenlos bleibt. Personenbezogene Daten werden basierend auf der Zustimmung gemäß Artikel 6 Absatz 1 Buchstabe a des DSGVO-Rahmens im EU-Recht verarbeitet oder wenn ein berechtigtes Interesse gemäß Artikel 6 Absatz 1 Buchstabe f desselben vorliegt. ERFAHREN SIE MEHR DARÜBER, WARUM IHNEN DIES ANGEZEIGT WIRD Wir, der 'Herausgeber' und eine ausgewählte Gruppe von vertrauenswürdigen Partnern (830), die als 'Anbieter' bezeichnet werden, benötigen Ihre Zustimmung zum Zweck der Datenverarbeitung. Mit diesen Zwecken können wir Informationen auf einem Gerät speichern und/oder abrufen, wie z. B. die Cookie-Verwaltung, und personenbezogene Daten verarbeiten, wie Standardinformationen, die von einem Gerät gesendet werden, und andere eindeutige Kennungen für personalisierte Anzeigen und Inhalte, Anzeigen- und Inhaltsmessungen, Erkenntnisse über Zielgruppen und Produktentwicklungen. Mit Ihrer Zustimmung können wir und unsere Partner möglicherweise genaue Standortdaten verwenden und Geräteeigenschaften zur Identifikation aktiv abfragen. Sie können der oben beschriebenen Verarbeitung zustimmen oder auf detailliertere Informationen zugreifen und Ihre Auswahl anpassen. Die erteilte Zustimmung gilt nur für diese Website. Bitte beachten Sie, dass ein Teil der Verarbeitung Ihrer personenbezogenen Daten möglicherweise auf berechtigten Interessen beruht, für die Ihre Zustimmung nicht erforderlich ist. Sie haben jedoch das Recht, dem zu widersprechen. Sie können Ihre Einstellungen jederzeit auf der Datenschutzerklärungsseite auf unserer Website ändern. Auswahlmöglichkeiten anpassen Alle akzeptieren und Website besuchen