Notice: This page requires JavaScript to function properly.
Please enable JavaScript in your browser settings or update your browser.
学ぶ Membership Operators | Conditional Statements
Introduction to Python
セクション 3.  4
single

single

bookMembership Operators

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

This chapter covers Python membership operators, which let you check if an item or substring exists within data structures like strings, lists, or tuples. Membership operators are essential for searching and filtering data.

Membership operators in Python, in and not in, let you check if a value exists within an iterable object. An iterable object is any data structure you can loop over, such as a string, list, or tuple.

  • Use in to check if an item is present in an iterable;
  • Use not in to check if an item is absent from an iterable.

Both operators always return a boolean value: True if the condition is met, False if not.

For example, you can check if a substring appears inside a string, or if an element is in a list or tuple. This is a simple, direct way to test for membership in Python.

123
itemName = "Strawberries" in_name = "Straw" in itemName print("Is 'Straw' in 'Strawberries'?", in_name)
copy

Example Application

Imagine you're managing the product descriptions or categories in your grocery store system. You might receive a long string of product details, and you need to quickly check for specific keywords to categorize or highlight products based on customer preferences or promotional activities:

12345678910
# Product description from supplier product_description = "Fresh organic milk from local farms, pasteurized and homogenized." # Check if the "organic" and "local" keywords are in the product description is_organic = "organic" in product_description is_local = "local" in product_description # Print the presence of these keywords to decide on marketing strategies print("Is the product organic?", is_organic) print("Is the product locally sourced?", is_local)
copy
タスク

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

You are managing data for a new product that has just been added to a grocery store system. Your task is to analyze the product information using membership operators.

  • Use membership operators (in) on the description string:

    • Check if the substring 'raw' exists in description. Store the result in contains_raw.
    • Check if the substring 'Imported' exists in description. Store the result in contains_Imported.
  • Print the results in the following format:

"Contains 'raw':" <contains_raw>
"Contains 'Imported':" <contains_Imported>

Python is case sensitive, so 'imported' and 'Imported' are considered different strings.

解答

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

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

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

セクション 3.  4
single

single

AIに質問する

expand

AIに質問する

ChatGPT

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

some-alt