今日已更新 233 条资讯 | 累计 20205 条内容
关于我们

Python for Beginners — Part 6: Functions

Ramesh S 2026年06月23日 11:43 2 次阅读 来源:Dev.to

Part 6 of a beginner-friendly series on learning Python from scratch. In Part 5 , we learned to organize data with lists, dictionaries, and other collections. Now it's time to organize our code itself. A function is a reusable block of code that performs a specific task. Instead of writing the same code multiple times, you write it once in a function, then call that function whenever you need it. This is the foundation of writing clean, maintainable programs. Defining and Calling Functions The basics def greet (): print ( " Hello, World! " ) greet () # Call the function Use def to define a function. The function name is followed by parentheses and a colon. The indented block below is the function's body. When you call the function (by typing its name with parentheses), Python runs the code inside it. Functions with parameters Most functions need information to work with. That's what parameters are for: def greet ( name ): print ( f " Hello, { name } ! " ) greet ( " Ramesh " ) # Hello, Ramesh! greet ( " Priya " ) # Hello, Priya! name is a parameter (placeholder). When you call greet("Ramesh") , name becomes "Ramesh" inside the function. Multiple parameters: def add ( x , y ): print ( x + y ) add ( 5 , 3 ) # 8 add ( 10 , 20 ) # 30 Return values A function can calculate something and give the result back to you with return : def add ( x , y ): return x + y result = add ( 5 , 3 ) print ( result ) # 8 The return statement stops the function and sends a value back. The caller can then use that value. def greet ( name ): message = f " Hello, { name } ! " return message greeting = greet ( " Ramesh " ) print ( greeting ) # Hello, Ramesh! A function can return multiple values as a tuple: def get_user_info (): return " Ramesh " , 25 , " Chennai " name , age , city = get_user_info () print ( name , age , city ) # Ramesh 25 Chennai Arguments: Positional vs Keyword There are two ways to pass values to a function: Positional arguments Arguments are matched by position: def describ

本文内容来源于互联网,版权归原作者所有
查看原文