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





 

Sunday, December 22, 2024

Python Variables Definition Creation Casting Getting the Type of a Variable Case Sensitivity Output Local Global Variable Inside a Function Numbers

Definition of Variables



  1. Variables are Containers
    • Used for storing data values.

Creating Variables

  1. No Declaration Command

    • Python does not require a specific command to declare variables.
    • A variable is created when you assign a value to it.
  2. Examples:

    • x = 5
      y = "John"
      print(x)
      print(y)
      
  3. Dynamic Typing

    • Variables do not need to have a fixed type and can change types after being set.
    • Example:
      x = 4       # x is of type int
      x = "Sally" # x is now of type str
      print(x)
      

Casting Variables

  1. Specifying Data Type
    • Use casting to define a variable's data type explicitly.
    • Example:
      x = str(3)    # x will be '3'
      y = int(3)    # y will be 3
      z = float(3)  # z will be 3.0
      

Getting the Type of a Variable

  1. Using type() Function
    • Check the data type of a variable.
    • Example:
      x = 5
      y = "John"
      print(type(x))  # Output: <class 'int'>
      print(type(y))  # Output: <class 'str'>
      

Strings and Quotes

  1. Single or Double Quotes
    • String variables can use either single (') or double (") quotes interchangeably.
    • Example:
      x = "John"
      y = 'John'
      

Case Sensitivity

  1. Variable Names are Case-Sensitive
    • Variables with different cases are treated as distinct variables.
    • Example:
      a = 4
      A = "Sally"
      # A will not overwrite a
      

Exercise

  • Question: What is a correct way to declare a Python variable?
    • Correct Answer: x = 5

Definition of Variable Names

  1. Short or Descriptive
    • Variable names can be short (e.g., x, y) or descriptive (e.g., age, carname, total_volume).

Rules for Python Variable Names

  1. Starting Character

    • Must start with a letter or an underscore (_).
  2. Cannot Start with a Number

    • A variable name cannot begin with a digit.
  3. Allowed Characters

    • Can only contain alphanumeric characters (A-Z, a-z, 0-9) and underscores (_).
  4. Case Sensitivity

    • Variable names are case-sensitive. Examples:
      • age, Age, and AGE are treated as different variables.
  5. Python Keywords

    • Variable names cannot be any of Python's reserved keywords.

Examples of Legal and Illegal Variable Names

Legal Variable Names:

myvar = "John"
my_var = "John"
_my_var = "John"
myVar = "John"
MYVAR = "John"
myvar2 = "John"

Illegal Variable Names:

2myvar = "John"  # Cannot start with a number
my-var = "John"  # Cannot contain special characters like "-"
my var = "John"  # Cannot contain spaces

Reminder

  • Case Sensitivity:
    • Variable names like myvar, MyVar, and MYVAR are distinct due to Python's case sensitivity.


Many Values to Multiple Variables

  1. Assigning Multiple Values in One Line

    • Python allows assigning multiple values to multiple variables in one line.
    • Example:
      x, y, z = "Orange", "Banana", "Cherry"
      print(x)  # Orange
      print(y)  # Banana
      print(z)  # Cherry
      
  2. Matching Variables and Values

    • The number of variables must match the number of values; otherwise, an error will occur.

One Value to Multiple Variables

  1. Assigning the Same Value to Multiple Variables
    • A single value can be assigned to multiple variables in one line.
    • Example:
      x = y = z = "Orange"
      print(x)  # Orange
      print(y)  # Orange
      print(z)  # Orange
      

Unpack a Collection

  1. Extracting Values from Collections

    • Python allows extracting values from a collection (like a list or tuple) into variables, called unpacking.
    • Example:
      fruits = ["apple", "banana", "cherry"]
      x, y, z = fruits
      print(x)  # apple
      print(y)  # banana
      print(z)  # cherry
      
  2. Learn More About Unpacking

    • You can learn more about unpacking in the Unpack Tuples Chapter.

Exercise

Question:
What is the correct syntax to assign the value 'Hello World' to 3 variables in one statement?

Options:

  1. x, y, z = 'Hello World'
  2. x = y = z = 'Hello World'
  3. x|y|z = 'Hello World'


Output Variables

  1. Using print() to Output Variables

    • The print() function can be used to display the value of a variable.
    • Example:
      x = "Python is awesome"
      print(x)
      
  2. Outputting Multiple Variables

    • Multiple variables can be output using commas within the print() function.
    • Example:
      x = "Python"
      y = "is"
      z = "awesome"
      print(x, y, z)  # Python is awesome
      
  3. Using the + Operator to Output Variables

    • The + operator can be used to concatenate strings.
    • Example:
      x = "Python "
      y = "is "
      z = "awesome"
      print(x + y + z)  # Python is awesome
      
    • Note: If there are no spaces within the string variables, the result will appear as a single concatenated string (e.g., "Pythonisawesome").

Working with Numbers

  1. Mathematical Operation with +

    • The + operator adds numbers when used with numeric variables.
    • Example:
      x = 5
      y = 10
      print(x + y)  # 15
      
  2. Error When Combining Strings and Numbers

    • Combining a string and a number with the + operator will result in a TypeError.
    • Example:
      x = 5
      y = "John"
      print(x + y)  # Error
      
  3. Using Commas for Different Data Types

    • Using commas in the print() function allows you to combine different data types.
    • Example:
      x = 5
      y = "John"
      print(x, y)  # 5 John
      

Exercise

Question:
Consider the following code:

print('Hello', 'World')

What will be the printed result?

Options:

  1. Hello, World
  2. Hello World
  3. HelloWorld

Global Variables


Definition of Global Variables

  1. Global Variables are created outside of a function and can be used both inside and outside of functions.

Using Global Variables Inside Functions

  1. A global variable can be accessed directly within a function.
    • Example:
      x = "awesome"
      
      def myfunc():
          print("Python is " + x)
      
      myfunc()  # Output: Python is awesome
      

Local Variables with the Same Name as Global Variables

  1. If a variable with the same name as a global variable is defined inside a function, it becomes a local variable and does not affect the global variable.
    • Example:
      x = "awesome"
      
      def myfunc():
          x = "fantastic"  # Local variable
          print("Python is " + x)
      
      myfunc()              # Output: Python is fantastic
      print("Python is " + x)  # Output: Python is awesome
      

The global Keyword

  1. Definition: The global keyword is used to define or modify a global variable inside a function.

Creating a Global Variable Inside a Function

  1. Using global within a function creates a global variable that can be accessed outside of the function.
    • Example:
      def myfunc():
          global x
          x = "fantastic"
      
      myfunc()
      print("Python is " + x)  # Output: Python is fantastic
      

Modifying a Global Variable Inside a Function

  1. To change the value of an existing global variable inside a function, use the global keyword.
    • Example:
      x = "awesome"
      
      def myfunc():
          global x
          x = "fantastic"
      
      myfunc()
      print("Python is " + x)  # Output: Python is fantastic
      

💥 WordPress https://computerclassinsrilanka.wordpress.com
💥 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/


Python script to develop a simple Student Exam Result Sheet App

If you're a beginner and want a simple way to handle subjects without using functions or loops, you can write the script like this:

Simplified Script:

# Welcome message
print("Welcome to the Student Exam Result Sheet App!")

# Input student details
name = input("Enter Student's Name: ").strip()
student_class = input("Enter Student's Class: ").strip()

# Input marks for each subject
math = float(input("Enter marks for Math: "))
science = float(input("Enter marks for Science: "))
history = float(input("Enter marks for History: "))
geography = float(input("Enter marks for Geography: "))
it = float(input("Enter marks for IT: "))

# Calculate total marks
total_marks = math + science + history + geography + it

# Print the result sheet
print("\n---- Student Exam Result Sheet ----")
print(f"Name: {name}")
print(f"Class: {student_class}")
print("\nSubjects and Marks:")
print(f"Math: {math}")
print(f"Science: {science}")
print(f"History: {history}")
print(f"Geography: {geography}")
print(f"IT: {it}")
print("\nTotal Marks:", total_marks)
print("-----------------------------------")

How It Works:

  1. Input Student Details:

    • Asks for the student's name and class.
  2. Input Marks for Each Subject:

    • Collects marks for "Math," "Science," "History," "Geography," and "IT" directly without using a loop.
  3. Calculate Total Marks:

    • Adds the marks of all subjects using simple arithmetic.
  4. Display the Result Sheet:

    • Prints the student details, each subject's marks, and the total marks in a readable format.

Example Input/Output:

Input:

Enter Student's Name: John Doe
Enter Student's Class: Grade 6
Enter marks for Math: 85
Enter marks for Science: 90
Enter marks for History: 75
Enter marks for Geography: 80
Enter marks for IT: 88

Output:

---- Student Exam Result Sheet ----
Name: John Doe
Class: Grade 6

Subjects and Marks:
Math: 85.0
Science: 90.0
History: 75.0
Geography: 80.0
IT: 88.0

Total Marks: 418.0
-----------------------------------

Why It’s Beginner-Friendly:

  1. No Functions or Loops: The script directly asks for each subject's marks and calculates the total.
  2. Step-by-Step: Each part of the script is written in a straightforward, sequential manner.
  3. Easily Expandable: To add more subjects, just add another input line and include it in the total.

Let me know if you'd like further simplifications or explanations!


========

Here's a Python script to develop a simple Student Exam Result Sheet App. The script will:

  1. Take input for the student's name and class.
  2. Take input for marks in each subject (Math, Science, History, Geography, IT).
  3. Calculate the total marks.
  4. Print the result sheet with the student's details, marks for each subject, and total marks.

Here's the complete Python script:

# Student Exam Result Sheet App

def get_student_details():
    """Get student's name and class"""
    name = input("Enter Student's Name: ").strip()
    student_class = input("Enter Student's Class: ").strip()
    return name, student_class

def get_subject_marks():
    """Get marks for all subjects"""
    subjects = ["Math", "Science", "History", "Geography", "IT"]
    marks = {}
    
    print("\nEnter marks for the following subjects:")
    for subject in subjects:
        while True:
            try:
                mark = float(input(f"{subject}: "))
                if 0 <= mark <= 100:  # Validating mark range
                    marks[subject] = mark
                    break
                else:
                    print("Marks should be between 0 and 100. Please try again.")
            except ValueError:
                print("Invalid input! Please enter a valid number.")
    return marks

def calculate_total_marks(marks):
    """Calculate the total marks"""
    return sum(marks.values())

def display_result_sheet(name, student_class, marks, total_marks):
    """Display the result sheet"""
    print("\n---- Student Exam Result Sheet ----")
    print(f"Name: {name}")
    print(f"Class: {student_class}")
    print("\nSubjects and Marks:")
    for subject, mark in marks.items():
        print(f"{subject}: {mark:.2f}")
    print("\nTotal Marks:", total_marks)
    print("-----------------------------------")

def main():
    """Main function to run the app"""
    print("Welcome to the Student Exam Result Sheet App!")
    name, student_class = get_student_details()
    marks = get_subject_marks()
    total_marks = calculate_total_marks(marks)
    display_result_sheet(name, student_class, marks, total_marks)

if __name__ == "__main__":
    main()

How to Use the Script

  1. Copy and paste the script into a Python IDE or a text editor (e.g., VS Code, PyCharm, or a simple text editor).
  2. Save the file with a .py extension, e.g., student_result_sheet.py.
  3. Run the script in your terminal or Python environment.
  4. Follow the prompts to enter:
    • The student's name and class.
    • Marks for each subject (input between 0 and 100).
  5. The script will display the result sheet.

Features

  • Input validation ensures marks are between 0 and 100.
  • Clear formatting for the result sheet.
  • Easy-to-modify script (e.g., add more subjects).

You can extend this script by saving the results to a file (CSV or JSON) or using a database for persistent storage. Let me know if you'd like to add any advanced features!