Monday, December 30, 2024

Python tuples Accessing Tuple Items by Index

  1. Definition of Tuples

    • Tuples are used to store multiple items in a single variable.
    • One of the four built-in data types in Python to store collections of data: List, Tuple, Set, and Dictionary.
    • Tuples are ordered and unchangeable collections.
    • Written with round brackets ( ).
  2. Tuple Example

    mytuple = ("apple", "banana", "cherry")
    print(mytuple)
    
  3. Tuple Properties

    • Ordered: Items have a defined order that does not change.
    • Unchangeable: Items cannot be modified, added, or removed once the tuple is created.
    • Allows Duplicates: Tuples can contain duplicate values.
  4. Tuple Indexing

    • Tuple items are indexed starting from [0] for the first item, [1] for the second, and so on.
  5. Example of Duplicate Values

    thistuple = ("apple", "banana", "cherry", "apple", "cherry")
    print(thistuple)
    
  6. Tuple Length

    • Use the len() function to determine the number of items in a tuple.
      Example:
    thistuple = ("apple", "banana", "cherry")
    print(len(thistuple))
    
  7. Tuple With One Item

    • To create a single-item tuple, include a trailing comma:
    thistuple = ("apple",)  # Tuple
    print(type(thistuple))
    thistuple = ("apple")  # Not a tuple
    print(type(thistuple))
    
  8. Tuple Items - Data Types

    • Items in a tuple can be of any data type. Examples:
      • Strings: tuple1 = ("apple", "banana", "cherry")
      • Integers: tuple2 = (1, 5, 7, 9, 3)
      • Booleans: tuple3 = (True, False, False)
    • A tuple can also mix different data types:
      tuple1 = ("abc", 34, True, 40, "male")
      
  9. Tuple Data Type

    • Tuples are objects of the data type <class 'tuple'>. Example:
    mytuple = ("apple", "banana", "cherry")
    print(type(mytuple))
    
  10. The tuple() Constructor

    • Tuples can also be created using the tuple() constructor. Example:
    thistuple = tuple(("apple", "banana", "cherry"))  # Double round brackets
    print(thistuple)
    
  11. Python Collections Overview

    • List: Ordered, changeable, allows duplicates.
    • Tuple: Ordered, unchangeable, allows duplicates.
    • Set: Unordered, unindexed, no duplicates, items are unchangeable (but can be added/removed).
    • Dictionary: Ordered (from Python 3.7 onwards), changeable, no duplicate keys.
  12. Choosing a Collection Type

    • Understanding the properties of collection types is essential for efficiency, meaning retention, and security.
  13. Exercise Example

    • Identify the tuple:
      thistuple = ('apple', 'banana', 'cherry')  # Tuple
      thistuple = ['apple', 'banana', 'cherry']  # List
      thistuple = {'apple', 'banana', 'cherry'}  # Set
      

  1. Accessing Tuple Items by Index

    • Use square brackets [ ] to access tuple items by their index.
    • Example:
      thistuple = ("apple", "banana", "cherry")
      print(thistuple[1])  # Output: banana
      
    • Note: The first item has index 0.
  2. Negative Indexing

    • Negative indexing starts from the end of the tuple.
    • -1 refers to the last item, -2 refers to the second last item, and so on.
    • Example:
      thistuple = ("apple", "banana", "cherry")
      print(thistuple[-1])  # Output: cherry
  3. Range of Indexes

    • Specify a range of indexes to retrieve multiple items.
    • The result is a new tuple with the specified items.
    • Example:
      thistuple = ("apple", "banana", "cherry", "orange", "kiwi", "melon", "mango")
      print(thistuple[2:5])  # Output: ('cherry', 'orange', 'kiwi')
      
    • Note: The range includes the start index but excludes the end index.
  4. Leaving Out Start Value

    • Leaving out the start index begins the range from the first item.
    • Example:
      thistuple = ("apple", "banana", "cherry", "orange", "kiwi", "melon", "mango")
      print(thistuple[:4])  # Output: ('apple', 'banana', 'cherry', 'orange')
      
  5. Leaving Out End Value

    • Leaving out the end index continues the range to the last item.
    • Example:
      thistuple = ("apple", "banana", "cherry", "orange", "kiwi", "melon", "mango")
      print(thistuple[2:])  # Output: ('cherry', 'orange', 'kiwi', 'melon', 'mango')
  6. Range of Negative Indexes

    • Use negative indexes to specify a range starting from the end.
    • Example:
      thistuple = ("apple", "banana", "cherry", "orange", "kiwi", "melon", "mango")
      print(thistuple[-4:-1])  # Output: ('orange', 'kiwi', 'melon')
  7. Check if an Item Exists

    • Use the in keyword to check if a specific item exists in a tuple.
    • Example:
      thistuple = ("apple", "banana", "cherry")
      if "apple" in thistuple:
          print("Yes, 'apple' is in the fruits tuple")
      
  8. Exercise Question

    • What is the index number of the first item?
      Answer: 0.

  9. 💥 WordPress https://computerclassinsrilanka.wordpress.com 💥 Facebook https://web.facebook.com/itclasssrilanka

Here are all the key points summarized from the provided text about updating tuples in Python:

1. Tuples Are Unchangeable (Immutable)

  • Tuples are immutable, meaning you cannot change, add, or remove items once created.
  • However, workarounds exist.

2. Change Tuple Values

  • Tuples themselves cannot be directly modified, but you can:
    1. Convert the tuple into a list.
    2. Modify the list.
    3. Convert the list back into a tuple.

Example:

x = ("apple", "banana", "cherry")
y = list(x)
y[1] = "kiwi"
x = tuple(y)
print(x)  # Output: ('apple', 'kiwi', 'cherry')

3. Add Items to a Tuple

  • Tuples do not have an append() method, but you can add items using two approaches:

    (1) Convert into a List:

    • Convert the tuple into a list, add the new item(s), and convert it back into a tuple.
      Example:
      thistuple = ("apple", "banana", "cherry")
      y = list(thistuple)
      y.append("orange")
      thistuple = tuple(y)
      print(thistuple)  # Output: ('apple', 'banana', 'cherry', 'orange')
      

    (2) Add Tuple to Tuple:

    • Create a new tuple with the additional item(s) and concatenate it to the existing tuple.
      Example:
      thistuple = ("apple", "banana", "cherry")
      y = ("orange",)
      thistuple += y
      print(thistuple)  # Output: ('apple', 'banana', 'cherry', 'orange')
      

    Note: When creating a tuple with one item, always include a comma (,) after the item to identify it as a tuple.


4. Remove Items from a Tuple

  • Direct removal is not possible because tuples are immutable.
  • Workaround: Convert the tuple into a list, remove the item(s), and convert it back into a tuple.

Example:

thistuple = ("apple", "banana", "cherry")
y = list(thistuple)
y.remove("apple")
thistuple = tuple(y)
print(thistuple)  # Output: ('banana', 'cherry')
  • Delete the Entire Tuple:
    • Use the del keyword to delete the entire tuple.
      Example:
      thistuple = ("apple", "banana", "cherry")
      del thistuple
      # print(thistuple) will raise an error because the tuple no longer exists
      

5. Exercise Question

You cannot change the items of a tuple, but there are workarounds. Which of the following suggestions will work?

  • Correct Answer:
    • Convert tuple into a list, change item, convert back into a tuple.
  • Incorrect Answers:
    • Convert tuple into a set, change item, convert back into a tuple.
    • Convert tuple into a dictionary, change item, convert back into a tuple.
----

Here are all the key points summarized from the provided text about unpacking tuples in Python:


1. Packing a Tuple

  • Packing refers to assigning multiple values to a tuple.
    Example:
fruits = ("apple", "banana", "cherry")

2. Unpacking a Tuple

  • Unpacking is extracting the values from a tuple into individual variables.
  • The number of variables must match the number of items in the tuple, unless an asterisk is used.
    Example:
fruits = ("apple", "banana", "cherry")
(green, yellow, red) = fruits

print(green)   # Output: apple
print(yellow)  # Output: banana
print(red)     # Output: cherry

3. Using Asterisk (*)

  • If the number of variables is less than the number of tuple items, an asterisk (*) can be used to collect the remaining values into a list.

Example 1: Assign the remaining values to the last variable:

fruits = ("apple", "banana", "cherry", "strawberry", "raspberry")
(green, yellow, *red) = fruits

print(green)   # Output: apple
print(yellow)  # Output: banana
print(red)     # Output: ['cherry', 'strawberry', 'raspberry']

Example 2: Assign the remaining values to a middle variable:

  • The asterisk can be added to a variable that is not the last one. Python will adjust values to fit the remaining variables.
fruits = ("apple", "mango", "papaya", "pineapple", "cherry")
(green, *tropic, red) = fruits

print(green)   # Output: apple
print(tropic)  # Output: ['mango', 'papaya', 'pineapple']
print(red)     # Output: cherry

4. Exercise Question

Consider the following code:

fruits = ('apple', 'banana', 'cherry')
(x, y, z) = fruits
print(y)

What will be the value of y?

  • Correct Answer: banana

--------------------------

Here are all the key points about looping through tuples in Python:


1. Loop Through a Tuple Using a for Loop

  • You can directly iterate through tuple items using a for loop. Example:
thistuple = ("apple", "banana", "cherry")
for x in thistuple:
    print(x)

2. Loop Through a Tuple Using Index Numbers

  • You can iterate through a tuple by referring to its index numbers.
  • Use the range() and len() functions to create an iterable sequence of index numbers. Example:
thistuple = ("apple", "banana", "cherry")
for i in range(len(thistuple)):
    print(thistuple[i])

3. Loop Through a Tuple Using a while Loop

  • A while loop can also be used to iterate through a tuple.
  • Use the len() function to determine the length of the tuple.
  • Start at index 0 and increase the index by 1 after each iteration. Example:
thistuple = ("apple", "banana", "cherry")
i = 0
while i < len(thistuple):
    print(thistuple[i])
    i += 1

4. Exercise Question

What is the correct syntax for looping through the items of a tuple?

Options:

  1. for x in ('apple', 'banana', 'cherry'):
        print(x)
    
  2. for x in ('apple', 'banana', 'cherry')
        print(x)
    
  3. foreach x in ('apple', 'banana', 'cherry')
        print(x)
    

Correct Answer:
Option 1

for x in ('apple', 'banana', 'cherry'):
    print(x)

---------------------

Here are the key points about joining and multiplying tuples in Python:


1. Join Two Tuples Using the + Operator

  • You can join two or more tuples by using the + operator. Example:
tuple1 = ("a", "b", "c")
tuple2 = (1, 2, 3)

tuple3 = tuple1 + tuple2
print(tuple3)  # Output: ('a', 'b', 'c', 1, 2, 3)

2. Multiply Tuples Using the * Operator

  • You can multiply a tuple to repeat its content a specific number of times using the * operator. Example:
fruits = ("apple", "banana", "cherry")
mytuple = fruits * 2

print(mytuple)  # Output: ('apple', 'banana', 'cherry', 'apple', 'banana', 'cherry')

3. Exercise Question

What is the correct syntax for joining tuple1 and tuple2 into tuple3?

Options:

  1. tuple3 = join(tuple1, tuple2)
  2. tuple3 = tuple1 + tuple2
  3. tuple3 = [tuple1, tuple2]

Correct Answer:
Option 2

tuple3 = tuple1 + tuple2
----------------------------------

Python - Tuple Methods

Python provides two built-in methods for working with tuples:


1. count() Method

  • Description: Returns the number of times a specified value occurs in the tuple.
  • Example:
    thistuple = (1, 2, 3, 2, 2, 4)
    occurrences = thistuple.count(2)
    print(occurrences)  # Output: 3
    

2. index() Method

  • Description: Searches the tuple for a specified value and returns the position (index) of its first occurrence.
  • Example:
    thistuple = (1, 2, 3, 4, 5)
    position = thistuple.index(3)
    print(position)  # Output: 2
    

These methods can be applied directly to any tuple to analyze or retrieve specific data.






Friday, December 27, 2024

Python Lists Creating Properties Items Length Data Types Constructor Collections syntax

  1. Python Lists

    • Lists are used to store multiple items in a single variable.
    • One of the four built-in data types in Python used to store collections of data (the others are Tuple, Set, and Dictionary).
  2. Creating Lists

    • Lists are created using square brackets ([]).
    • Example:
      thislist = ["apple", "banana", "cherry"]
      print(thislist)
      
  3. List Properties

    • Ordered: Items have a defined order, which doesn’t change unless explicitly altered.
    • Changeable: You can add, remove, and modify items after creation.
    • Allow Duplicates: Lists can have items with duplicate values.
  4. List Items

    • Items are indexed: The first item has index [0], the second [1], and so on.
    • Example of duplicate values:
      thislist = ["apple", "banana", "cherry", "apple", "cherry"]
      print(thislist)
      
  5. List Length

    • Use len() to determine the number of items in a list.
    • Example:
      thislist = ["apple", "banana", "cherry"]
      print(len(thislist))
      
  6. List Items - Data Types

    • List items can be of any data type (string, integer, boolean, etc.).
    • A list can even contain mixed data types.
    • Examples:
      list1 = ["apple", "banana", "cherry"]
      list2 = [1, 5, 7, 9, 3]
      list3 = [True, False, False]
      list4 = ["abc", 34, True, 40, "male"]
      
  7. Type of a List

    • From Python’s perspective, lists are objects of the data type 'list'.
    • Example:
      mylist = ["apple", "banana", "cherry"]
      print(type(mylist))
      
  8. The list() Constructor

    • You can create a list using the list() constructor.
    • Example:
      thislist = list(("apple", "banana", "cherry"))  # note the double round brackets
      print(thislist)
      
  9. Python Collections (Arrays)

    • List: Ordered and changeable. Allows duplicates.
    • Tuple: Ordered and unchangeable. Allows duplicates.
    • Set: Unordered, unchangeable*, unindexed. No duplicates.
    • Dictionary: Ordered** and changeable. No duplicates.
    • Notes:
      • Set items are unchangeable, but you can add/remove items.
      • Dictionaries are ordered as of Python 3.7.
  10. Choosing a Collection Type

    • Understanding properties of different types is crucial for efficiency, security, and meaning retention.
  11. Exercise Example

    • What will be the result of the syntax:
      mylist = ['apple', 'banana', 'cherry']
      print(mylist[1])
      
    • Answer: banana.

 Python List Items:

Access Items by Index

  • Indexed access: Use index numbers to access list items. Index starts at 0.
    thislist = ["apple", "banana", "cherry"]
    print(thislist[1])  # Output: "banana"
    
  • Note: The first item has index 0.

Negative Indexing

  • Access from the end: Negative indexing starts at -1 for the last item.
    thislist = ["apple", "banana", "cherry"]
    print(thislist[-1])  # Output: "cherry"
    
  • Examples:
    • -1 = Last item
    • -2 = Second-last item

Range of Indexes

  • Slice a range: Specify start and end indexes for a subset.
    thislist = ["apple", "banana", "cherry", "orange", "kiwi", "melon", "mango"]
    print(thislist[2:5])  # Output: ['cherry', 'orange', 'kiwi']
    
  • Important Notes:
    • Start index is included, end index is not included.
    • Start defaults to 0 if omitted.
    • End defaults to last item if omitted.

Examples:

# From the beginning to "kiwi" (not included)
print(thislist[:4])  # Output: ['apple', 'banana', 'cherry', 'orange']

# From "cherry" to the end
print(thislist[2:])  # Output: ['cherry', 'orange', 'kiwi', 'melon', 'mango']

Range of Negative Indexes

  • Use negative indexes to slice from the end.
    thislist = ["apple", "banana", "cherry", "orange", "kiwi", "melon", "mango"]
    print(thislist[-4:-1])  # Output: ['orange', 'kiwi', 'melon']
    
  • Example: Start at -4 ("orange") and end before -1 ("mango").

Check if Item Exists

  • Use the in keyword to check if an item is in a list.
    thislist = ["apple", "banana", "cherry"]
    if "apple" in thislist:
        print("Yes, 'apple' is in the fruits list")
    

Exercise

What will be the result of the following syntax?

mylist = ['apple', 'banana', 'cherry']
print(mylist[-1])

Answer: cherry.

💥 WordPress https://computerclassinsrilanka.wordpress.com

💥 Facebook https://web.facebook.com/itclasssrilanka

Changing Python List Items

1. Change Item Value

  • To change a specific item, use its index:
    thislist = ["apple", "banana", "cherry"]
    thislist[1] = "blackcurrant"
    print(thislist)  # Output: ['apple', 'blackcurrant', 'cherry']
    

2. Change a Range of Item Values

  • Replace a range with a new list:
    thislist = ["apple", "banana", "cherry", "orange", "kiwi", "mango"]
    thislist[1:3] = ["blackcurrant", "watermelon"]
    print(thislist)  # Output: ['apple', 'blackcurrant', 'watermelon', 'orange', 'kiwi', 'mango']
    

3. Insert More Items Than Replaced

  • If the new list has more items than the replaced range, the extra items are inserted, shifting the remaining elements:
    thislist = ["apple", "banana", "cherry"]
    thislist[1:2] = ["blackcurrant", "watermelon"]
    print(thislist)  # Output: ['apple', 'blackcurrant', 'watermelon', 'cherry']
    

4. Insert Fewer Items Than Replaced

  • If the new list has fewer items than the replaced range, the remaining elements shift accordingly:
    thislist = ["apple", "banana", "cherry"]
    thislist[1:3] = ["watermelon"]
    print(thislist)  # Output: ['apple', 'watermelon']
    

5. Insert Items Without Replacing

  • Use the insert() method to add an item at a specific index without replacing existing items:
    thislist = ["apple", "banana", "cherry"]
    thislist.insert(2, "watermelon")
    print(thislist)  # Output: ['apple', 'banana', 'watermelon', 'cherry']
    

Exercise

What will be the result of the following syntax?

mylist = ['apple', 'banana', 'cherry']
mylist[0] = 'kiwi'
print(mylist[1])

Answer: banana.

Explanation:

  • mylist[0] = 'kiwi' replaces "apple" with "kiwi."
  • The list becomes ['kiwi', 'banana', 'cherry'].
  • Printing mylist[1] outputs the second item, which is "banana".

Key Points on Adding Items to Python Lists

1. Append Items

  • Use the append() method to add an item to the end of the list:
    thislist = ["apple", "banana", "cherry"]
    thislist.append("orange")
    print(thislist)  # Output: ['apple', 'banana', 'cherry', 'orange']
    

2. Insert Items

  • Use the insert() method to add an item at a specified index:
    thislist = ["apple", "banana", "cherry"]
    thislist.insert(1, "orange")
    print(thislist)  # Output: ['apple', 'orange', 'banana', 'cherry']
    

3. Extend List

  • Use the extend() method to append elements from another list:
    thislist = ["apple", "banana", "cherry"]
    tropical = ["mango", "pineapple", "papaya"]
    thislist.extend(tropical)
    print(thislist)  # Output: ['apple', 'banana', 'cherry', 'mango', 'pineapple', 'papaya']
    
  • Note: The elements of the second list are added to the end of the current list.

4. Add Any Iterable

  • The extend() method can also append elements from any iterable object (e.g., tuples, sets, or dictionaries):
    thislist = ["apple", "banana", "cherry"]
    thistuple = ("kiwi", "orange")
    thislist.extend(thistuple)
    print(thislist)  # Output: ['apple', 'banana', 'cherry', 'kiwi', 'orange']
    

Exercise

What will be the result of the following syntax?

mylist = ['apple', 'banana', 'cherry']
mylist.insert(0, 'orange')
print(mylist[1])

Answer: apple.

Explanation:

  • mylist.insert(0, 'orange') inserts "orange" at index 0.
  • The updated list becomes ['orange', 'apple', 'banana', 'cherry'].
  • Printing mylist[1] outputs the second item, which is "apple".


Key Points on Removing Items from Python Lists

1. Remove a Specified Item

  • Use the remove() method to remove the first occurrence of the specified value:
    thislist = ["apple", "banana", "cherry"]
    thislist.remove("banana")
    print(thislist)  # Output: ['apple', 'cherry']
    
  • If there are duplicate items, remove() will only remove the first occurrence:
    thislist = ["apple", "banana", "cherry", "banana", "kiwi"]
    thislist.remove("banana")
    print(thislist)  # Output: ['apple', 'cherry', 'banana', 'kiwi']
    

2. Remove an Item by Index

  • Use the pop() method to remove the item at a specific index:
    thislist = ["apple", "banana", "cherry"]
    thislist.pop(1)
    print(thislist)  # Output: ['apple', 'cherry']
    
  • If no index is specified, pop() will remove the last item:
    thislist = ["apple", "banana", "cherry"]
    thislist.pop()
    print(thislist)  # Output: ['apple', 'banana']
    

3. Remove an Item Using del

  • Use the del keyword to remove an item at a specific index:
    thislist = ["apple", "banana", "cherry"]
    del thislist[0]
    print(thislist)  # Output: ['banana', 'cherry']
    
  • Use del to delete the entire list:
    thislist = ["apple", "banana", "cherry"]
    del thislist
    # List no longer exists
    

4. Clear the Entire List

  • Use the clear() method to empty the list while keeping the list object:
    thislist = ["apple", "banana", "cherry"]
    thislist.clear()
    print(thislist)  # Output: []
    

Exercise

What is a list method for removing list items?

  • Options:
    • pop()
    • push()
    • delete()

Answer: pop().

Explanation:

  • pop() is a built-in method for removing items from a list by index.



Looping Through Python Lists

1. Loop Through a List Using for Loop

  • You can directly loop through the items in a list:
    thislist = ["apple", "banana", "cherry"]
    for x in thislist:
        print(x)
    
    Output:
    apple
    banana
    cherry
    

2. Loop Through the List Using Index Numbers

  • Use range() and len() to loop through items by their index:
    thislist = ["apple", "banana", "cherry"]
    for i in range(len(thislist)):
        print(thislist[i])
    
    Output:
    apple
    banana
    cherry
    
    • Here, the range [0, 1, 2] is created for the list indices.

3. Loop Through a List Using a while Loop

  • Use the while loop with the index and the length of the list:
    thislist = ["apple", "banana", "cherry"]
    i = 0
    while i < len(thislist):
        print(thislist[i])
        i += 1
    
    Output:
    apple
    banana
    cherry
    

4. Loop Through a List Using List Comprehension

  • Use list comprehension for a more concise looping syntax:
    thislist = ["apple", "banana", "cherry"]
    [print(x) for x in thislist]
    
    Output:
    apple
    banana
    cherry
    

Exercise

What is the correct syntax for looping through the items of a list?

Options:

  1. for x in ['apple', 'banana', 'cherry']:
        print(x)
    ``` ✅
    
  2. for x in ['apple', 'banana', 'cherry']
        print(x)
    ``` ❌ (Missing colon `:`)
    
  3. foreach x in ['apple', 'banana', 'cherry']
        print(x)
    ``` ❌ (Python does not use `foreach`)
    

Answer: Option 1.




Python List Comprehension

1. What is List Comprehension?

  • Definition: A shorter syntax to create a new list based on values from an existing list.
  • Example (Traditional Approach):
    fruits = ["apple", "banana", "cherry", "kiwi", "mango"]
    newlist = []
    
    for x in fruits:
        if "a" in x:
            newlist.append(x)
    
    print(newlist)
    
    Output:
    ['apple', 'banana', 'mango']
    
  • Example (Using List Comprehension):
    fruits = ["apple", "banana", "cherry", "kiwi", "mango"]
    newlist = [x for x in fruits if "a" in x]
    print(newlist)
    
    Output:
    ['apple', 'banana', 'mango']
    

2. Syntax

newlist = [expression for item in iterable if condition == True]
  • expression: The item or manipulated version of the item to include in the new list.
  • iterable: The original list, range, tuple, etc., being iterated.
  • condition: (Optional) Filters the items to be included in the new list.

3. Condition

  • Filters the items that evaluate to True.

  • Example: Exclude "apple":

    newlist = [x for x in fruits if x != "apple"]
    print(newlist)
    

    Output:

    ['banana', 'cherry', 'kiwi', 'mango']
    
  • Condition is Optional: Without a condition:

    newlist = [x for x in fruits]
    print(newlist)
    

    Output:

    ['apple', 'banana', 'cherry', 'kiwi', 'mango']
    

4. Iterable

  • Any iterable object can be used, e.g., lists, tuples, sets, etc.

  • Example: Use range():

    newlist = [x for x in range(10)]
    print(newlist)
    

    Output:

    [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
    
  • Example with a condition (Numbers less than 5):

    newlist = [x for x in range(10) if x < 5]
    print(newlist)
    

    Output:

    [0, 1, 2, 3, 4]
    

5. Expression

  • Manipulate each item in the iteration.

  • Example: Convert to uppercase:

    newlist = [x.upper() for x in fruits]
    print(newlist)
    

    Output:

    ['APPLE', 'BANANA', 'CHERRY', 'KIWI', 'MANGO']
    
  • Example: Set all values to "hello":

    newlist = ['hello' for x in fruits]
    print(newlist)
    

    Output:

    ['hello', 'hello', 'hello', 'hello', 'hello']
    
  • Example: Use condition in the expression (Replace "banana" with "orange"):

    newlist = [x if x != "banana" else "orange" for x in fruits]
    print(newlist)
    

    Output:

    ['apple', 'orange', 'cherry', 'kiwi', 'mango']
    

Exercise

Question:
Given the code:

fruits = ['apple', 'banana', 'cherry']
newlist = [x for x in fruits if x == 'banana']

What will be the value of newlist?

Options:

  1. ['apple', 'cherry']
  2. ['banana']
  3. True

Answer: ['banana']


****************

Key Points on Python - Sorting Lists

1. Sort List Alphanumerically (Ascending by Default)

  • The sort() method sorts lists alphabetically or numerically in ascending order.

  • Example (Alphabetical Sort):

    thislist = ["orange", "mango", "kiwi", "pineapple", "banana"]
    thislist.sort()
    print(thislist)
    

    Output:

    ['banana', 'kiwi', 'mango', 'orange', 'pineapple']
    
  • Example (Numerical Sort):

    thislist = [100, 50, 65, 82, 23]
    thislist.sort()
    print(thislist)
    

    Output:

    [23, 50, 65, 82, 100]
    

2. Sort in Descending Order

  • Use the keyword argument reverse=True to sort in descending order.

  • Example (Descending Alphabetical Sort):

    thislist = ["orange", "mango", "kiwi", "pineapple", "banana"]
    thislist.sort(reverse=True)
    print(thislist)
    

    Output:

    ['pineapple', 'orange', 'mango', 'kiwi', 'banana']
    
  • Example (Descending Numerical Sort):

    thislist = [100, 50, 65, 82, 23]
    thislist.sort(reverse=True)
    print(thislist)
    

    Output:

    [100, 82, 65, 50, 23]
    

3. Customize the Sort Function

  • Use the key=function argument to define a custom sort function.
  • Example (Sort by Distance to 50):
    def myfunc(n):
        return abs(n - 50)
    
    thislist = [100, 50, 65, 82, 23]
    thislist.sort(key=myfunc)
    print(thislist)
    
    Output:
    [50, 65, 23, 82, 100]
    

4. Case Sensitivity in Sorting

  • By default, sort() is case-sensitive, placing uppercase letters before lowercase ones.
  • Example (Case-Sensitive Sort):
    thislist = ["banana", "Orange", "Kiwi", "cherry"]
    thislist.sort()
    print(thislist)
    
    Output:
    ['Kiwi', 'Orange', 'banana', 'cherry']
    

5. Case-Insensitive Sorting

  • Use the key=str.lower argument to perform a case-insensitive sort.
  • Example:
    thislist = ["banana", "Orange", "Kiwi", "cherry"]
    thislist.sort(key=str.lower)
    print(thislist)
    
    Output:
    ['banana', 'cherry', 'Kiwi', 'Orange']
    

6. Reverse the Order

  • The reverse() method reverses the current order of list items, regardless of their values.
  • Example:
    thislist = ["banana", "Orange", "Kiwi", "cherry"]
    thislist.reverse()
    print(thislist)
    
    Output:
    ['cherry', 'Kiwi', 'Orange', 'banana']
    

Exercise

Question:
What is the correct syntax for sorting a list?

Options:

  1. mylist.orderby(0)
  2. mylist.order()
  3. mylist.sort()

Answer:
mylist.sort()

*****************

Key Points on Python - Copying Lists

1. Problem with Direct Assignment

  • Direct assignment (list2 = list1) does not create a new list; instead, list2 becomes a reference to list1.
  • Changes made to list1 will automatically reflect in list2.

2. Using the copy() Method

  • The copy() method creates a shallow copy of the list, independent of the original list.
  • Example:
    thislist = ["apple", "banana", "cherry"]
    mylist = thislist.copy()
    print(mylist)
    
    Output:
    ['apple', 'banana', 'cherry']
    

3. Using the list() Method

  • The list() method can also create a new list from an existing one.
  • Example:
    thislist = ["apple", "banana", "cherry"]
    mylist = list(thislist)
    print(mylist)
    
    Output:
    ['apple', 'banana', 'cherry']
    

4. Using the Slice (:) Operator

  • The slice operator ([:]) creates a copy of the entire list.
  • Example:
    thislist = ["apple", "banana", "cherry"]
    mylist = thislist[:]
    print(mylist)
    
    Output:
    ['apple', 'banana', 'cherry']
    

Exercise

Question:
What is the correct syntax for making a copy of a list?

Options:

  1. list2 = list1
  2. list2 = list1.copy()
  3. list2.copy(list1)

Answer:
list2 = list1.copy()



Here are all the points related to joining lists in Python:

  1. Using the + Operator: The easiest way to join two lists is by using the + operator.

    Example:

    list1 = ["a", "b", "c"]
    list2 = [1, 2, 3]
    list3 = list1 + list2
    print(list3)
    

    Output:

    ['a', 'b', 'c', 1, 2, 3]
    
  2. Using the append() Method: Another way to join two lists is by appending each item from list2 to list1 one by one.

    Example:

    list1 = ["a", "b", "c"]
    list2 = [1, 2, 3]
    for x in list2:
        list1.append(x)
    print(list1)
    

    Output:

    ['a', 'b', 'c', 1, 2, 3]
    
  3. Using the extend() Method: You can also use the extend() method, which adds elements from one list to another list.

    Example:

    list1 = ["a", "b", "c"]
    list2 = [1, 2, 3]
    list1.extend(list2)
    print(list1)
    

    Output:

    ['a', 'b', 'c', 1, 2, 3]
    

Exercise Question:
What is a correct syntax for joining list1 and list2 into list3?

Options:

  • list3 = join(list1, list2)
  • list3 = list1 + list2
  • list3 = [list1, list2]

Correct answer:

  • list3 = list1 + list2




Here are all the points related to Python list methods:

List Methods in Python:

  1. append()
    Adds an element at the end of the list.
    Example:

    list1.append(4)
    
  2. clear()
    Removes all the elements from the list.
    Example:

    list1.clear()
    
  3. copy()
    Returns a copy of the list.
    Example:

    list2 = list1.copy()
    
  4. count()
    Returns the number of elements with the specified value.
    Example:

    list1.count(2)
    
  5. extend()
    Adds the elements of a list (or any iterable) to the end of the current list.
    Example:

    list1.extend([4, 5, 6])
    
  6. index()
    Returns the index of the first element with the specified value.
    Example:

    list1.index(3)
    
  7. insert()
    Adds an element at the specified position.
    Example:

    list1.insert(1, 'a')
    
  8. pop()
    Removes the element at the specified position and returns it.
    Example:

    list1.pop(2)
    
  9. remove()
    Removes the item with the specified value.
    Example:

    list1.remove(3)
    
  10. reverse()
    Reverses the order of the list.
    Example:

    list1.reverse()
    
  11. sort()
    Sorts the list.
    Example:

    list1.sort()
    








Thursday, December 26, 2024

What are the 7 Python operators Logical Arithmetic Assignment Bitwise Comparison Membership Online Classes Project Assignments Guide Help

General Overview

  • Definition: Operators perform operations on variables and values.
  • Example: print(10 + 5)

Categories of Python Operators

  1. Arithmetic operators
  2. Assignment operators
  3. Comparison operators
  4. Logical operators
  5. Identity operators
  6. Membership operators
  7. Bitwise operators

Details of Each Operator Category

1. Python Arithmetic Operators

  • Operators and their meanings:
    • + (Addition)
    • - (Subtraction)
    • * (Multiplication)
    • / (Division)
    • % (Modulus)
    • ** (Exponentiation)
    • // (Floor division)

2. Python Assignment Operators

  • Assign values to variables:
    • =
    • +=
    • -=
    • *=
    • /=
    • %=
    • //=
    • **=
    • &=
    • |=
    • ^=
    • >>=
    • <<=
    • := (Walrus operator)

3. Python Comparison Operators

  • Compare two values:
    • == (Equal)
    • != (Not equal)
    • > (Greater than)
    • < (Less than)
    • >= (Greater than or equal to)
    • <= (Less than or equal to)

4. Python Logical Operators

  • Combine conditional statements:
    • and
    • or
    • not

5. Python Identity Operators

  • Compare object identity (memory location):
    • is
    • is not

6. Python Membership Operators

  • Test for presence in a sequence:
    • in
    • not in

7. Python Bitwise Operators

  • Compare binary numbers:
    • & (AND)
    • | (OR)
    • ^ (XOR)
    • ~ (NOT)
    • << (Left shift)
    • >> (Right shift)

Python Operator Precedence

  • Defines the order of evaluation in expressions.
  • Precedence order (highest to lowest):
    1. () Parentheses
    2. ** Exponentiation
    3. +x, -x, ~x Unary operations
    4. *, /, //, % Multiplication, division, floor division, modulus
    5. +, - Addition and subtraction
    6. <<, >> Bitwise shifts
    7. & Bitwise AND
    8. ^ Bitwise XOR
    9. | Bitwise OR
    10. Comparisons, identity, and membership operators
    11. not Logical NOT
    12. and Logical AND
    13. or Logical OR

Examples

  1. Parentheses have the highest precedence:

    print((6 + 3) - (6 + 3))  
    
  2. Multiplication is evaluated before addition:

    print(100 + 5 * 3)  
    
  3. Operators with the same precedence are evaluated left to right:

    print(5 + 4 - 7 + 3)  
    

Exercise

What will be the result of the following syntax?

x = 5  
x += 3  
print(x)  

Answer: 8.


💥 YouTube https://www.youtube.com/channel/UCJojbxGV0sfU1QPWhRxx4-A

💥 Blog https://localedxcelcambridgeictcomputerclass.blogspot.com/

💥 WordPress https://computerclassinsrilanka.wordpress.com

💥 Facebook https://web.facebook.com/itclasssrilanka

💥 Wix https://itclasssl.wixsite.com/icttraining

💥 Web https://itclasssl.github.io/eTeacher/

💥 Medium https://medium.com/@itclasssl

💥 Quora https://www.quora.com/profile/BIT-UCSC-UoM-Final-Year-Student-Project-Guide

💥 mystrikingly https://bit-ucsc-uom-final-year-project-ideas-help-guide-php-class.mystrikingly.com/

💥 https://elakiri.com/threads/bit-ucsc-uom-php-mysql-project-guidance-and-individual-classes-in-colombo.1627048/

💥 https://bitbscucscuomfinalprojectclasslk.weebly.com/

💥 https://www.tiktok.com/@onlinelearningitclassso1



Tuesday, December 24, 2024

Python Strings Definition Quotes Assigning String Slicing Methods Escape Characters Format Concatenation

💥 WordPress https://computerclassinsrilanka.wordpress.com

💥 Facebook https://web.facebook.com/itclasssrilanka

Points on Python Strings

  1. Definition of Strings

    • Strings in Python are surrounded by either single (') or double (") quotation marks.
      Example:
      print("Hello")
      print('Hello')
      
  2. Quotes Inside Strings

    • Quotes inside strings can be used as long as they don't match the outer quotes.
      Example:
      print("It's alright")
      print("He is called 'Johnny'")
      print('He is called "Johnny"')
      
  3. Assigning Strings to Variables

    • Strings can be assigned to variables using the equal sign (=).
      Example:
      a = "Hello"
      print(a)
      
  4. Multiline Strings

    • Multiline strings are created using triple quotes (""" or ''').
      Example:
      a = """Lorem ipsum dolor sit amet,
      consectetur adipiscing elit."""
      print(a)
      
      Or:
      a = '''Lorem ipsum dolor sit amet,
      consectetur adipiscing elit.'''
      print(a)
      
  5. Strings as Arrays

    • Strings are arrays of bytes representing Unicode characters.
    • Access elements using square brackets ([]).
      Example:
      a = "Hello, World!"
      print(a[1])  # Outputs 'e'
      
  6. Looping Through a String

    • Strings can be iterated using a for loop.
      Example:
      for x in "banana":
          print(x)
      
  7. String Length

    • Use the len() function to get the length of a string.
      Example:
      a = "Hello, World!"
      print(len(a))  # Outputs 13
      
  8. Check String Presence

    • Use the in keyword to check if a substring is present.
      Example:
      txt = "The best things in life are free!"
      print("free" in txt)  # Outputs True
      
    • Use in with an if statement:
      if "free" in txt:
          print("Yes, 'free' is present.")
      
  9. Check String Absence

    • Use the not in keyword to check if a substring is not present.
      Example:
      txt = "The best things in life are free!"
      print("expensive" not in txt)  # Outputs True
      
    • Use not in with an if statement:
      if "expensive" not in txt:
          print("No, 'expensive' is NOT present.")
      
  10. Exercise

    • Question:
      x = 'Welcome'
      print(x[3])
      
    • Answer: The output will be:
      c (since indexing starts at 0).
  1. Slicing Syntax

    • Strings can be sliced using the syntax [start:end].
    • The slicing returns characters from the start index up to, but not including, the end index.
      Example:
      b = "Hello, World!"
      print(b[2:5])  # Outputs 'llo'
      
    • Note: Indexing starts at 0.
  2. Slice From the Start

    • Omitting the start index makes the slice begin from the start of the string.
      Example:
      b = "Hello, World!"
      print(b[:5])  # Outputs 'Hello'
      
  3. Slice To the End

    • Omitting the end index makes the slice go until the end of the string.
      Example:
      b = "Hello, World!"
      print(b[2:])  # Outputs 'llo, World!'
      
  4. Negative Indexing

    • Negative indices count from the end of the string.
    • Example:
      b = "Hello, World!"
      print(b[-5:-2])  # Outputs 'orl'
      
      • Here, -5 corresponds to "o" in "World!" and -2 excludes "d" in "World!".
  5. Exercise

    • Question:
      x = 'Welcome'
      print(x[3:5])
      
    • Answer: The output will be:
      co (characters from index 3 to 4, as index 5 is not included).

Points on Python - Modify Strings

  1. Built-in Methods

    • Python provides built-in methods to modify strings.
  2. Convert to Upper Case

    • The upper() method converts all characters in the string to upper case.
      Example:
      a = "Hello, World!"
      print(a.upper())  # Outputs: "HELLO, WORLD!"
      
  3. Convert to Lower Case

    • The lower() method converts all characters in the string to lower case.
      Example:
      a = "Hello, World!"
      print(a.lower())  # Outputs: "hello, world!"
      
  4. Remove Whitespace

    • The strip() method removes whitespace from the beginning and the end of the string.
      Example:
      a = " Hello, World! "
      print(a.strip())  # Outputs: "Hello, World!"
      
  5. Replace Substring

    • The replace() method replaces a specified substring with another substring.
      Example:
      a = "Hello, World!"
      print(a.replace("H", "J"))  # Outputs: "Jello, World!"
      
  6. Split String

    • The split() method splits the string into substrings based on a specified separator and returns them as a list.
      Example:
      a = "Hello, World!"
      print(a.split(","))  # Outputs: ['Hello', ' World!']
      
  7. String Methods Reference

    • Python provides many more string methods. Refer to Python's String Methods Reference for a complete list.
  8. Exercise

    • Question:
      What is the correct syntax to print a string in upper case letters?
      • 'Welcome'.upper()
      • 'Welcome'.toUpper()
      • 'Welcome'.toUpperCase()
    • Correct Answer:
      'Welcome'.upper()


String Concatenation

  1. String Concatenation

    • Concatenation is the process of combining two or more strings.
  2. Using the + Operator

    • The + operator can be used to concatenate strings.
      Example:
      a = "Hello"
      b = "World"
      c = a + b
      print(c)  # Outputs: "HelloWorld"
      
  3. Adding a Space Between Strings

    • To include a space between concatenated strings, add " " in between.
      Example:
      a = "Hello"
      b = "World"
      c = a + " " + b
      print(c)  # Outputs: "Hello World"
      
  4. Exercise

    • Question:
      What is the correct syntax to merge variable x and y into variable z?
      • z = x, y
      • z = x = y
      • z = x + y
    • Correct Answer:
      z = x + y

Format Strings

  1. String Format Problem

    • Strings and numbers cannot be combined directly using +.
      Example:
      age = 36
      txt = "My name is John, I am " + age  # ❌ Results in an error
      print(txt)
      
  2. Solutions for Combining Strings and Numbers

    • Use f-strings or the format() method.
  3. F-Strings

    • Introduced in Python 3.6 and is the preferred method for string formatting.
    • Add an f before the string and use {} as placeholders.
      Example:
      age = 36
      txt = f"My name is John, I am {age}"
      print(txt)  # Outputs: "My name is John, I am 36"
      
  4. Placeholders and Modifiers

    • Placeholders in f-strings can include variables, operations, and modifiers.
  5. Placeholders for Variables

    • Example:
      price = 59
      txt = f"The price is {price} dollars"
      print(txt)  # Outputs: "The price is 59 dollars"
      
  6. Using Modifiers in Placeholders

    • A modifier formats the value inside a placeholder.
    • Example with .2f (fixed-point number with 2 decimals):
      price = 59
      txt = f"The price is {price:.2f} dollars"
      print(txt)  # Outputs: "The price is 59.00 dollars"
      
  7. Performing Math Operations in Placeholders

    • Example:
      txt = f"The price is {20 * 59} dollars"
      print(txt)  # Outputs: "The price is 1180 dollars"
      
  8. Exercise

    • Question: If x = 9, what is the correct syntax to print "The price is 9.00 dollars"?
      • print(f'The price is {x:.2f} dollars')
      • print(f'The price is {x:2} dollars')
      • print(f'The price is {x:format(2)} dollars')
    • Correct Answer:
      print(f'The price is {x:.2f} dollars')  # Outputs: "The price is 9.00 dollars"
      

***

Escape Characters in Python

  1. Purpose of Escape Characters

    • Escape characters allow the insertion of characters that are illegal or problematic in a string.
    • They are written as a backslash \ followed by the character to insert.
  2. Example of Illegal Character

    • Using double quotes inside a string surrounded by double quotes results in an error:
      txt = "We are the so-called "Vikings" from the north."  # ❌ Error
      
  3. Fixing the Problem with Escape Characters

    • Use \" to include double quotes in a string:
      txt = "We are the so-called \"Vikings\" from the north."
      print(txt)  # Outputs: We are the so-called "Vikings" from the north.
      
  4. List of Escape Characters

    • \': Inserts a single quote.
      Example:

      txt = 'It\'s a sunny day.'
      print(txt)  # Outputs: It's a sunny day.
      
    • \\: Inserts a backslash.
      Example:

      txt = "This is a backslash: \\"
      print(txt)  # Outputs: This is a backslash: \
      
    • \n: Inserts a new line.
      Example:

      txt = "Hello\nWorld!"
      print(txt)  
      # Outputs:
      # Hello
      # World!
      
    • \r: Inserts a carriage return.
      Example:

      txt = "Hello\rWorld"
      print(txt)  # Outputs: World (carriage return overwrites the line)
      
    • \t: Inserts a tab.
      Example:

      txt = "Hello\tWorld"
      print(txt)  # Outputs: Hello    World
      
    • \b: Inserts a backspace.
      Example:

      txt = "Hello\bWorld"
      print(txt)  # Outputs: HellWorld (removes 'o')
      
    • \f: Inserts a form feed.
      Example:

      txt = "Hello\fWorld"
      print(txt)  # Outputs: HelloWorld (new page indicator)
      
    • \ooo: Inserts a character based on its octal value.
      Example:

      txt = "\110\145\154\154\157"  # Octal for 'Hello'
      print(txt)  # Outputs: Hello
      
    • \xhh: Inserts a character based on its hex value.
      Example:

      txt = "\x48\x65\x6C\x6C\x6F"  # Hex for 'Hello'
      print(txt)  # Outputs: Hello
      

 String Methods

  1. General Note

    • All string methods return new values and do not change the original string.
  2. String Methods and Their Descriptions

Method Description
capitalize() Converts the first character to upper case.
casefold() Converts string into lower case (more aggressive than lower()).
center() Returns a centered string.
count() Returns the number of times a specified value occurs in a string.
encode() Returns an encoded version of the string.
endswith() Returns True if the string ends with the specified value.
expandtabs() Sets the tab size of the string.
find() Searches for a specified value and returns the position where it was found.
format() Formats specified values in a string.
format_map() Formats specified values in a string using a dictionary.
index() Searches for a specified value and returns its position (raises an error if not found).
isalnum() Returns True if all characters in the string are alphanumeric.
isalpha() Returns True if all characters in the string are alphabetic.
isascii() Returns True if all characters in the string are ASCII characters.
isdecimal() Returns True if all characters in the string are decimals.
isdigit() Returns True if all characters in the string are digits.
isidentifier() Returns True if the string is a valid identifier.
islower() Returns True if all characters in the string are lower case.
isnumeric() Returns True if all characters in the string are numeric.
isprintable() Returns True if all characters in the string are printable.
isspace() Returns True if all characters in the string are whitespaces.
istitle() Returns True if the string follows title case rules.
isupper() Returns True if all characters in the string are upper case.
join() Joins the elements of an iterable to the string.
ljust() Returns a left-justified version of the string.
lower() Converts a string to lower case.
lstrip() Returns a left-trimmed version of the string.
maketrans() Returns a translation table for use in string translation.
partition() Splits the string into three parts: before, the separator, and after.
replace() Replaces a specified value with another value in the string.
rfind() Searches for a specified value and returns the last position of where it was found.
rindex() Searches for a specified value and returns its last position (raises an error if not found).
rjust() Returns a right-justified version of the string.
rpartition() Splits the string into three parts from the right: before, the separator, and after.
rsplit() Splits the string at the specified separator from the right and returns a list.
rstrip() Returns a right-trimmed version of the string.
split() Splits the string at the specified separator and returns a list.
splitlines() Splits the string at line breaks and returns a list.
startswith() Returns True if the string starts with the specified value.
strip() Returns a trimmed version of the string (removes spaces from both ends).
swapcase() Swaps case: lower case becomes upper case, and vice versa.
title() Converts the first character of each word to upper case.
translate() Returns a translated string using a translation table.
upper() Converts a string to upper case.
zfill() Pads the string with zeros on the left until it reaches the specified length.










Monday, December 23, 2024

Python Data Types Built-in Data Types Numbers Casting String Booleans | Online ICT Technology Classes English Tamil Medium GCE OL AL

Python Data Types

1. Built-in Data Types

  • Data types are essential as they define the kind of operations variables can perform.
  • Categories of Python Data Types:
    • Text Type: str
    • Numeric Types: int, float, complex
    • Sequence Types: list, tuple, range
    • Mapping Type: dict
    • Set Types: set, frozenset
    • Boolean Type: bool
    • Binary Types: bytes, bytearray, memoryview
    • None Type: NoneType

2. Getting the Data Type

  • Use the type() function to determine the type of any object.
    x = 5
    print(type(x))  # Output: <class 'int'>
    

3. Setting the Data Type

  • Data type is assigned based on the value assigned to a variable.

    Examples:

    • x = "Hello World"str
    • x = 20int
    • x = 20.5float
    • x = 1jcomplex
    • x = ["apple", "banana", "cherry"]list
    • x = ("apple", "banana", "cherry")tuple
    • x = range(6)range
    • x = {"name": "John", "age": 36}dict
    • x = {"apple", "banana", "cherry"}set
    • x = frozenset({"apple", "banana", "cherry"})frozenset
    • x = Truebool
    • x = b"Hello"bytes
    • x = bytearray(5)bytearray
    • x = memoryview(bytes(5))memoryview
    • x = NoneNoneType

4. Setting Specific Data Types

  • Use constructor functions to specify the data type.

    Examples:

    • x = str("Hello World")str
    • x = int(20)int
    • x = float(20.5)float
    • x = complex(1j)complex
    • x = list(("apple", "banana", "cherry"))list
    • x = tuple(("apple", "banana", "cherry"))tuple
    • x = range(6)range
    • x = dict(name="John", age=36)dict
    • x = set(("apple", "banana", "cherry"))set
    • x = frozenset(("apple", "banana", "cherry"))frozenset
    • x = bool(5)bool
    • x = bytes(5)bytes
    • x = bytearray(5)bytearray
    • x = memoryview(bytes(5))memoryview

5. Quiz/Exercise

  • Question: If x = 5, what is the correct syntax for printing the data type of x?
    • Correct Answer: print(type(x))

💥 YouTube https://www.youtube.com/channel/UCJojbxGV0sfU1QPWhRxx4-A

💥 Blog https://localedxcelcambridgeictcomputerclass.blogspot.com/

Python Numbers

  1. Three Numeric Types in Python:

    • int: Integer (whole numbers, positive or negative, without decimals, unlimited length).
    • float: Floating-point number (numbers with decimals or in scientific notation).
    • complex: Complex number (with a real and imaginary part, written as a + bj).
  2. Creating Numeric Variables:

    x = 1    # int
    y = 2.8  # float
    z = 1j   # complex
    
  3. Verifying the Type of an Object: Use the type() function.

    print(type(x))
    print(type(y))
    print(type(z))
    

Details of Numeric Types

1. Int (Integer):

  • Whole numbers without decimals.
  • Positive, negative, or zero.
  • Unlimited length.
x = 1
y = 35656222554887711
z = -3255522

print(type(x))
print(type(y))
print(type(z))

2. Float (Floating-Point Numbers):

  • Numbers containing one or more decimals.
  • Can also represent scientific numbers using e for powers of 10.
x = 1.10
y = 1.0
z = -35.59

x = 35e3
y = 12E4
z = -87.7e100

print(type(x))
print(type(y))
print(type(z))

3. Complex Numbers:

  • Written with a "j" to represent the imaginary part.
x = 3+5j
y = 5j
z = -5j

print(type(x))
print(type(y))
print(type(z))

Type Conversion

  • Convert between numeric types using int(), float(), and complex().
    x = 1    # int
    y = 2.8  # float
    z = 1j   # complex
    
    a = float(x)  # Convert int to float
    b = int(y)    # Convert float to int
    c = complex(x)  # Convert int to complex
    
    print(a)
    print(b)
    print(c)
    
    print(type(a))
    print(type(b))
    print(type(c))
    
  • Note: Complex numbers cannot be converted to other numeric types.

Random Numbers

  • Python does not have a built-in random() function but includes a random module.
  • Use the random.randrange(start, stop) function to generate a random number.
    import random
    
    print(random.randrange(1, 10))
    

Quiz/Exercise:

Question: Which is NOT a legal numeric data type in Python?

  • int
  • long (Correct Answer: long is not valid; it was part of Python 2.)
  • float

 ðŸ’¥ WordPress https://computerclassinsrilanka.wordpress.com

💥 Facebook https://web.facebook.com/itclasssrilanka


Here are the key points extracted from the content:


Python Casting

1. Purpose of Casting

  • Casting is used to specify the data type of a variable explicitly.
  • Python, being an object-oriented language, uses classes to define data types.

2. Constructor Functions for Casting

  • int()
    Constructs an integer:

    • From an integer literal.
    • From a float literal (removing decimals).
    • From a string literal (if the string represents a whole number).
    • Examples:
      x = int(1)      # x will be 1
      y = int(2.8)    # y will be 2 (decimals are removed)
      z = int("3")    # z will be 3
      
  • float()
    Constructs a floating-point number:

    • From an integer literal.
    • From a float literal.
    • From a string literal (if the string represents a number).
    • Examples:
      x = float(1)       # x will be 1.0
      y = float(2.8)     # y will be 2.8
      z = float("3")     # z will be 3.0
      w = float("4.2")   # w will be 4.2
      
  • str()
    Constructs a string:

    • From strings.
    • From integers.
    • From floats.
    • Examples:
      x = str("s1")  # x will be 's1'
      y = str(2)     # y will be '2'
      z = str(3.0)   # z will be '3.0'
      

3. Quiz/Exercise

  • Question: What will be the result of the following code?
    print(int(35.88))
    
    • Correct Answer: 35
      (The decimals are truncated when casting a float to an integer.)

💥 Wix https://itclasssl.wixsite.com/icttraining

💥 Web https://itclasssl.github.io/eTeacher/

Here are all the key points from the content about Python Booleans:


Python Booleans

1. Boolean Representation

  • Booleans represent one of two values: True or False.

2. Boolean Values

  • Any expression in Python can be evaluated to True or False.
  • Comparison Examples:
    print(10 > 9)   # True
    print(10 == 9)  # False
    print(10 < 9)   # False
    

3. Booleans in Conditional Statements

  • When used in an if statement, Python evaluates the condition and returns True or False.
    • Example:
      a = 200
      b = 33
      
      if b > a:
        print("b is greater than a")
      else:
        print("b is not greater than a")
      

4. The bool() Function

  • Purpose: Evaluates any value and returns True or False.
  • Examples:
    print(bool("Hello"))  # True
    print(bool(15))       # True
    
    x = "Hello"
    y = 15
    print(bool(x))        # True
    print(bool(y))        # True
    

5. Most Values are True

  • Non-empty strings, numbers (non-zero), and collections (non-empty lists, tuples, sets, dictionaries) evaluate to True.
    • Examples:
      print(bool("abc"))                      # True
      print(bool(123))                        # True
      print(bool(["apple", "cherry", "banana"]))  # True
      

6. Some Values are False

  • Values that evaluate to False include:
    • Empty values: (), [], {}, "".
    • The number 0.
    • None.
    • The value False.
    • Examples:
      print(bool(False))  # False
      print(bool(None))   # False
      print(bool(0))      # False
      print(bool(""))     # False
      print(bool(()))     # False
      print(bool([]))     # False
      print(bool({}))     # False
      

7. Special Case: Custom Objects

  • Objects with a __len__ method that returns 0 or False evaluate to False.
    • Example:
      class myclass():
        def __len__(self):
          return 0
      
      myobj = myclass()
      print(bool(myobj))  # False
      

8. Functions Returning a Boolean

  • Functions can return Boolean values and can be used in conditions.
    • Example:
      def myFunction():
        return True
      
      print(myFunction())  # True
      
      if myFunction():
        print("YES!")
      else:
        print("NO!")
      

9. Built-in Boolean Functions

  • Python includes functions like isinstance() to check data types, which return True or False.
    • Example:
      x = 200
      print(isinstance(x, int))  # True
      

10. Quiz/Exercise

  • Question: What will be the result of the following syntax?
    print(5 > 3)
    
    • Correct Answer: True