0% found this document useful (0 votes)
52 views

Py Basic

Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
52 views

Py Basic

Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 59

Lesson Plan -2month course 72 hrs.

PYTHON
1991
Python was created by Guido van Rossum, and first released on February 20, 1991

Variables
Variable is a named storage location that holds value or data
A=5
a=5

Creating Variables
A variable is created the moment you first assign a value to it.

x = 5
y = “John”
z=3.5
print(x)
print(y)

Variable Naming Rules


A variable can have a short name (like x and y) or a more descriptive name (age, carname,
total_volume).
St_name

_1Num

_Num1

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)
Age=89
print(AGE)

Example
#Legal variable names:
myvar = "John"
my_var = "John"
_my_var = "John"
myVar = "John"
MYVAR = "John"
myvar2 = "John"

Get the Type


You can get the data type of a variable with the type () function.

Example
x = 5
y = "John"
z=3.5
print(type(x))
print(type(y))
print(type(z))

Python Type Conversion


You can convert from one type to another with the int(), float(), and complex() methods:
x = 1 # int
y = 2.8 # float
z = 1j # complex

#convert from int to float:


a = float(x)

#convert from float to int:


b = int(y)

#convert from int to complex:


c = complex(x)

print(a)
print(b)
print(c)
print(a,b,c)

print(type(a))
print(type(b))
print(type(c))
OR
print(type(a),type(b),type(c))

Multiple assignment to variables


x=”Orange”

y=”Banana”

z=”Cherry”

name=”aruN”

Mark=780

Percentage=85.5

Many Values to Multiple Variables


Python allows you to assign values to multiple variables in one line:

x, y, z = "Orange", "Banana", "Cherry"


print(x)
print(y) or print(x,y,z)
print(z)

a, b ,c =20,45,30 20 45 30

print (a,b,c) a b c

One Value to Multiple Variables

And you can assign the same value to multiple variables in one line:

x = y = z = "Orange" x y z
print(x)
Orange Orange Orange
print(y)
print(z)

or
print(x,y,z)
Unpack a Collection
If you have a collection of values in a list, tuple etc. Python allows you to extract the values into
variables. This is called unpacking.

Example
Unpack a list:

fruits = ["apple", "banana", "cherry"]


x, y, z = fruits
print(x)
print(y)
print(z)
or print(x,y,z)

Input &Print Function


The input () function:
 The purpose of input() function is to read input from the the keyboard
 It accepts all user input as a string.
 The user may enter a number or a string but the input() function treats them as
strings only.
a=”Gtech”

a=input("enter your name")

enter your name SARANYA


print(a)

Output SARANYA

Accept an Integer input from User


We need to convert an input string value into an integer using an int() function.
# both input values are converted into integer type
b=int(input("enter a number"))
enter a number 78
print(type(b))
output
<class 'int'>

Example program:

num1 = int (input ("Enter first number: "))


num2 = int (input ("Enter second number: "))
sum = num1 + num2

print(“sum of num1 and num2 is “,sum)

print("the sum of ",num1,"and ",num2, " is ",sum)


OUTPUT:
Enter the first number: 10
Enter second number: 30
The sum of 10 and 30 is 40

Accept a float input from User


We need to convert an input string value into a float using a float() function.
# Both input values are converted into float type

num1 = float (input("Enter first number: "))


num2 = float(input("Enter second number: "))
sum = num1 + num2
print("the sum of ",num1,"and ",num2, " is: ",sum)
OUTPUT:
Enter the first number: 10.5
Enter second number: 30.5
The sum of 10 and 30 is 41.0

Get multiple input values from a user in one line


In Python, we can accept two or three values from the user in one input() call.
name,Course = input("Enter your Name,Course separated by space:
").split()
print("User Details: ",name, Course)
.split() method -split
a string in to a list

OUTPUT:
Enter your Name,Course separated by space: Ashaz Python
User Details: Ashaz python

Python program to input two integers on a single line.

# Print a message to instruct the user to input the values of 'x' and 'y'.
print("Input the value of x & y")

# Use 'map' to apply the 'int' function to the input values and split them into variables 'x' and 'y'.
x, y = map(int, input().split())

or
x, y = map(int, input(“enter two numbers”).split())
print("The value of x & y are: ", x, y) # Print the values of 'x' and 'y' after they have been assigned.

Regno
Name
Sub1
Sub2
Sub3
Total
o/p
regno
name
total

The print () function


 The print() function prints strings in between quotes (either single or double). If a
print statement has quotes around text, the computer will print it out just as it is written.
 The print ( ) function allows you to print out the value of a variable and strings

print(“Learn python from”)


print('G Tech Thirumala')

OUTPUT:
Learn python from

G Tech Thirumala

2) The print () function prints the value of variable.


For example:

N1 = 20
N2 = 30
Sum=N1+N2
print (Sum) # prints a value
The above print statement receives a variable Sum

3) The print () function prints the value of an expression.


For example:

N1 = 20
N2 = 30
print (N1 + N2) # prints a value of an expression i.e., N1+N2
The above print statement prints a value of an expression
OUTPUT:
50
4) The print () function prints two values separated with comma (,)
For example:

Ver = 3.9
Lang = 'Python'
print (Lang, Ver) # prints two values separated with comma (,)

OUTPUT:
Python 3.9

5) The print() function prints a value, message or both message and values and vice
versa.
For example:

N1 = 20
N2 = 30
Sum = N1 + N2
print ('The sum of two numbers is', Sum)
# print is alternate way
Print(“the sum of”,n1,”and”,n2,”is”,sum)

Formatting Number & stringst Updated : 09 Aug, 2024


Formatting Numbers

 Using f-strings (Formatted String Literals):


o allow you to embed expressions inside string literals, using {}.
o Example:

number = 123.456789
formatted_number = f"{number:.2f}" # Formats the number to 2
decimal places
print(formatted_number) # Output: 123.46

Using format() method:

 The format() method is another way to format numbers.


 Example:

number = 123.456789
formatted_number = "{:.2f}".format(number) # Formats the number to 2 decimal places
print(formatted_number) # Output: 123.46
Thousands separator:

 You can also add commas to separate thousands.


 Example:

number = 1234567.89
formatted_number = f"{number:,.2f}" # Adds comma and formats to 2 decimal places
print(formatted_number) # Output: 1,234,567.89
2. Formatting Strings

 Using f-strings:
o You can embed variables directly into strings.
o Example:

name = "Alice"
age = 30
introduction = f"My name is {name} and I am {age} years old."
print(introduction)

# Output: My name is Alice and I am 30 years old.

 Using format() method:


o You can also use the format() method to insert variables into strings.
o Example:

name = "Alice"
age = 30
introduction = "My name is {} and I am {} years old.".format(name, age)
print(introduction)

# Output: My name is Alice and I am 30 years old.

Padding and alignment:

o You can format strings to be left, right, or center-aligned with padding.


o Example:

text = "Hello"
formatted_text = f"{text:<10}" # Left-aligns the text within 10 characters
print(formatted_text) # Output: Hello
OPERATORS & EXPRESSIONS
Python Operators

Operators are used to perform operations on variables and values.

we use the + operator to add together two values:

print(10 + 5)
result 15

✓ Operators & operands, types

 OPERATORS: These are the special symbols. Eg- + , * , /, etc.


 OPERAND: It is the value on which the operator is applied.

✓ Arithmetic Operators: Unary, Binary

Unary Operators:

Unary Operator is an operator that operates on a single operand, meaning it affects only one
value or variable

Unary operators are commonly used in programming languages to perform various operations
such as changing the sign of a value, incrementing or decrementing a value

Binary operators

Bitwise Operators:

 AND (&): Performs a bitwise AND operation.

a = 6 # 110 in binary
b = 3 # 011 in binary
result = a & b # result is 2 (010 in binary)

6 =0110
3 =0011
--------------------
2 =0010
====================

Decimal numbers and their binary values:


0 = 0000
1 =0001
2 =0010
3 =0011
4 =0100
5 =0101
6 = 0110
7 = 0111
8 = 1000
9 = 1001
10 = 1010
11 = 1011
12 = 1100
13 = 1101
14 = 1110
15 = 1111

 OR (|): Performs a bitwise OR operation.

result = a | b # result is 7 (111 in binary)

6 =0110
3 =0011
--------------------
7 =0111
--------------------

 XOR (^): Performs a bitwise XOR operation.

result = a ^ b # result is 5 (101 in binary)

 NOT (~): Performs a bitwise NOT operation (inverts all bits).

result = ~a # result is -7 (inverts 110 to 001 and adds a sign bit)


a = 0110 6
~a= 1001 -7

 Left Shift (<<): Shifts the bits of the first operand to the left by the number of positions specified by the second
operand.

result = a << 1 # result is 12 (1100 in binary)

a= 0110 #6
a<<1 1100 #12

 Right Shift (>>): Shifts the bits of the first operand to the right by the number of positions specified by the
second operand.

result = a >> 1 # result is 3 (011 in binary)


a= 0110 #6
a>>1 0011 #12
Arithmetic operators

Arithmetic operators are used with numeric values to perform common mathematical operations:
Operator Name Example Sample program

+ Addition x+y x=7

y=6

print(x+y)

output 13

- Subtraction x-y x=7

y=6

print(x-y)

output 1

* Multiplication x*y x=7

y=6

print(x*y)

output 42

/ Division x/y x=5

y=2

print(x/y)

output 2.5

% Modulus x%y x=15

y=2

print(x%y)

output 1
Python Comparison Operators
Comparison operators are used to compare two values:

Operator Name Example Program

== Equal x == y x=5

y=3

print(x == y)

# returns False
because 5 is not equal
to 3

!= Not equal x != y x=5

y=7

print(x != y)

# returns True because


5 is not equal to 3

> Greater than x>y x=5

y=3

print(x > y)

# returns True because


5 is greater than 3

< Less than x<y x=5

y=3

print(x < y)

# returns False
because 5 is not less
than 3

>= Greater than or equal to x >= y x=5


y=3

print(x >= y)

# returns True because


five is greater, or
equal, to 3

<= Less than or equal to x <= y x=5

y=3

print(x <= y)

# returns False
because 5 is neither
less than or equal to 3
Python Logical Operators

Operator Description Program

and Returns True if both statements are true x=5

print(x > 3 and x <10)

# returns True because 5 is


greater than 3 AND 5 is
less than 10

or Returns True if one of the statements is


true x=3

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)

not Reverse the result, returns False if the x=5


result is true
x!=5 false

x!=10 true

print(not(x > 3 and x <


10))

# returns False because


not is used to reverse the
result

Membership Operators
Membership operators are used to test if a value is presented in a sequence:

Operato Description Example


r

in Returns True if a sequence with y in x x = ["apple", "banana"]


the specified value is present in
the object y=”banana”
print(y in x)

print("banana" in x)

# returns True because a


sequence with the value "banana"
is in the list

not in Returns True if a sequence with y not in x = ["apple", "banana"]


the specified value is not x
present in the object y=”pineapple”

print(y not in x)

print("pineapple" not in x)

# returns True because a


sequence with the value
"pineapple" is not in the list

Workout questions:

Write a program to get name and institution of a user and display a greeting for the user and if the user is from G-TEC
EDUCATION, display another Message “Welcome to G-Tec” or else just print the greetings.
Eg.
Enter your name: Akshitha
Enter your institution: G-TEC EDUCATION

Hello Akshitha. Welcome to G-TEC EDUCATION

Enter your name: Ameen


Enter your institution: OXFORD
Hello Ameen.

37. Write a program with multiline strings.

a = """Lorem ipsum dolor sit amet,


consectetur adipiscing elit,
sed do eiusmod tempor incididunt
ut labore et dolore magna aliqua."""
print(a)
50. Write a Python program to calculate Area of a Triangle using base and height.

Python program to find the area of a triangle


Mathematical formula:

Area of a triangle = (s*(s-a)*(s-b)*(s-c))-1/2


Here is the semi-perimeter and a, b and c are three sides of the triangle. Let's understand the
following example.

See this example:

# Three sides of the triangle is a, b and c:


a = float(input('Enter first side: '))
b = float(input('Enter second side: '))
c = float(input('Enter third side: '))

# calculate the semi-perimeter


s = (a + b + c) / 2

# calculate the area


area = (s*(s-a)*(s-b)*(s-c)) ** 0.5
print('The area of the triangle is f' ,area)

Output:

ADVERTISEMENT

Enter first side: 5


Enter second side: 6
Enter third side: 7
The area of the triangle is 14.70

Write a program which prompts the user to input principle, rate and time and calculate
compound interest.
Hint:
CI = P(1+R/100) ^T – P.

# Input principal amount, interest rate, and number of years

principal_amount = float(input("Enter the principal amount: "))


interest_rate = float(input("Enter the interest rate (in percentage): "))
number_of_years = int(input("Enter the number of years: "))
# Calculate compound interest
compound_interest = principal_amount * (1 + interest_rate/100) ** number_of_years - principal_amount
# Display the compound interest
print("Compound Interest: ", compound_interest)
Input :
Enter the Principle amount : 5000
Enter the interest Rate (percentage) : 5.5
Enter the number of Years : 3
COPY

Output :
Compound Interest : 854.375
Write a Python program to find simple interest. Hint: simple interest = principle x rate x time / 100.

# Input principal amount, interest rate, and time period


principal = float(input("Enter the principal amount: "))
rate = float(input("Enter the interest rate: "))
time = float(input("Enter the time period in years: "))

# Calculate simple interest


interest = (principal * rate * time) / 100

# Print the calculated simple interest


print("Simple Interest:", interest)

input :
Enter the principal amount: 1000
Enter the Interest Rate: 5
Enter the time periods in year : 2

Output:
Simple Interest : 100.0

Decision making statements • the if statement • The If-else statement • Nested if statement

• Multi way if else statements

DECISION & LOOP CONTROL STATEMENTS /Conditional Statements

Decisions in a program are used when the program has conditional choices to execute a code block. Let's
take an example of traffic lights, where different colours of lights lit up in different situations based on the
conditions of the road or any specific rule.

If conditions that occur while executing a program to specify actions. Multiple expressions get evaluated with an
outcome of either TRUE or FALSE. These are logical decisions, and
Python also provides decision-making statements that to make decisions within a program for an application based on
the user requirement.

Python provides various types of conditional statements:


If Statements
It consists of a Boolean expression which results are either TRUE or FALSE, followed by one or more
statements
If flow chart

Syntax:

if expression:

#execute your code

Example

a = 15

if a > 10:

print("a is greater")

output
a is greater than

If else Statements
It also contains a Boolean expression.
The if the statement is followed by an optional else statement &
if the expression results in FALSE, then else statement gets
executed. It is also called alternative execution in which there
are two possibilities of the condition determined in which any
one of them will get executed.
Syntax:
if expression:
#execute your code
else:
#execute your code

Example:
a = 15
b = 20
if a > b:
print("a is greater")
else:
print("b is greater")

output
b is greater

elif Statements
Syntax

if expression1:

#execute your code

elif expression2:

#execute your code

else:

#execute your code

Example

a =15

b = 15

if a > b:

print("a is greater")

elif a == b:

print("both are equal")

else:

print("b is greater")

output
both are equal

Nested if

X=14

if x>0:

print("the given number is greater than zero")

if x%2==0:

print("and it is even number")

else:

print("and it is odd number")


else:

print("the given number is negative number")

Output

The given number is greater than zero and it is even number

9th

✓ Boolean Expression & relational operators

1. Boolean Expressions

 A Boolean expression is an expression that evaluates to either True or False.


 It often involves comparison or logical operations.

Example:

a = 5
b = 3
result = a > b # This is a Boolean expression
print(result) # Output: True

In this case, a > b is a Boolean expression, and it evaluates to True because 5 is greater than 3.

2. Relational (Comparison) Operators

Relational operators are used to compare two values and return a Boolean result (True or False). Here’s a list of the
relational operators:

 Equal to (==): Checks if two values are equal.

result = a == b # False, because 5 is not equal to 3

 Not equal to (!=): Checks if two values are not equal.

result = a != b # True, because 5 is not equal to 3

 Greater than (>): Checks if the left value is greater than the right.

result = a > b # True, because 5 is greater than 3

 Less than (<): Checks if the left value is less than the right.

result = a < b # False, because 5 is not less than 3

 Greater than or equal to (>=): Checks if the left value is greater than or equal to the right.

result = a >= b # True, because 5 is greater than or equal to 3

 Less than or equal to (<=): Checks if the left value is less than or equal to the right.

result = a <= b # False, because 5 is not less than or equal to 3


Example of Boolean Expressions with Relational Operators:

You can use these relational operators inside Boolean expressions to perform comparisons.

age = 18
can_vote = age >= 18 # Checks if age is greater than or equal to 18
print(can_vote) # Output: True

In this example, age >= 18 is a Boolean expression, and since the value of age is 18, the expression evaluates to True.

Summary

 Boolean Expressions: Expressions that evaluate to True or False.


 Relational Operators: Used to compare two values (==, !=, >, <, >=, <=) and return a Boolean result.

✓ Conditional expressions

Conditional expressions in Python allow you to choose between two values based on a condition. They are also
known as ternary operators.

Basic Syntax

The syntax for a conditional expression is:

value_if_true if condition else value_if_false


How It Works

 condition: This is the Boolean expression that is evaluated.


 value_if_true: This value is returned if the condition is True.
 value_if_false: This value is returned if the condition is False.

Example

Let’s say you want to assign a value to a variable based on whether a number is even or odd:

number = 10
result = "Even" if number % 2 == 0 else "Odd"
print(result) # Output: Even

In this example:

 The condition number % 2 == 0 checks if number is even.


 If the condition is True, "Even" is assigned to result.
 If the condition is False, "Odd" is assigned to result.

Another Example

Here’s a slightly different example:

age = 16
status = "Adult" if age >= 18 else "Minor"
print(status) # Output: Minor

In this case:

 The condition age >= 18 checks if age is 18 or older.


 Since age is 16, which is not greater than or equal to 18, "Minor" is assigned to status.

Summary

 Conditional expressions are a concise way to assign values based on a condition.


 The syntax is value_if_true if condition else value_if_false.
n1=int(input(“enter your first number”)

n2=int(input(“enter your second number”)

n3= int(input(“enter your third number”)

if n1==n2 and n2==n3:

printf(“numbers are equal”)

elif(n1>n2) and (n1>n3):

printf(“n1 is the largest number”)

elif n2>n3:

print(“n2 is largest number”)

else:

printf(“n3 is largest number”)

Python Loops
Python has two primitive loop commands:

 while loops
 for loops

The while Loop


With the while loop we can execute a set of statements as long as a condition is true.

Print i as long as i is less than 6:

i = 1
while i < 6:
print(i)
i += 1
The while loop requires relevant variables to be ready, in this example we need to define an
indexing variable, i, which we set to 1.

while loops with breaks


With the break statement we can stop the loop even if the while condition is true.
Syntax

i = 1
while i < 5:
print(i)
if i == 2:
break
i += 1

while loops with continue


With the continue statement, we can skip over a part of the loop where an additional condition is set, and then go on to complete the rest of
the loop.
Syntax

i = 0
while i < 5:
i += 1
if i == 2:
continue
print(i)

while loops with else


With the else statement, we can run a block of code once when the condition no longer is true.
Syntax

i = 1
while i < 5:
print(i)
i += 1
else:
print("i is no longer less than 5")

✓ For loops

Python For Loops


A for loop is used for iterating over a sequence (that is either a list, a tuple, a dictionary, a set, or
a string).

This is less like the for keyword in other programming languages, and works more like an iterator
method as found in other object-orientated programming languages.

With the for loop we can execute a set of statements, once for each item in a list, tuple, set etc.

Example
Print each fruit in a fruit list:

fruits = ["apple", "banana", "cherry"]


for x in fruits:
print(x)
the break Statement
With the break statement we can stop the loop before it has looped through all the items:

Example
Exit the loop when x is "banana":

fruits = ["apple", "banana", "cherry"]


for x in fruits:
print(x)
if x == "banana":
break

The continue Statement


With the continue statement we can stop the current iteration of the loop, and continue with the
next:

Example
Do not print banana:

fruits = ["apple", "banana", "cherry"]


for x in fruits:
if x == "banana":
continue
print(x)

✓ Range Functions

loop through a set of code a specified number of times, we can use the range() function,

The range() function returns a sequence of numbers, starting from 0 by default, and increments
by 1 (by default), and ends at a specified number.

Example
Using the range() function:

for x in range(6):
print(x)
0
1
2
3
4
5

Note that range(6) is not the values of 0 to 6, but the values 0 to 5.

The range() function defaults to 0 as a starting value, however it is possible to specify the
starting value by adding a parameter: range(2, 6), which means values from 2 to 6 (but not
including 6):

Example
Using the start parameter:

for x in range(2, 6):


print(x)
2
3
4
5

for x in range(3, 6,2):


print(x)
3
5
for x in range(6, 3,2):
print(x)
EMPTY LIST

for x in range(6, 3,-2):


print(x)
6
4
The range() function defaults to increment the sequence by 1, however it is possible to specify
the increment value by adding a third parameter: range(2, 30, 3):

Example
Increment the sequence with 3 (default is 1):

for x in range(2, 30, 3):


print(x)

example:

python Example: Python program to check if a number is odd or even.


# list of numbers
list_of_numbers = [2,4,6,9,5]

# for loop to iterate through the list and check each elements of the list
for i in list_of_numbers:
# check if no. is odd
if i % 2 != 0:
# if condition is True print "odd"
print (i, "is an odd number")
# check if no. is even
if i % 2 == 0:
# if condition is false print "even"
print (i, "is an even number")
2)
grade = 34

if grade >= 60:


print("You passed the exam.")
print("Congratulations!")
else:
print("You failed the exam.")
print("Better luck next time.")
3)
grade = 85

if grade >= 90:


print("You got an 'A' on the exam.")
elif grade >= 80:
print("You got a 'B' on the exam.")
elif grade >= 70:
print("You got a 'C' on the exam.")
elif grade >= 60:
print("You got a 'D' on the exam.")
else:
print("You got an 'F' on the exam.")

4)
names = ['Anna', 'Beth', 'Chad', 'Drew', 'Elsa', 'Fred']
grades = [56, 92, 87, 43, 75, 62]

for i in range(0, len(names) ):

if grades[i] >= 90:


print(names[i] + " got a grade of 'A' on the exam.")
elif grades[i] >= 80:
print(names[i] + " got a grade of 'B' on the exam.")
elif grades[i] >= 70:
print(names[i] + " got a grade of 'C' on the exam.")
elif grades[i] >= 60:
print(names[i] + " got a grade of 'D' on the exam.")
else:
print(names[i] + " got a grade of 'F' on the exam.")
5)
my_list = [74, -55, -77, 58, 0, 91, 62, 0, -91, 61]

for i in range(0, len(my_list)):


if my_list[i] % 2 == 0:
print(str(my_list[i]) + " is even.")
else:
print(str(my_list[i]) + " is odd.")

74 is even.
-55 is odd.
-77 is odd.
58 is even.
0 is even.
91 is odd.
62 is even.
0 is even.
-91 is odd.
61 is odd.

6)

Example: Determining if Elements of a List are Positive, Negative,


or Neither
for i in range(0, len(my_list)):

if my_list[i] < 0:
print(str(my_list[i]) + " is negative.")
elif my_list[i] > 0:
print(str(my_list[i]) + " is positive.")
else:
print(str(my_list[i]) + " is neither positive nor negative.")

74 is positive.
-55 is negative.
-77 is negative.
58 is positive.
0 is neither positive nor negative.
91 is positive.
62 is positive.
0 is neither positive nor negative.
-91 is negative.
61 is positive.

LISTS

✓ List values

✓ Create, Accessing elements

Access Items
List items are indexed and you can access them by referring to the index number:

Example
Print the second item of the list:

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.

Example
Print the last item of the list:

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


print(thislist[-1])

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", "melon", "mango"]


print(thislist[2:5])

Note: The search will start at index 2 (included) and end at index 5 (not included).

Remember that the first item has index 0.

By leaving out the start value, the range will start at the first item
✓ List length, membership

Finding the Length of a List in Python


Method 1: Naïve Counter Method
The first way to determine a list length in Python is to use a for loop and a counter. This method does not
require any built-in or imported functions.

The following code shows how to find the list length using a for loop and a counter:

my_list = [0,1,2,3,4]
counter = 0
for element in my_list:
counter += 1
print(counter)

Method 2: len()
Python offers a built-in method to find the length of a list called len(). This method is the most
straightforward and common way to determine a list length.

To use the len() function, provide the list as an argument. For example:

my_list = [0,1,2,3,4]
print(len(my_list))

What is a Membership Operator?

Membership operators in Python are operators used to test whether a value exists
in a sequence, such as a list, tuple, or string. The membership operators available in
Python are,

 in: The in operator returns True if the value is found in the sequence.
 not in: The not in operator returns True if the value is not found in the sequence

# membership operator in Python


# using "in" operator
fruits = ["apple", "banana", "cherry"]
if "banana" in fruits:
print("Yes, banana is a fruit!")
# using "not in" operator
if "orange" not in fruits:
print("Yes, orange is not in the list of fruits")

✓ List & for loops a list in Python


In Python , the list is a type of container in Data Structures, which is used to store
multiple data at the same time. Unlike Sets , lists in Python are ordered and have a
definite count. In this article, we will see how to iterate over a list in Python and also
Python loop through list of strings.

# Python3 code to iterate over a list

list = [1, 3, 5, 7, 9]

# Using for loop

for i in list:
print(i)

Iterate through a list using f or loop and range()


In case we want to use the traditional for loop which iterates from number x to number y.
Python

# Python3 code to iterate over a list


list = [1, 3, 5, 7, 9]

# getting length of list


length = len(list)

✓ List operations

List Operations in Python


Below are some of the commonly used list operations in python:
1. Append()
As we know, a list is mutable. We can add an element at the back of the list using an inbuilt function of
Python list operation append(). Let us see implementations of it.
Python
my_list=[1,2,3]

my_list.append(9)

my_list.append(8)
print("The list after append() operation is: ",my_list)

Here, we created a list called my_list and added elements to the list. The output of the above code is:

2. extend()
Extend () method can be used to add more than one element at the end of a list. Let us understand the
function by its implementation.
 Python
my_list.extend([20,21])
print("The list after axtend() operator is: ",my_list)

3. Insert()
Now we can insert an element in between the list using the inbuilt function of Python list operation insert()
 Python
my_list.insert(5,30)
print("The list after insert() operator is: \n",my_list)

In this function, the first input is the position at which the element is to be added, and the second input is the element's
value. Here after using the insert() we have added 30 at 5th position in my_list. Hence the updated list will be:

4. remove()
The way we added an element between the list, similarly, we can remove from in between a list using an
inbuilt Python list operation function remove().
 Python
my_list.remove(10)
print("The list after remove() operator is: \n",my_list)
5. Pop()
There is an inbuilt function to remove the last element from the list known as pop().
 Python
my_list.pop()
print("The list after pop() operator is:\n",my_list)

6. Slice()
This method is used to print a section of the list. Which means we can display elements of a specific index.
 Python
print("The elements of list in the range of 3 to 12 are:\n",my_list[3:12])

7. reverse()
You can use the reverse() operation to reverse the elements of a list. This method modifies the

original list. We use the slice operation with negative indices to reverse a list without

modifying the original. Specifying negative indices iterates the list from the rear end to the

front end of the list.

Code:

myList = [1, 2, 3, 'EduCBA', 'makes learning fun!']


print(myList[::-1]) # does not modify the original list
myList.reverse() # modifies the original list
print(myList)

Output:

8. len()
The len() method returns the length of the list, i.e., the number of elements in the list.

Code:

myList = [1, 2, 3, 'EduCBA', 'makes learning fun!']


print(len(myList))

output

9. min() & max()


The min() method returns the minimum value in the list. The max() method returns the

maximum value in the list. Both methods accept only homogeneous lists, i.e., lists with similar

elements.

Code:

myList = [1, 2, 3, 4, 5, 6, 7]
print(min(myList))
print(max(myList))

out put

1
7

10. count()
The function count() returns the number of occurrences of a given element in the list.

Code:

myList = [1, 2, 3, 4, 3, 7, 3, 8, 3]
print(myList.count(3))

Output:

11. concatenate
The concatenate operation merges two lists and returns a single list. The concatenation is

performed using the + sign. It’s important to note that the individual lists are not modified,

and a new combined list is returned.

Code:

myList = [1, 2, 3, 'EduCBA', 'makes learning fun!']


yourList = [4, 5, 'Python', 'is fun!']
print(myList+yourList)

12. multiply
Python also allows multiplying the list n times. The resultant list is the original list iterated n

times.

Code:
myList = ['EduCBA', 'makes learning fun!']
print(myList*2)

3. index()
The index() method returns the position of the first occurrence of the given element. It takes

two optional parameters – the beginning index and the end index. These parameters define

the start and end position of the search area on the list. When you supply the begin and end

indices, the element is searched only within the sub-list specified by those indices. When not

supplied, the element is searched in the whole list.

Code:

myList = [1, 2, 3, 'EduCBA', 'makes learning fun!']


print(myList.index('EduCBA')) # searches in the whole list
print(myList.index('EduCBA', 0, 2)) # searches from 0th to 2nd

position

14. sort()
The sort method sorts the list in ascending order. You can only perform this operation on

homogeneous lists, which means lists with similar elements.

Code:

yourList = [4, 2, 6, 5, 0, 1]
yourList.sort()
print(yourList)
15. clear()
This function erases all the elements from the list and empties them.

Code:

myList = [1, 2, 3, 'EduCBA', 'makes learning fun!']


myList.clear()

Output:

Here the output is empty because it clears all the data.

16. copy()
The copy method returns the shallow copy list. Now the created list points to a different

memory location than the original one. Hence any changes made to the list don’t affect

another one.

Syntax:

list.copy()

Code:

even_numbers = [2, 4, 6, 8]
value = even_numbers.copy()
print('Copied List:', value)

✓ Object & values


Objects
Definition: In Python, everything is an object. An object is a collection of data and methods that operate on
that data. Python uses objects to represent data structures, functions, and more.
Types: Each object in Python has a type, which determines what kind of data it holds and what operations
can be performed on it. Examples of types include int, float, str, list, dict, and user-defined classes
x = 10 # x is an int object
name = "Alice" # name is a str object

Attributes: Objects can have attributes (data) and methods (functions) associated with them. For example,
a list object has methods like .append () and .remove().

my_list = [1, 2, 3]
my_list.append(4) # Append method modifies the list object
2. Values
Definition: Values are the actual data stored within an object. For example, in x = 10, the value 10 is stored
within the integer object x.
Mutability: Python objects can be mutable or immutable.
Mutable: Objects whose values can be changed after they are created. Examples include lists, dictionaries,
and sets.
Python

Copy code
my_list = [1, 2, 3]
my_list[0] = 10 # The value of the first element is changed
Immutable: Objects whose values cannot be changed after they are created. Examples include integers,
floats, strings, and tuples.
python
Copy code
s = "hello"
s = s.upper() # A new string object is created, s now references "HELLO"

3. Object Identity and Comparison


Identity: Each object has a unique identity, which you can check using the id() function. This identity is
essentially the memory address where the object is stored.
python
Copy code
a = [1, 2, 3]
b = [1, 2, 3]
print(id(a)) # Prints the memory address of list a
print(id(b)) # Prints the memory address of list b

Equality: You can check if two objects have the same value using ==, and if they are the same object (i.e.,
have the same identity) using is.
python
Copy code
a = [1, 2, 3]
b = [1, 2, 3]
print(a == b) # True, because the values are the same
print(a is b) # False, because they are different objects in memory

✓ Passing list to a function

you can send any data types of argument to a function (string, number, list, dictionary etc.), and it
will be treated as the same data type inside the function.

E.g. if you send a List as an argument, it will still be a List when it reaches the function:

Example
def my_function(food):
for x in food:
print(x)

fruits = ["apple", "banana", "cherry"]

my_function(fruits)

✓ Cloning lists

Cloning a list in Python means creating a copy of the original list. This way, you can work with the clone without
affecting the original list. Here’s a simple explanation of how to clone lists:

1. Using the copy() Method

 The copy() method creates a shallow copy of the list.


 Example:

original_list = [1, 2, 3, 4]
cloned_list = original_list.copy()
print(cloned_list) # Output: [1, 2, 3, 4]
2. Using List Slicing

 You can create a copy of a list using slicing. This method also creates a shallow copy.
 Example:
original_list = [1, 2, 3, 4]
cloned_list = original_list[:]
print(cloned_list) # Output: [1, 2, 3, 4]
3. Using the list() Constructor

 You can use the list() constructor to create a copy of the list.
 Example:

original_list = [1, 2, 3, 4]
cloned_list = list(original_list)
print(cloned_list) # Output: [1, 2, 3, 4]
4. Using copy Module for Deep Copy

 If your list contains nested lists or other mutable objects and you want to make sure changes to the nested objects
don’t affect the original list, you need a deep copy.
 Example using copy.deepcopy():

import copy

original_list = [1, 2, [3, 4]]


cloned_list = copy.deepcopy(original_list)
print(cloned_list) # Output: [1, 2, [3, 4]]

 A deep copy creates a new copy of the list and all nested objects, so changes to nested objects in the clone won’t affect
the original.

Summary

 Shallow Copy: Use copy(), slicing [:], or list() to clone a list. Changes to nested objects in the clone will affect the
original.
 Deep Copy: Use copy.deepcopy() to clone a list and its nested objects. Changes to nested objects won’t affect the
original.

✓ Nested list

# Creating a simple nested list


nested_list = [
[1, 2, 3], # First inner list
[4, 5, 6], # Second inner list
[7, 8, 9] # Third inner list
]

# Printing the entire nested list


print("Nested List:")
print(nested_list)

# Accessing elements in a nested list


# Accessing the first inner list
print("\nFirst inner list:")
print(nested_list[0])

# Accessing an element from the second inner list


print("\nElement from the second inner list (row 2, column 3):")
print(nested_list[1][2]) # Accesses the element at row 2, column 3 (i.e., 6)

# Modifying an element in the nested list


print("\nModifying an element in the nested list...")
nested_list[2][1] = 88 # Changing the element at row 3, column 2 to 88
print("Updated Nested List:")
print(nested_list)

TUPLES, SET & DICTIONARIES

✓ Tuples

• Introduction to tuples

• Creating tuple

• Tuple assignment

• Operations on tuples

Tuples in Python are a type of data structure that can hold a collection of items. They are similar to lists but with some
key differences. Here's a simple overview:

1. What Is a Tuple?

 A tuple is an immutable sequence of elements.


 Once created, you cannot modify (add, remove, or change) the elements of a tuple.

2. Creating a Tuple

 You create a tuple by placing comma-separated values inside parentheses ().


 Example:

my_tuple = (1, 2, 3, 4)
3. Accessing Tuple Elements

 You access elements in a tuple using indexing, similar to lists.


 Example:

my_tuple = (1, 2, 3, 4)
first_element = my_tuple[0] # Accesses the first element
print(first_element) # Output: 1
4. Tuple Characteristics

 Immutable: You cannot modify, add, or remove elements after the tuple is created.
 Ordered: Elements are stored in a specific order, and you can access them by their index.
 Allow Duplicates: Tuples can contain duplicate values.
 Can Contain Mixed Data Types: Tuples can store elements of different data types.

mixed_tuple = (1, "hello", 3.14, [1, 2, 3])


5. Tuple Operations

 Concatenation: You can concatenate tuples using the + operator.

tuple1 = (1, 2, 3)
tuple2 = (4, 5, 6)
result = tuple1 + tuple2
print(result) # Output: (1, 2, 3, 4, 5, 6)

 Repetition: You can repeat tuples using the * operator.

my_tuple = (1, 2, 3)
result = my_tuple * 2
print(result) # Output: (1, 2, 3, 1, 2, 3)

 Unpacking: You can unpack tuple values into variables.

a, b, c = (1, 2, 3)
print(a) # Output: 1
print(b) # Output: 2
print(c) # Output: 3
6. Tuple Methods

 count(): Counts the number of occurrences of a value.

my_tuple = (1, 2, 2, 3)
count_of_twos = my_tuple.count(2)
print(count_of_twos) # Output: 2

 index(): Finds the index of the first occurrence of a value.

my_tuple = (1, 2, 3, 4)
index_of_three = my_tuple.index(3)
print(index_of_three) # Output: 2
Summary

 Tuples: Immutable, ordered collections.


 Creation: (1, 2, 3).
 Access: Use indexing like lists.
 Operations: Concatenation, repetition, and unpacking.
✓ Sets

• Introduction

• Set with List - operations

You can perform various operations with sets and lists in Python. Here’s a quick overview of how to work with sets
and lists together:

1. Converting Lists to Sets

 Convert a list to a set to remove duplicates and perform set operations.


 Example:

my_list = [1, 2, 2, 3, 4]
my_set = set(my_list) # Converts list to set, resulting in {1, 2, 3, 4}
2. Converting Sets to Lists

 Convert a set to a list if you need ordered elements or indexing.


 Example:

my_set = {1, 2, 3, 4}
my_list = list(my_set) # Converts set to list
3. Adding List Elements to a Set

 Use the update() method to add elements from a list to a set.


 Example:
my_set = {1, 2}
my_list = [3, 4]
my_set.update(my_list) # Adds elements from list to set
4. Removing List Elements from a Set

 Use a loop or a set comprehension to remove elements found in a list from a set.
 Example:

my_set = {1, 2, 3, 4}
remove_list = [2, 4]
my_set.difference_update(remove_list) # Removes elements that are in remove_list
5. Finding Common Elements (Intersection)

 Find common elements between a set and a list.


 Example:

my_set = {1, 2, 3, 4}
my_list = [3, 4, 5, 6]
common_elements = my_set.intersection(my_list) # Results in {3, 4}
6. Finding Elements in the Set but not in the List (Difference)

 Find elements present in the set but not in the list.


 Example:

my_set = {1, 2, 3, 4}
my_list = [3, 4, 5, 6]
unique_elements = my_set.difference(my_list) # Results in {1, 2}
7. Finding Elements in the List but not in the Set (Difference)

 Find elements present in the list but not in the set.


 Example:

my_set = {1, 2, 3, 4}
my_list = [3, 4, 5, 6]
unique_in_list = set(my_list).difference(my_set) # Results in {5, 6}
8. Union of Set and List

 Combine elements from both a set and a list.


 Example:

my_set = {1, 2, 3}
my_list = [3, 4, 5]
combined = my_set.union(my_list) # Results in {1, 2, 3, 4, 5}
9. Symmetric Difference (Elements in Either Set or List but Not Both)

 Find elements in either the set or the list but not in both.
 Example:

my_set = {1, 2, 3}
my_list = [3, 4, 5]
sym_diff = my_set.symmetric_difference(my_list) # Results in {1, 2, 4, 5}
Summary

 Conversion: Convert between lists and sets using set() and list().
 Add Elements: Use update() to add list elements to a set.
 Remove Elements: Use difference_update() or a loop to remove list elements from a set.
 Set Operations: Use intersection(), difference(), union(), and symmetric_difference() for set and list
operations.

These operations help you leverage the strengths of both lists and sets in Python. If you have more questions or need
further examples, feel free to ask!
• Set operations and functions

Sets in Python: Simple Notes

1. Definition:
o A set is an unordered collection of unique elements.
o Sets do not allow duplicate values.

2. Creating a Set:
o Use curly braces {} or the set() constructor.
o Example:

my_set = {1, 2, 3}
another_set = set([1, 2, 3])

3. Adding Elements:
o Use the add() method to add elements.
o Example:

my_set.add(4) # Adds 4 to the set

4. Removing Elements:
o Use remove() to remove a specific element.
o Use discard() to remove an element if it exists (no error if the element is not found).
o Example:

my_set.remove(2) # Removes 2 from the set


my_set.discard(3) # Removes 3 from the set if it exists

5. Set Operations:
o Union: Combine elements from two sets.

union_set = set1 | set2

o Intersection: Get common elements between two sets.

intersection_set = set1 & set2

o Difference: Get elements in the first set but not in the second.

difference_set = set1 - set2

o Symmetric Difference: Get elements in either set but not in both.

sym_diff_set = set1 ^ set2

6. Checking Membership:
o Use the in keyword to check if an element is in the set.
o Example:

exists = 1 in my_set # Checks if 1 is in the set

7. Set Comprehensions:
o Similar to list comprehensions but for sets.
o Example:

squared_set = {x**2 for x in range(5)} # Creates a set of squared numbers


8. Set Methods:
o copy(): Creates a shallow copy of the set.
o clear(): Removes all elements from the set.
o pop(): Removes and returns an arbitrary element.
o update(): Adds elements from an iterable to the set.

Summary

 Unordered: No guaranteed order of elements.


 Unique: No duplicate values allowed.
 Operations: Union, intersection, difference, and symmetric difference.
 Methods: Add, remove, discard, and others.

Sets are particularly useful for membership testing and eliminating duplicates. If you have more questions or need
examples, just let me know!

✓ Dictionaries

• Basics of dictionaries

• Creating a dictionary

• Add, Replace, retrieve, format, and delete items in a dictionary

Dictionaries in Python are a versatile data structure used to store key-value pairs. Here’s a simple guide to
understanding and working with dictionaries:

1. What Is a Dictionary?

 A dictionary is an unordered collection of key-value pairs.


 Each key is unique and maps to a value.

2. Creating a Dictionary

 Use curly braces {} with key-value pairs separated by a colon :.


 Example:

my_dict = {"name": "Alice", "age": 25, "city": "New York"}


3. Accessing Values

 Access values using their keys.


 Example:

name = my_dict["name"] # Accesses the value associated with the key "name"
4. Adding or Updating Items

 Add or update items using square brackets and assignment.


 Example:

my_dict["email"] = "alice@example.com" # Adds a new key-value pair


my_dict["age"] = 26 # Updates the value for the key "age"
5. Removing Items

 Use the del statement or the pop() method.


 Example:

del my_dict["city"] # Removes the key-value pair with the key "city"
email = my_dict.pop("email") # Removes and returns the value associated with the key
"email"
6. Checking if a Key Exists

 Use the in keyword.


 Example:

has_name = "name" in my_dict # Checks if the key "name" exists in the dictionary
7. Iterating Over a Dictionary

 Keys: Iterate over keys using a loop.

for key in my_dict:


print(key)

 Values: Iterate over values using values().

for value in my_dict.values():


print(value)

 Items: Iterate over key-value pairs using items().

for key, value in my_dict.items():


print(f"Key: {key}, Value: {value}")

8. Dictionary Methods

 copy(): Creates a shallow copy of the dictionary.

new_dict = my_dict.copy()

 get(key, default): Returns the value for the key, or a default value if the key doesn’t exist.

age = my_dict.get("age", "Not Found")

 keys(): Returns a view object of all keys.

keys = my_dict.keys()

 values(): Returns a view object of all values.

values = my_dict.values()

 items(): Returns a view object of all key-value pairs.

items = my_dict.items()
9. Nested Dictionaries

 Dictionaries can contain other dictionaries as values.


 Example:

nested_dict = {
"person1": {"name": "Alice", "age": 25},
"person2": {"name": "Bob", "age": 30}
}
Summary

 Unordered: Keys and values are stored without a specific order.


 Mutable: You can change, add, or remove key-value pairs.
 Key-Value Pairs: Access and modify values using unique keys.

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

STRING MANIPULATION

✓ Built-in string functions

this provides a wide range of built-in string functions that make it easy to manipulate and work with strings. Here's an
overview of some of the most commonly used string functions:

1. len()

 Purpose: Returns the length of a string.


 Example:

python
Copy code
length = len("Hello") # Results in 5
2. str()

 Purpose: Converts a value to a string.


 Example:

python
Copy code
number = 123
text = str(number) # Results in "123"
3. lower()

 Purpose: Converts all characters in a string to lowercase.


 Example:

python
Copy code
text = "Hello".lower() # Results in "hello"
4. upper()

 Purpose: Converts all characters in a string to uppercase.


 Example:
python
Copy code
text = "Hello".upper() # Results in "HELLO"
5. capitalize()

 Purpose: Capitalizes the first character of the string.


 Example:

python
Copy code
text = "hello".capitalize() # Results in "Hello"
6. title()

 Purpose: Capitalizes the first character of each word in the string.


 Example:

python
Copy code
text = "hello world".title() # Results in "Hello World"
7. strip()

 Purpose: Removes leading and trailing whitespace (or specified characters).


 Example:

text = " Hello ".strip() # Results in "Hello"


8. lstrip() and rstrip()

 Purpose: Removes leading (lstrip()) or trailing (rstrip()) whitespace or specified characters.


 Example:

text = " Hello".lstrip() # Results in "Hello"


text = "Hello ".rstrip() # Results in "Hello"
9. replace()

 Purpose: Replaces all occurrences of a substring with another substring.


 Example:

text = "Hello, World!".replace("World", "Python") # Results in "Hello, Python!"


10. find()

 Purpose: Returns the lowest index where the substring is found, or -1 if not found.
 Example:

index = "Hello, World!".find("World") # Results in 7


11. rfind()

 Purpose: Returns the highest index where the substring is found, or -1 if not found.
 Example:

index = "Hello, World, Hello!".rfind("Hello") # Results in 13


12. index()

 Purpose: Similar to find(), but raises a ValueError if the substring is not found.
 Example:

index = "Hello, World!".index("World") # Results in 7


13. count()

 Purpose: Returns the number of non-overlapping occurrences of a substring.


 Example:

count = "Hello, Hello, Hello!".count("Hello") # Results in 3


14. split()

 Purpose: Splits a string into a list of substrings based on a delimiter.


 Example:

words = "Hello, World!".split(", ") # Results in ["Hello", "World!"]


15. join()

 Purpose: Joins elements of an iterable (like a list) into a single string with a specified separator.
 Example:

text = ", ".join(["Alice", "Bob", "Charlie"]) # Results in "Alice, Bob, Charlie"


16. startswith()

 Purpose: Checks if the string starts with a spec


 ied prefix.

Example:

result = "Hello, World!".startswith("Hello") # Results in True


17. endswith()

 Purpose: Checks if the string ends with a specified suffix.

Example:

result = "Hello, World!".endswith("World!") # Results in True


18. isalpha()

 Purpose: Returns True if all characters in the string are alphabetic.

Example:

result = "Hello".isalpha() # Results in True


result = "Hello123".isalpha() # Results in False
19. isdigit()

 Purpose: Returns True if all characters in the string are digits.

Example:

result = "12345".isdigit() # Results in True


result = "123a5".isdigit() # Results in False
20. isalnum()

 Purpose: Returns True if all characters in the string are alphanumeric (letters and numbers).

Example:

result = "Hello123".isalnum() # Results in True


result = "Hello 123".isalnum() # Results in False
21. islower() and isupper()

 Purpose: Returns True if all alphabetic characters are lowercase (islower()) or uppercase (isupper()).
Example:

result = "hello".islower() # Results in True


result = "HELLO".isupper() # Results in True
22. swapcase()

 Purpose: Swaps the case of all characters in the string.

Example:

text = "Hello, World!".swapcase() # Results in "hELLO, wORLD!"


23. zfill()

 Purpose: Pads the string with zeros on the left to reach a specified length.
 Example:

text = "42".zfill(5) # Results in "00042"


24. format()

 Purpose: Formats the string using placeholders.


 Example:

text = "Hello, {}".format("Alice") # Results in "Hello, Alice"


25. partition()

 Purpose: Splits the string into three parts: before the separator, the separator, and after the separator.
 Example:

parts = "Hello, World!".partition(", ") # Results in ('Hello', ', ', 'World!')


26. expandtabs()

 Purpose: Replaces all tabs in the string with spaces.


 Example:

text = "Hello\tWorld".expandtabs(4) # Results in "Hello World"


Summary

These are some of the most commonly used string functions in Python, and they cover a wide range of string
manipulation needs. Each function provides a specific utility, making it easier to work with and process text data. If
you have any specific use cases or need more examples

✓ Pattern Searching

✓ Replacing and removing substrings

✓ Working with Slice Operator

✓ Applying Slice Operators in Lists and Tuples

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

String manipulation in Python involves working with and modifying text data. Here’s a guide to some common string
operations and techniques:
1. Basic String Operations

 Creating Strings:

my_string = "Hello, World!"

 Concatenation:
o Combine strings using the + operator.

greeting = "Hello"
name = "Alice"
message = greeting + " " + name # Results in "Hello Alice"

 Repetition:
o Repeat strings using the * operator.

repeat = "Hi! " * 3 # Results in "Hi! Hi! Hi! "

 Indexing:
o Access individual characters using zero-based indexing.

char = my_string[0] # Results in 'H'

 Slicing:
o Extract a substring using slicing.

substring = my_string[0:5] # Results in 'Hello'


2. String Methods

 len():
o Get the length of a string.

length = len(my_string) # Results in 13

 strip():
o Remove leading and trailing whitespace.

cleaned_string = " Hello ".strip() # Results in 'Hello'

 lower() and upper():


o Convert to lowercase or uppercase.

lower_case = my_string.lower() # Results in 'hello, world!'


upper_case = my_string.upper() # Results in 'HELLO, WORLD!'

 replace(old, new):
o Replace occurrences of a substring.

new_string = my_string.replace("World", "Alice") # Results in 'Hello, Alice!'

 find(sub):
o Find the index of the first occurrence of a substring.

index = my_string.find("World") # Results in 7

 startswith(prefix) and endswith(suffix):


o Check if a string starts or ends with a specific substring.

starts = my_string.startswith("Hello") # Results in True


ends = my_string.endswith("!") # Results in True
 split(separator):
o Split a string into a list of substrings.

parts = my_string.split(", ") # Results in ['Hello', 'World!']

 join(iterable):
o Join a list of strings into a single string with a specified separator.

joined = ", ".join(['Alice', 'Bob', 'Charlie']) # Results in 'Alice, Bob, Charlie'

 format():
o Format strings using placeholders.

formatted = "Hello, {}!".format("Alice") # Results in 'Hello, Alice!'

 f-Strings (Python 3.6+):


o Use f-strings for embedding expressions inside string literals.

name = "Alice"
f_string = f"Hello, {name}!" # Results in 'Hello, Alice!'
3. String Escaping

 Escape Sequences:
o Use backslashes to include special characters.

quote = "He said, \"Hello!\"" # Results in He said, "Hello!"


newline = "Line1\nLine2" # Results in a string with a newline character
4. String Immutability

 Strings are immutable: Once created, their content cannot be changed. Operations that modify a string actually create
a new string.

Summary

 Concatenation: Combine strings with +.


 Repetition: Repeat strings with *.
 Slicing: Extract substrings with [].
 Methods: Use methods like strip(), replace(), split(), etc.
 Formatting: Use format() or f-strings for dynamic content.

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

FUNCTIONS

✓ Introduction to Functions

Python Functions

A function is a block of code which only runs when it is called.

You can pass data, known as parameters, into a function.


A function can return data as a result.

Creating a Function
In Python a function is defined using the def keyword:

def my_function():
print("Hello from a function")

Calling a Function
To call a function, use the function name followed by parenthesis:

Example
def my_function():
print("Hello from a function")

my_function()

✓ Parameters & arguments in a function

Arguments
Information can be passed into functions as arguments.

Arguments are specified after the function name, inside the parentheses. You can add as many
arguments as you want, just separate them with a comma.

The following example has a function with one argument (fname). When the function is called, we
pass along a first name, which is used inside the function to print the full name:

def my_function(fname):
print(fname + " Refsnes")

my_function("Emil")
my_function("Tobias")
my_function("Linus")

parameters or Arguments?
The terms parameter and argument can be used for the same thing: information that are passed
into a function.

From a function's perspective:

A parameter is the variable listed inside the parentheses in the function definition.

An argument is the value that is sent to the function when it is called.


Number of Arguments
By default, a function must be called with the correct number of arguments. Meaning that if your
function expects 2 arguments, you have to call the function with 2 arguments, not more, and not
less.

Example
This function expects 2 arguments, and gets 2 arguments:

def my_function(fname, lname):


print(fname + " " + lname)

my_function("Emil", "Refsnes")

• Arguments

• Positional arguments

Positional-Only Arguments
You can specify that a function can have ONLY positional arguments, or ONLY keyword arguments.

To specify that a function can have only positional arguments, add , / after the arguments:

Example
def my_function(x, /):
print(x)

my_function(3)

but when adding the , / you will get an error if you try to send a keyword argument:

Example
def my_function(x, /):
print(x)

my_function(x = 3)

• Arguments with default values

✓ Function with return values

✓ Lambda Keyword

✓ Custom Libraries

✓ Custom Packages

You might also like

pFad - Phonifier reborn

Pfad - The Proxy pFad of © 2024 Garber Painting. All rights reserved.

Note: This service is not intended for secure transactions such as banking, social media, email, or purchasing. Use at your own risk. We assume no liability whatsoever for broken pages.


Alternative Proxies:

Alternative Proxy

pFad Proxy

pFad v3 Proxy

pFad v4 Proxy