Notice: This page requires JavaScript to function properly.
Please enable JavaScript in your browser settings or update your browser.
学ぶ Arbitrary Positional Arguments in Python | Section
/
Python Functions
セクション 1.  12
single

single

bookArbitrary Positional Arguments in Python

メニューを表示するにはスワイプしてください

You already know positional and optional arguments. But when a function may receive many inputs or you don't know them in advance, you can use arbitrary positional arguments. They allow a function to accept any number of values.

Note
Note

Each argument can be any data structure (list, dict, etc.). Arbitrary arguments let you pass as many such objects as needed.

To define arbitrary positional arguments, place an asterisk * before the parameter name. Example:

12345678
# Define function with arbitrary positional arguments named values def calculate_sum(*values): return sum(values) # Test the function using different number of arguments print(calculate_sum(1, 2, 3)) print(calculate_sum(1, 2, 3, 4)) print(calculate_sum(1, 2, 3, 4, 5))
copy

Here, *values collects all passed positional arguments into a tuple. Inside the function, you use the variable name without *. The result is correct regardless of how many arguments are provided.

Note
Note

Although any name works, the common and readable form is *args.

1234567891011121314
def example_function(*args): print(type(args)) print(args) for arg in args: print(arg) print("Call without arguments:") example_function() print("\nCall with one argument:") example_function(1) print("\nCall with multiple arguments:") example_function(1, 2, 3, 'hello', [4, 5, 6])
copy

As shown:

  • No arguments → args is ();
  • One argument → (1,);
  • Multiple arguments → all values appear in a tuple, e.g., (1, 2, 3, 'hello', [4, 5, 6]).

*args behaves like any other tuple, giving you full flexibility when handling many inputs.

タスク

スワイプしてコーディングを開始

Implement a calculate_total function that calculates the total price of items in a cart, applying discounts based on the total amount.

  • Use arbitrary positional arguments named prices in the calculate_total function.
  • If no arguments are provided, return "Your cart is empty.".
  • Apply a 20% discount if the total is $200 or more.
  • Apply a 10% discount if the total is $100 or more.

解答

Switch to desktop実践的な練習のためにデスクトップに切り替える下記のオプションのいずれかを利用して、現在の場所から続行する
すべて明確でしたか?

どのように改善できますか?

フィードバックありがとうございます!

セクション 1.  12
single

single

AIに質問する

expand

AIに質問する

ChatGPT

何でも質問するか、提案された質問の1つを試してチャットを始めてください

some-alt