Location via proxy:   [ UP ]  
[Report a bug]   [Manage cookies]                

Python Programming

Download as pptx, pdf, or txt
Download as pptx, pdf, or txt
You are on page 1of 142

PYTHON

PROGRAMMING
Python Installation

• If you find that you do not have Python installed on


your computer, then you can download it for free from
the following website: https://www.python.org/
• Use Google Colab
• Python Hello World Program
• Using python IDE
• Using text editor and run it in command prompt
Python - Interpreter

• This tutorial will teach you How Python Interpreter


Works in interactive and scripted mode. Python code is
executed by one statement at a time method. Python
interpreter has two components. The translator checks
the statement for syntax. If found correct, it generates
an intermediate byte code. There is a Python virtual
machine which then converts the byte code in native
binary and executes it. The following diagram illustrates
the mechanism:
• Python Interpreter - Interactive Mode
• When launched from a command line terminal without
any additional options, a Python prompt >>> appears
and the Python interpreter works on the principle
of REPL (Read, Evaluate, Print, Loop). Each command
entered in front of the Python prompt is read,
translated and executed. A typical interactive session is
as follows.
• >>> price = 100
• >>> qty = 5
• >>> total = price*qty
• >>> total
• 500
• >>> print ("Total = ", total)
• Total = 500
• To close the interactive session, enter the end-of-line
character (ctrl+D for Linux and ctrl+Z for Windows).
• You may also type quit() in front of the Python prompt
and press Enter to return to the OS prompt.
Python Interpreter - Scripting Mode

• Instead of entering and obtaining the result of one


instruction at a time as in the interactive environment,
it is possible to save a set of instructions in a text file,
make sure that it has .py extension, and use the name
as the command line parameter for Python command.
• Save the following lines as prog.py, with the use of any
text editor such as vim on Linux or Notepad on
Windows.
• print ("My first program")
• price = 100
• qty = 5
• total = price*qty
• print ("Total = ", total)
C:\Users\Acer>python prog.py My first program Total = 500

• When we execute above program on a Windows


machine, it will produce following result:
• C:\Users\Acer>python prog.py
• My first program
• Total = 500
• Note that even though Python executes the entire script
in one go, but internally it is still executed in line by line
fashion.
• In case of any compiler-based language such as Java,
the source code is not converted in byte code unless the
entire code is error-free. In Python, on the other hand,
statements are executed until first occurrence of error
is encountered.
• Note the misspelt variable prive instead of price. Try to
execute the script again as before −
• C:\Users\Acer>python prog.py
• My first program
• Traceback (most recent call last):
• File "C:\Python311\prog.py", line 4, in <module>
• total = prive*qty
• ^^^^^
• NameError: name 'prive' is not defined. Did you mean: 'price'?
• Note that the statements before the erroneous
statement are executed and then the error message
appears. Thus it is now clear that Python script is
executed in interpreted manner.
Python Comments
• Comments can be used to explain Python code.
• Comments can be used to make the code more
readable.
• Comments can be used to prevent execution when
testing code.
• Creating a Comment
• Comments starts with a #, and Python will ignore them:
• #This is a comment
print("Hello, World!")
• Comments can be placed at the end of a line, and
Python will ignore the rest of the line:
• print("Hello, World!") #This is a comment
• A comment does not have to be text that explains the
code, it can also be used to prevent Python from
executing code:
• #print("Hello, World!")
print("Cheers, Mate!")
• Multiline Comments
• Python does not really have a syntax for multiline comments.

• To add a multiline comment you could insert a # for each line:


• #This is a comment
• #written in
• #more than just one line
• print("Hello, World!")
• Since Python will ignore string literals that are not
assigned to a variable, you can add a multiline string
(triple quotes) in your code, and place your comment
inside it:
• """
• This is a comment
• written in
• more than just one line
• """
• print("Hello, World!")
PYTHON VARIABLES
• Variables
• Variables are containers for storing data values.
• Creating Variables
• Python has no command for declaring a variable.
• A variable is created the moment you first assign a
value to it.
•x = 5
y = "John"
print(x)
print(y)
• Variables do not need to be declared with any
particular type, and can even change type after they
have been set.
•x = 4 # x is of type int
x = "Sally" # x is now of type str
print(x)
• Casting
• If you want to specify the data type of a variable, this
can be done with casting.
• x = str(3) # x will be '3'
y = int(3) # y will be 3
z = float(3) # z will be 3.0
• Get the Type
• You can get the data type of a variable with the type() function.
•x = 5
y = "John"
print(type(x))
print(type(y))
Single or Double Quotes?

• String variables can be declared either by using single


or double quotes:
• x = "John"
# is the same as
x = 'John'
• Case-Sensitive
• Variable names are case-sensitive.
• Example
• This will create two variables:
•a = 4
A = "Sally"
#A will not overwrite a
• Python - Variable Names
• Variable Names
• A variable can have a short name (like x and y) or a more descriptive
name (age, carname, total_volume).
• Rules for Python variables:A variable name must start with a letter or
the underscore character
• A variable name cannot start with a number
• A variable name can only contain alpha-numeric characters and
underscores (A-z, 0-9, and _ )
• Variable names are case-sensitive (age, Age and AGE are three
different variables)
• A variable name cannot be any of the python keywords
• Python has a set of keywords that are reserved words
that cannot be used as variable names, function names,
or any other identifiers:
• Legal variable names:
• myvar = "John"
my_var = "John"
_my_var = "John"
myVar = "John"
MYVAR = "John"
myvar2 = "John"
• Example
• Illegal variable names:
• 2myvar = "John"
my-var = "John"
my var = "John"
• Multi Words Variable Names
• Variable names with more than one word can be
difficult to read.
• There are several techniques you can use to make them
more readable:
• Camel Case
• Each word, except the first, starts with a capital letter:
• myVariableName = "John“
• Pascal Case
• Each word starts with a capital letter:
• MyVariableName = "John"
• Snake Case
• Each word is separated by an underscore character:
• my_variable_name = "John“
• Python Variables - Assign Multiple Values
• Many Values to Multiple Variables
• Python allows you to assign values to multiple variables
in one line:
• Example
• x, y, z = "Orange", "Banana", "Cherry"
print(x)
print(y)
print(z)
• Note: Make sure the number of variables matches the
number of values, or else you will get an error.
• One Value to Multiple Variables
• And you can assign the same value to multiple variables
in one line:
• Example
• x = y = z = "Orange"
print(x)
print(y)
print(z)
Python - Output Variables

• Output Variables
• The Python print() function is often used to output variables.
• x = "Python is awesome"
print(x)
• In the print() function, you output multiple variables, separated by a
comma:
• x = "Python"
• y = "is"
• z = "awesome"
• print(x, y, z)
• You can also use the + operator to output multiple variables:
• x = "Python "
y = "is "
z = "awesome"
print(x + y + z)
• Notice the space character after "Python " and "is ", without them the
result would be "Pythonisawesome".
• For numbers, the + character works as a mathematical operator:
•x = 5
y = 10
print(x + y)
• In the print() function, when you try to combine a string and a
number with the + operator, Python will give you an error:
•x = 5
y = "John"
print(x + y)
• The best way to output multiple variables in the print() function is to
separate them with commas, which even support different data
types:
•x = 5
y = "John"
print(x, y)
Built-in Data Types

• In programming, data type is an important concept.


• Variables can store data of different types, and different
types can do different things.
• Python has the following data types built-in by default,
in these categories:
• 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
You can get the data type of any object by using the type() function:

• Getting the Data Type


• Example 1:
• x = "Hello World"
• #display x:
• print(x)
• #display the data type of x:
• print(type(x))
• Example 2:
• x = 20
• #display x:
• print(x)
• #display the data type of x:
• print(type(x))
• Example 3:
• x = 20.5
• #display x:
• print(x)
• #display the data type of x:
• print(type(x))
Python Numbers
• There are three numeric types in Python:
• Int
• Float &
• Complex
• Example
• x=1
• y = 2.8
• z = 1j
• print(type(x))
• print(type(y))
• print(type(z))
• Example
• x=1
• y = 35656222554887711
• z = -3255522
• print(type(x))
• print(type(y))
• print(type(z))
Specify a Variable Type

• Casting in python is therefore done using constructor


functions:
• int() - constructs an integer number from an integer
literal, a float literal (by removing all decimals), or a string
literal (providing the string represents a whole number)
• float() - constructs a float number from an integer
literal, a float literal or a string literal (providing the string
represents a float or an integer)
• str() - constructs a string from a wide variety of data
types, including strings, integer literals and float literals
• x = int(1)
• y = int(2.8)
• z = int("3")
• print(x)
• print(y)
• print(z)
• x = float(1)
• y = float(2.8)
• z = float("3")
• w = float("4.2")
• print(x)
• print(y)
• print(z)
• print(w)
• x = str("s1")
• y = str(2)
• z = str(3.0)
• print(x)
• print(y)
• print(z)
• Strings
• Strings in python are surrounded by either single quotation marks, or
double quotation marks.

• 'hello' is the same as "hello".

• You can display a string literal with the print() function:


• #You can use double or single quotes:

• print("Hello")
• print('Hello')
• a = "Hello"
• print(a)
• Multiline Strings
• a = """Lorem ipsum dolor sit amet,
• consectetur adipiscing elit,
• sed do eiusmod tempor incididunt
• ut labore et dolore magna aliqua."""
• print(a)
• Or three single quotes:
• a = '''Lorem ipsum dolor sit amet,
• consectetur adipiscing elit,
• sed do eiusmod tempor incididunt
• ut labore et dolore magna aliqua.'''
• print(a)
• String Concatenation
• a = "Hello"
• b = "World"
•c=a+b
• print(c)
• a = "Hello"
• b = "World"
• c=a+""+b
• print(c)
Python Booleans

• Booleans represent one of two values: True or False


• Boolean Values
• In programming you often need to know if an expression is True or False.

• You can evaluate any expression in Python, and get one of two answers,
True or False.

• When you compare two values, the expression is evaluated and Python
returns the Boolean answer:
• print(10 > 9)
• print(10 == 9)
• print(10 < 9)
PYTHON OPERATORS
• Python Arithmetic Operators
• x=5
• y=3
• print(x + y)

• x=5
• y=3

• print(x - y)
• x=5
• y=3
• print(x * y)

• x = 12
• y=3
• print(x / y)
• x=5
• y=2
• print(x % y)

• x=2
• y=5
• print(x ** y) #same as 2*2*2*2*2
• x = 15
• y=2
• print(x // y)
• #the floor division // rounds the result down to the nearest whole
number
• x=5
• print(x)

• x=5
• x += 3
• print(x)

• x=5
• x -= 3
• print(x)
• x=5
• x -= 3
• print(x)

• x=5
• x *= 3
• print(x)
• x=5
• x *= 3
• print(x)

• x=5
• x /= 3
• print(x)
• x=5
• x%=3
• print(x)

• x=5
• x//=3
• print(x)

• x=5
• x **= 3
• print(x)
• x=5
• y=3
• print(x == y)
• # returns False because 5 is not equal to 3

• x=5
• y=3
• print(x != y)

• # returns True because 5 is not equal to 3


• x=5
• y=3
• print(x > y)
• # returns True because 5 is greater than 3

• x=5
• y=3
• print(x < y)
• # returns False because 5 is not less than 3
• x=5
• y=3
• print(x < y)
• # returns False because 5 is not less than 3

• x=5
• y=3
• print(x >= y)
• # returns True because five is greater, or equal, to 3
• x=5
• y=3
• print(x <= y)
• # returns False because 5 is neither less than or equal to 3
• x=5
• print(x > 3 and x < 10)
• # returns True because 5 is greater than 3 AND 5 is less than 10

• x=5
• print(x > 3 or x < 4)
• # returns True because one of the conditions are true (5 is greater
than 3, but 5 is not less than 4)
• x=5
• print(not(x > 3 and x < 10))
• # returns False because not is used to reverse the result
Operator Precedence
• Operator Precedence
• Operator precedence describes the order in which
operations are performed.
• print((6 + 3) - (6 + 3))
• """
• Parenthesis have the highest precedence, and need to be evaluated
first.
• The calculation above reads 9 - 9 = 0
• """
• print(100 + 5 * 3)
• """
• Multiplication has higher precedence than addition, and needs to be
evaluated first.
• The calculation above reads 100 + 15 = 115
• “””
• If two operators have the same precedence, the
expression is evaluated from left to right.
• Example
• Addition + and subtraction - has the same precedence, and therefor
we evaluate the expression from left to right:
• print(5 + 4 - 7 + 3)
• """
• Additions and subtractions have the same precedence, and we need
to calculate from left to right.
• The calculation above reads:
• 5+4=9
• 9-7=2
• 2+3=5
• """
Membership IN Operator
• Membership in operator explanation with example
• The in operator in Python is used to test whether a value exists in a
sequence (such as a string, list, or tuple).
• It returns True if the value is found, and False otherwise.
• # Using the 'in' operator with a list
• fruits = ['apple', 'banana', 'orange']

• # Check if 'banana' is in the list


• result = 'banana' in fruits
• print(result) # Output: True

• # Check if 'grape' is in the list


• result = 'grape' in fruits
• print(result) # Output: False
• In this example, the in operator is used to check if the values 'banana'
and 'grape' are present in the fruits list.
• The first check returns True because 'banana' is in the list, while the
second check returns False because 'grape' is not in the list.
• You can also use the in operator with strings to check if a substring
exists in the given string:
• # Using the 'in' operator with a string
• sentence = "Hello, how are you?"

• # Check if 'how' is in the string


• result = 'how' in sentence
• print(result) # Output: True

• # Check if 'world' is in the string


• result = 'world' in sentence
• print(result) # Output: False
• In this case, the in operator is used to check if the substrings 'how'
and 'world' are present in the sentence string.
• The in operator is versatile and can be used with various data types to
test membership within sequences.
• The not in operator is the negation of the in operator in Python.
• It is used to test whether a value does not exist in a sequence.
• It returns True if the value is not found, and False if it is found.
• # Using the 'not in' operator with a list
• fruits = ['apple', 'banana', 'orange']

• # Check if 'grape' is not in the list


• result = 'grape' not in fruits
• print(result) # Output: True

• # Check if 'banana' is not in the list


• result = 'banana' not in fruits
• print(result) # Output: False
• In this example, the not in operator is used to check if the values
'grape' and 'banana' are not present in the fruits list.
• The first check returns True because 'grape' is not in the list, while the
second check returns False because 'banana' is in the list.
• Similarly, you can use the not in operator with strings to check if a substring does not exist in
the given string:
• # Using the 'not in' operator with a string
• sentence = "Hello, how are you?"

• # Check if 'world' is not in the string


• result = 'world' not in sentence
• print(result) # Output: True

• # Check if 'how' is not in the string


• result = 'how' not in sentence
• print(result) # Output: False
• In this case, the not in operator is used to check if the substrings
'world' and 'how' are not present in the sentence string.
• The not in operator complements the behavior of the in operator,
providing a convenient way to test for the absence of a value in a
sequence.
PYTHON-Lists
• Lists are used to store multiple items in a single
variable.
• Lists are one of 4 built-in data types in Python used to
store collections of data, the other 3 are Tuple, Set,
and Dictionary, all with different qualities and usage.
• Lists are created using square brackets:
• thislist = ["apple", "banana", "cherry"]
print(thislist) #List Items
• List items are ordered, changeable, and allow
duplicate values.

• List items are indexed, the first item has index


[0], the second item has index [1] etc.
• Changeable
• The list is changeable, meaning that we can change,
add, and remove items in a list after it has been
created.
• Allow Duplicates
• thislist =
["apple", "banana", "cherry", "apple", "cherry"]
print(thislist)
• List Length
• To determine how many items a list has, use the len() function:
• Example
• Print the number of items in the list:
• thislist = ["apple", "banana", "cherry"]
print(len(thislist))
• List Items - Data Types
• List items can be of any data type:
• Example
• String, int and boolean data types:
• list1 = ["apple", "banana", "cherry"]
list2 = [1, 5, 7, 9, 3]
list3 = [True, False, False]
• A list can contain different data types:
• type()
• From Python's perspective, lists are defined as objects
with the data type 'list':
• Example
• What is the data type of a list?
• mylist = ["apple", "banana", "cherry"]
print(type(mylist))
• Access Items
• List items are indexed and you can access them by
referring to the index number:
• thislist = ["apple", "banana", "cherry"]
print(thislist[1])
• Note: The first item has index 0.
• Negative Indexing
• Negative indexing means start from the end
• -1 refers to the last item, -2 refers to the second last item etc.
• Range of Indexes
• You can specify a range of indexes by specifying where
to start and where to end the range.
• When specifying a range, the return value will be a new
list with the specified items.
• Example
• Return the third, fourth, and fifth item:
• thislist =
["apple", "banana", "cherry", "orange", "kiwi", "me
lon", "mango"]
print(thislist[2:5])
• Note: The search will start at index 2 (included) and
end at index 5 (not included).
• By leaving out the start value, the range will start at the
first item:
• thislist =
["apple", "banana", "cherry", "orange", "kiwi", "me
lon", "mango"]
print(thislist[:4])
• Range of Negative Indexes
• Specify negative indexes if you want to start the search
from the end of the list:
• Example
• This example returns the items from "orange" (-4) to,
but NOT including "mango" (-1):
• thislist =
["apple", "banana", "cherry", "orange", "kiwi", "me
lon", "mango"]
print(thislist[-4:-1])
• Check if Item Exists
• To determine if a specified ite
• m is present in a list use the in keyword:
• Example
• Check if "apple" is present in the list:
• thislist = ["apple", "banana", "cherry"]
if "apple" in thislist:
print("Yes, 'apple' is in the fruits list")
Insert Items
• To insert a new list item, without replacing any of
the existing values, we can use the insert()
method.

• The insert() method inserts an item at the


specified index:
• thislist = ["apple", "banana", "cherry"]
thislist.insert(2, "watermelon")
print(thislist)
• Python - Add List Items
• Append Items
• To add an item to the end of the list, use
the append() method:
• thislist = ["apple", "banana", "cherry"]
thislist.append("orange")
print(thislist)
• Insert Items
• To insert a list item at a specified index, use the insert() method.

• The insert() method inserts an item at the specified index:


• thislist = ["apple", "banana", "cherry"]
thislist.insert(1, "orange")
print(thislist)
• Extend List
• To append elements from another list to the current list, use the
extend() method.
• thislist = ["apple", "banana", "cherry"]
tropical = ["mango", "pineapple", "papaya"]
thislist.extend(tropical)
print(thislist)
• Python - Remove List Items
• Remove Specified Item
• The remove() method removes the specified item.
• thislist = ["apple", "banana", "cherry"]
thislist.remove("banana")
print(thislist)
• If there are more than one item with the specified
value, the remove() method removes the first
occurance:
• The list() Constructor
• It is also possible to use the list() constructor when
creating a new list.
• Using the list() constructor to make a List:
• thislist = list(("apple", "banana", "cherry")) # note the double round-
brackets
• print(thislist)
Check item exists
• To determine if a specified item is present in a list use the in keyword:
• Example
• Check if "apple" is present in the list:
• thislist = ["apple", "banana", "cherry"]
if "apple" in thislist:
print("Yes, 'apple' is in the fruits list")
Python - Change List Items

• Change Item Value


• To change the value of a specific item, refer to the
index number:
• thislist = ["apple", "banana", "cherry"]
thislist[1] = "blackcurrant"
print(thislist)
• Change a Range of Item Values
• To change the value of items within a specific range,
define a list with the new values, and refer to the range
of index numbers where you want to insert the new
values:
• Example
• Change the values "banana" and "cherry" with the
values "blackcurrant" and "watermelon":
• thislist =
["apple", "banana", "cherry", "orange", "kiwi", "ma
ngo"]
thislist[1:3] = ["blackcurrant", "watermelon"]
print(thislist)
• If you insert more items than you replace, the new
items will be inserted where you specified, and the
remaining items will move accordingly:
• thislist = ["apple", "banana", "cherry"]
thislist[1:2] = ["blackcurrant", "watermelon"]
print(thislist)
• Insert Items
• To insert a new list item, without replacing any of the existing values,
we can use the insert() method.
• The insert() method inserts an item at the specified index:
• Example
• Insert "watermelon" as the third item:
• thislist = ["apple", "banana", "cherry"]
thislist.insert(2, "watermelon")
print(thislist)
• Python - Add List Items
• Append Items
• To add an item to the end of the list, use
the append() method:
• ExampleGet your own Python Server
• Using the append() method to append an item:
Append Items
To add an item to the end of the list, use the append() method:

• ExampleGet your own Python Server


• Using the append() method to append an item:
• thislist = ["apple", "banana", "cherry"]
thislist.append("orange")
print(thislist)
• Insert Items
• To insert a list item at a specified index, use the insert() method.
• The insert() method inserts an item at the specified index:
• Example
• Insert an item as the second position:
• thislist = ["apple", "banana", "cherry"]
thislist.insert(1, "orange")
print(thislist)
• Extend List
• To append elements from another list to the current list, use the
extend() method.
• Example
• Add the elements of tropical to thislist:
• thislist = ["apple", "banana", "cherry"]
tropical = ["mango", "pineapple", "papaya"]
thislist.extend(tropical)
print(thislist)
• Python - Remove List Items
• Remove Specified Item
• The remove() method removes the specified item.
• thislist = ["apple", "banana", "cherry"]
• thislist.remove("banana")
• print(thislist)
• If there are more than one item with the specified value, the
remove() method removes the first occurance:
• Example
• Remove the first occurance of "banana":
• thislist = ["apple", "banana", "cherry", "banana", "kiwi"]
• thislist.remove("banana")
• print(thislist)
• Remove Specified Index
• The pop() method removes the specified index.
• thislist = ["apple", "banana", "cherry"]
thislist.pop(1)
print(thislist)
• If you do not specify the index, the pop() method removes the last
item.

• thislist = ["apple", "banana", "cherry"]


thislist.pop()
print(thislist)
• The del keyword also removes the specified index:
• Example
• Remove the first item:
• thislist = ["apple", "banana", "cherry"]
• del thislist[0]
• print(thislist)
• The del keyword can also delete the list completely.
• Example
• Delete the entire list:
• thislist = ["apple", "banana", "cherry"]
del thislist
• Clear the List
• The clear() method empties the list.

• The list still remains, but it has no content.

• Example
• Clear the list content:

• thislist = ["apple", "banana", "cherry"]


• thislist.clear()
• print(thislist)
PYTHON TUPLES
• mytuple = ("apple", "banana", "cherry")
• Tuple
• Tuples are used to store multiple items in a single
variable.
• Tuple is one of 4 built-in data types in Python used to
store collections of data, the other 3 are List, Set, and
Dictionary, all with different qualities and usage.
• A tuple is a collection which is ordered
and unchangeable.
• Tuples are written with round brackets.
• # Creating a tuple
• my_tuple = (1, 'apple', 3.14, True)

• # Accessing elements
• print("Tuple:", my_tuple)
• print("First element:", my_tuple[0])
• print("Second element:", my_tuple[1])

• # Tuple unpacking
• a, b, c, d = my_tuple
• print("Unpacked elements:", a, b, c, d)
• # Repeating elements in a tuple
• repeated_tuple = ('hello',) * 3
• print("Repeated tuple:", repeated_tuple)

• # Slicing a tuple
• sliced_tuple = my_tuple[1:3]
• print("Sliced tuple:", sliced_tuple)
• # Nested tuple
• nested_tuple = ((1, 2), ('a', 'b'), (True, False))
• print("Nested tuple:", nested_tuple)

• # Tuple as keys in a dictionary


• dict_with_tuples = {('x', 'y'): 10, ('a', 'b'): 20}
• print("Dictionary with tuples as keys:", dict_with_tuples)
• what is the difference between lists and tuples in python with example
and output
• In Python, lists and tuples are both used to store collections of items,
but there are key differences between them.
• Lists:
• Lists are mutable, meaning you can modify their contents (add,
remove, or change elements) after they are created.
• Lists are defined using square brackets [].
• # Creating a list
• my_list = [1, 2, 3, 4, 5]

• # Modifying the list


• my_list[2] = 10

• # Adding an element to the list


• my_list.append(6)

• # Removing an element from the list


• my_list.remove(4)

• print(my_list)
• Tuples:
• Tuples are immutable, meaning once they are created, you cannot
modify their contents (add, remove, or change elements).
• Tuples are defined using parentheses ().
• # Creating a tuple
• my_tuple = (1, 2, 3, 4, 5)
• # Attempting to modify the tuple will raise an error
• # my_tuple[2] = 10 # This will result in an error
• # Tuples do not have append or remove methods
• print(my_tuple)
Example:Tuple with various aspects
• # Creating a tuple
• my_tuple = (1, 'apple', 3.14, True)

• # Accessing elements
• print("Tuple:", my_tuple)
• print("First element:", my_tuple[0])
• print("Second element:", my_tuple[1])
• # Tuple unpacking
• a, b, c, d = my_tuple
• print("Unpacked elements:", a, b, c, d)

• # Finding the length of the tuple


• tuple_length = len(my_tuple)
• print("Length of the tuple:", tuple_length)

• # Checking if an element is present in the tuple


• is_present = 'banana' in my_tuple
• print("'banana' in the tuple:", is_present)

• # Concatenating tuples
• tuple1 = (1, 2, 3)
• tuple2 = ('a', 'b', 'c')
• concatenated_tuple = tuple1 + tuple2
• print("Concatenated tuple:", concatenated_tuple)

• # Repeating elements in a tuple


• repeated_tuple = ('hello',) * 3
• print("Repeated tuple:", repeated_tuple)
• print("Dictionary with tuples as keys:", dict_with_tuples)
• # Slicing a tuple
• sliced_tuple = my_tuple[1:3]
• print("Sliced tuple:", sliced_tuple)

• # Nested tuple
• nested_tuple = ((1, 2), ('a', 'b'), (True, False))
• print("Nested tuple:", nested_tuple)

• # Tuple as keys in a dictionary


• dict_with_tuples = {('x', 'y'): 10, ('a', 'b'): 20}

You might also like