Py Basic
Py Basic
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)
_1Num
_Num1
Example
#Legal variable names:
myvar = "John"
my_var = "John"
_my_var = "John"
myVar = "John"
MYVAR = "John"
myvar2 = "John"
Example
x = 5
y = "John"
z=3.5
print(type(x))
print(type(y))
print(type(z))
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))
y=”Banana”
z=”Cherry”
name=”aruN”
Mark=780
Percentage=85.5
a, b ,c =20,45,30 20 45 30
print (a,b,c) a b c
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:
Output SARANYA
Example program:
OUTPUT:
Enter your Name,Course separated by space: Ashaz Python
User Details: Ashaz python
# 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
OUTPUT:
Learn python from
G Tech Thirumala
N1 = 20
N2 = 30
Sum=N1+N2
print (Sum) # prints a value
The above print statement receives a variable Sum
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 Numbers
number = 123.456789
formatted_number = f"{number:.2f}" # Formats the number to 2
decimal places
print(formatted_number) # Output: 123.46
number = 123.456789
formatted_number = "{:.2f}".format(number) # Formats the number to 2 decimal places
print(formatted_number) # Output: 123.46
Thousands separator:
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)
name = "Alice"
age = 30
introduction = "My name is {} and I am {} years old.".format(name, age)
print(introduction)
text = "Hello"
formatted_text = f"{text:<10}" # Left-aligns the text within 10 characters
print(formatted_text) # Output: Hello
OPERATORS & EXPRESSIONS
Python Operators
print(10 + 5)
result 15
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:
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
====================
6 =0110
3 =0011
--------------------
7 =0111
--------------------
Left Shift (<<): Shifts the bits of the first operand to the left by the number of positions specified by the second
operand.
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.
Arithmetic operators are used with numeric values to perform common mathematical operations:
Operator Name Example Sample program
y=6
print(x+y)
output 13
y=6
print(x-y)
output 1
y=6
print(x*y)
output 42
y=2
print(x/y)
output 2.5
y=2
print(x%y)
output 1
Python Comparison Operators
Comparison operators are used to compare two values:
== Equal x == y x=5
y=3
print(x == y)
# returns False
because 5 is not equal
to 3
y=7
print(x != y)
y=3
print(x > y)
y=3
print(x < y)
# returns False
because 5 is not less
than 3
print(x >= y)
y=3
print(x <= y)
# returns False
because 5 is neither
less than or equal to 3
Python Logical Operators
x!=10 true
Membership Operators
Membership operators are used to test if a value is presented in a sequence:
print("banana" in x)
print(y not in x)
print("pineapple" not in x)
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
Output:
ADVERTISEMENT
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.
Output :
Compound Interest : 854.375
Write a Python program to find simple interest. Hint: simple interest = principle x rate x time / 100.
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
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.
Syntax:
if expression:
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:
elif expression2:
else:
Example
a =15
b = 15
if a > b:
print("a is greater")
elif a == b:
else:
print("b is greater")
output
both are equal
Nested if
X=14
if x>0:
if x%2==0:
else:
Output
9th
1. Boolean Expressions
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.
Relational operators are used to compare two values and return a Boolean result (True or False). Here’s a list of the
relational operators:
Greater than (>): Checks if the left value is greater than the right.
Less than (<): Checks if the left value is less than the right.
Greater than or equal to (>=): Checks if the left value is greater than or equal to the right.
Less than or equal to (<=): Checks if the left value is less than or equal to the right.
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
✓ 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
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:
Another Example
age = 16
status = "Adult" if age >= 18 else "Minor"
print(status) # Output: Minor
In this case:
Summary
elif n2>n3:
else:
Python Loops
Python has two primitive loop commands:
while loops
for loops
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.
i = 1
while i < 5:
print(i)
if i == 2:
break
i += 1
i = 0
while i < 5:
i += 1
if i == 2:
continue
print(i)
i = 1
while i < 5:
print(i)
i += 1
else:
print("i is no longer less than 5")
✓ For loops
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:
Example
Exit the loop when x is "banana":
Example
Do not print banana:
✓ 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
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:
Example
Increment the sequence with 3 (default is 1):
example:
# 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
4)
names = ['Anna', 'Beth', 'Chad', 'Drew', 'Elsa', 'Fred']
grades = [56, 92, 87, 43, 75, 62]
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)
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
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:
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:
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:
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
✓ List length, membership
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))
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
list = [1, 3, 5, 7, 9]
for i in list:
print(i)
✓ List operations
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
Code:
Output:
8. len()
The len() method returns the length of the list, i.e., the number of elements in the list.
Code:
output
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,
Code:
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
Code:
position
14. sort()
The sort method sorts the list in ascending order. You can only perform this operation on
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:
Output:
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)
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"
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
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)
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:
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
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
✓ 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?
2. Creating a Tuple
my_tuple = (1, 2, 3, 4)
3. Accessing Tuple Elements
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.
tuple1 = (1, 2, 3)
tuple2 = (4, 5, 6)
result = tuple1 + tuple2
print(result) # Output: (1, 2, 3, 4, 5, 6)
my_tuple = (1, 2, 3)
result = my_tuple * 2
print(result) # Output: (1, 2, 3, 1, 2, 3)
a, b, c = (1, 2, 3)
print(a) # Output: 1
print(b) # Output: 2
print(c) # Output: 3
6. Tuple Methods
my_tuple = (1, 2, 2, 3)
count_of_twos = my_tuple.count(2)
print(count_of_twos) # Output: 2
my_tuple = (1, 2, 3, 4)
index_of_three = my_tuple.index(3)
print(index_of_three) # Output: 2
Summary
• Introduction
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:
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
my_set = {1, 2, 3, 4}
my_list = list(my_set) # Converts set to list
3. Adding List Elements to 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)
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)
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)
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
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
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:
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:
5. Set Operations:
o Union: Combine elements from two sets.
o Difference: Get elements in the first set but not in the second.
6. Checking Membership:
o Use the in keyword to check if an element is in the set.
o Example:
7. Set Comprehensions:
o Similar to list comprehensions but for sets.
o Example:
Summary
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
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?
2. Creating a Dictionary
name = my_dict["name"] # Accesses the value associated with the key "name"
4. Adding or Updating Items
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
has_name = "name" in my_dict # Checks if the key "name" exists in the dictionary
7. Iterating Over a Dictionary
8. Dictionary Methods
new_dict = my_dict.copy()
get(key, default): Returns the value for the key, or a default value if the key doesn’t exist.
keys = my_dict.keys()
values = my_dict.values()
items = my_dict.items()
9. Nested Dictionaries
nested_dict = {
"person1": {"name": "Alice", "age": 25},
"person2": {"name": "Bob", "age": 30}
}
Summary
-----------------------------------------------------------------------------------------------------------------
STRING MANIPULATION
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()
python
Copy code
length = len("Hello") # Results in 5
2. str()
python
Copy code
number = 123
text = str(number) # Results in "123"
3. lower()
python
Copy code
text = "Hello".lower() # Results in "hello"
4. upper()
python
Copy code
text = "hello".capitalize() # Results in "Hello"
6. title()
python
Copy code
text = "hello world".title() # Results in "Hello World"
7. strip()
Purpose: Returns the lowest index where the substring is found, or -1 if not found.
Example:
Purpose: Returns the highest index where the substring is found, or -1 if not found.
Example:
Purpose: Similar to find(), but raises a ValueError if the substring is not found.
Example:
Purpose: Joins elements of an iterable (like a list) into a single string with a specified separator.
Example:
Example:
Example:
Example:
Example:
Purpose: Returns True if all characters in the string are alphanumeric (letters and numbers).
Example:
Purpose: Returns True if all alphabetic characters are lowercase (islower()) or uppercase (isupper()).
Example:
Example:
Purpose: Pads the string with zeros on the left to reach a specified length.
Example:
Purpose: Splits the string into three parts: before the separator, the separator, and after the separator.
Example:
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
-----------------------------------------------------------------------------------------------------------
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:
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.
Indexing:
o Access individual characters using zero-based indexing.
Slicing:
o Extract a substring using slicing.
len():
o Get the length of a string.
strip():
o Remove leading and trailing whitespace.
replace(old, new):
o Replace occurrences of a substring.
find(sub):
o Find the index of the first occurrence of a substring.
join(iterable):
o Join a list of strings into a single string with a specified separator.
format():
o Format strings using placeholders.
name = "Alice"
f_string = f"Hello, {name}!" # Results in 'Hello, Alice!'
3. String Escaping
Escape Sequences:
o Use backslashes to include special characters.
Strings are immutable: Once created, their content cannot be changed. Operations that modify a string actually create
a new string.
Summary
------------------------------------------------------------------------------------
FUNCTIONS
✓ Introduction to Functions
Python Functions
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()
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.
A parameter is the variable listed inside the parentheses in the function definition.
Example
This function expects 2 arguments, and gets 2 arguments:
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)
✓ Lambda Keyword
✓ Custom Libraries
✓ Custom Packages