[go: up one dir, main page]

0% found this document useful (0 votes)
25 views10 pages

Python Lecture II & IIIqkekrk2k1i

The document covers Python programming concepts, focusing on variables, tokens, data types, and lists. It explains Python's keywords, identifiers, literals, operators, and various data types including numeric, sequence, mapping, set, and boolean types. Additionally, it details list operations such as creation, accessing, modifying, slicing, and organizing elements, along with best practices to avoid common errors.

Uploaded by

bonedobnd
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
25 views10 pages

Python Lecture II & IIIqkekrk2k1i

The document covers Python programming concepts, focusing on variables, tokens, data types, and lists. It explains Python's keywords, identifiers, literals, operators, and various data types including numeric, sequence, mapping, set, and boolean types. Additionally, it details list operations such as creation, accessing, modifying, slicing, and organizing elements, along with best practices to avoid common errors.

Uploaded by

bonedobnd
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 10

Python Lecture II AND III

Variable

Data/Values can be stored in temporary storage areas called variables. Each variable is associated with a data type
for example:

var1=”John”

type(var1)

Print(var1)

Python Tokens

Smallest meaningful components in a program

1. Keywords
2. Identifiers
3. Literals
4. Operators

Keywords: Keywords are special reserved words

False Class Finally Is Return


None Def For Lambda Try
True Continue From Nonlocal While
And Del Global Not With
As Elif If Or Yield

Identifiers: Identifiers are names used for variables, functions or objects

Rule

1. No special character except _(underscore)


2. Identifiers are case sensitive
3. First letter cannot be digit

Literals: Literals are constants in Python

Operator

In Python, operators are special symbols or keywords used to perform operations on variables and values. Python
supports various types of operators, each designed for different kinds of operations. Here's a breakdown of the main
categories of operators in Python:

1. Arithmetic Operators

These operators are used to perform mathematical operations.

Operator Description Example


Operator Description Example
+ Addition x+y
- Subtraction x-y
* Multiplication x*y
/ Division x/y
% Modulus (remainder) x%y
** Exponentiation x ** y
// Floor Division x // y

2. Comparison Operators

These operators compare two values and return a Boolean (True or False).

Operator Description Example


== Equal to x == y
!= Not equal to x != y
> Greater than x>y
< Less than x<y
>= Greater than or equal to x >= y
<= Less than or equal to x <= y

3. Assignment Operators

These operators are used to assign values to variables.

Operator Description Example


= Assignment x=y
+= Add and assign x += y
-= Subtract and assign x -= y
*= Multiply and assign x *= y
/= Divide and assign x /= y
%= Modulus and assign x %= y
**= Exponent and assign x **= y
//= Floor divide and assign x //= y

4. Logical Operators

These operators are used to perform logical operations.

Operator Description Example


and Logical AND x and y
or Logical OR x or y
not Logical NOT not x

Examples:
Arithmetic Operator Example

a = 10

b=3

type(a)

type(b)

print(a + b) # Output: 13

print(a / b) # Output: 3.3333333333333335

print(a // b) # Output: 3 (floor division)

Comparision Operator Example

x=5

y = 10

print(x > y) # Output: False

print(x <= y) # Output: True

Logical Operator Example

x = True

y = False

type(x)

type(y)

print(x and y) # Output: False

print(x or y) # Output: True

print(not x) # Output: False

Data Types In Python

Python has several built-in data types that are used to store and manipulate data. These data types can be broadly
categorized into various types, including numeric types, sequence types, set types, mapping types, and more. Here's
an overview of the key data types in Python:

1. Numeric Types

 int (Integer): Represents whole numbers, positive or negative, without decimals. There is no limit to the
size of an integer in Python.

x = 10
y = -3

z = 1234567890123456789

 float (Floating Point): Represents real numbers with a decimal point. It can also represent numbers in
scientific notation.

a = 3.14

b = -0.001

c = 2.5e2 # 2.5 * 10^2 = 250.0

 complex (Complex Numbers): Represents complex numbers, which are written in the form a + bj,
where a is the real part and b is the imaginary part.

num = 2 + 3j

2. Sequence Types

 str (String): Represents a sequence of characters enclosed in single, double, or triple quotes. Strings are
immutable.

s1 = 'Hello'

s2 = "World"

s3 = '''This is a

multi-line string'''

 list: Represents an ordered, mutable sequence of elements, which can be of different types.
my_list = [1, 2, 3, 'a', 'b', 'c']
my_list[0] = 10 # Modifying an element
 tuple: Represents an ordered, immutable sequence of elements, which can be of different types.
my_tuple = (1, 2, 3, 'a', 'b', 'c')
 range: Represents an immutable sequence of numbers, commonly used in loops
r = range(0, 10, 2) # Start at 0, up to 10, with a step of 2

3. Mapping Type

 dict (Dictionary): Represents a collection of key-value pairs, where keys are unique and are used to
retrieve the corresponding values. Dictionaries are mutable.

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

my_dict['age'] = 26 # Modifying a value

4. Set Types

 set: Represents an unordered collection of unique elements. Sets are mutable.


my_set = {1, 2, 3, 4, 5}

my_set.add(6) # Adding an element

 frozenset: Represents an immutable set, where elements cannot be changed once assigned.
my_frozenset = frozenset([1, 2, 3, 4, 5])

5. Boolean Type

 bool: Represents one of two values: True or False. Booleans are a subclass of integers.

is_active = True

is_deleted = False

LECTURE III

A list in Python is a versatile data structure that allows you to store an ordered collection of items, which
can be of different data types. Lists are mutable, meaning that their elements can be changed, added, or
removed after the list has been created.

Creating a List

You can create a list by placing all the items (elements) inside square brackets [], separated by
commas

# Creating a list

my_list = [1, 2, 3, "apple", True]

Accessing Elements in a List

You can access elements in a list using indexing, starting from 0.

# Accessing elements

print(my_list[0]) # Outputs: 1

print(my_list[3]) # Outputs: apple

Changing Elements in a List

You can change the value of an element by assigning a new value to a specific index.

# Changing an element
my_list[1] = "orange"

print(my_list) # Outputs: [1, 'orange', 3, 'apple', True]

Adding Elements to a List

You can add elements to a list using methods like append(), insert(), or by using the +
operator.

 append(): Adds an element to the end of the list.

my_list.append("banana")

print(my_list) # Outputs: [1, 'orange', 3, 'apple', True, 'banana']

 insert(): Inserts an element at a specific position in the list.

my_list.insert(2, "grape")

print(my_list) # Outputs: [1, 'orange', 'grape', 3, 'apple', True, 'banana']

 + Operator: Concatenates two lists.

my_list = my_list + ["cherry", "pear"]

print(my_list) # Outputs: [1, 'orange', 'grape', 3, 'apple', True, 'banana', 'cherry', 'pear']

Removing Elements from a List

You can remove elements from a list using methods like remove(), pop(), or del.

 remove(): Removes the first occurrence of a specific value.

my_list.remove("apple")

print(my_list) # Outputs: [1, 'orange', 'grape', 3, True, 'banana', 'cherry', 'pear']

 pop(): Removes and returns an element at a given index. If no index is specified, it removes the
last item.

popped_element = my_list.pop(2)

print(popped_element) # Outputs: grape

print(my_list) # Outputs: [1, 'orange', 3, True, 'banana', 'cherry', 'pear']

 del: Deletes an element at a specific index or the entire list.


del my_list[1]

print(my_list) # Outputs: [1, 3, True, 'banana', 'cherry', 'pear']

# Deleting the entire list

del my_list

Slicing Lists

Slicing a List

Slicing allows you to access a portion/ subset of the list.

 Syntax: list[start:end:step]

my_list = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]

# Slicing examples

print(my_list[2:5]) # Outputs: [2, 3, 4]

print(my_list[:3]) # Outputs: [0, 1, 2]

print(my_list[7:]) # Outputs: [7, 8, 9]

print(my_list[::2]) # Outputs: [0, 2, 4, 6, 8]

Checking if an Element Exists in a List

You can check if an element exists in a list using the in keyword. if "banana" in my_list:

print("Yes, 'banana' is in the list")

Length of a List

You can get the number of elements in a list using the len() function.

print(len(my_list)) # Outputs: 6
Organizing a List

You can organize or sort a list in various ways:

 sort() Method: Sorts the list in ascending order by default.

my_list = [4, 1, 3, 2, 5]

my_list.sort()

print(my_list) # Outputs: [1, 2, 3, 4, 5]

 sort(reverse=True): Sorts the list in descending order.

my_list.sort(reverse=True)

print(my_list) # Outputs: [5, 4, 3, 2, 1]

 sorted() Function: Returns a new sorted list without changing the original list.

new_list = sorted(my_list)

print(new_list) # Outputs: [1, 2, 3, 4, 5]

Avoiding Index Errors

To avoid IndexError, which occurs when you try to access an index that doesn't exist, you
should always ensure that the index you're accessing is within the range of the list.

 Using len(): Check the length of the list before accessing an index.

my_list = [1, 2, 3]

index = 3 # This index is out of range for a list of length 3

if index < len(my_list):

print(my_list[index])

else:
print("Index out of range")

Looping Through an Entire List

You can loop through a list using a for loop:

my_list = [1, 2, 3, 4, 5]

# Looping through the list

for item in my_list:

print(item)

Avoiding Indentation Errors

Indentation is crucial in Python, as it defines the structure of your code. Here's how to avoid
indentation errors:

 Consistent Indentation: Use the same number of spaces (usually 4) for each indentation
level.
 Avoid Mixing Tabs and Spaces: Stick to either spaces or tabs, but do not mix them.

my_list = [1, 2, 3, 4, 5]

# Correct indentation

for item in my_list:

if item % 2 == 0:

print(f"{item} is even")

else:

print(f"{item} is odd")

# Incorrect indentation (would cause an error)

# for item in my_list:


# if item % 2 == 0:

# print(f"{item} is even")

# else:

# print(f"{item} is odd")

Making a Numerical List

You can create a list of numbers using a for loop or the range() function.

 Using range(): Generates a sequence of numbers.

numerical_list = list(range(1, 11))

print(numerical_list) # Outputs: [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]

You might also like