0% found this document useful (0 votes)
6 views29 pages

Ch02 - Python - Variables

The document provides an overview of Python programming concepts, focusing on variables, basic operations, and string manipulation. It explains the definition and types of variables, including integers, floats, strings, and more, as well as various operations such as arithmetic, logical, and membership operations. Additionally, it covers string manipulation techniques like concatenation, formatting, and slicing, along with practical exercises to reinforce the concepts.

Uploaded by

Yuddho Seavminh
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)
6 views29 pages

Ch02 - Python - Variables

The document provides an overview of Python programming concepts, focusing on variables, basic operations, and string manipulation. It explains the definition and types of variables, including integers, floats, strings, and more, as well as various operations such as arithmetic, logical, and membership operations. Additionally, it covers string manipulation techniques like concatenation, formatting, and slicing, along with practical exercises to reinforce the concepts.

Uploaded by

Yuddho Seavminh
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

Python Programming:

Variables, Basic Operations and


String Manipulation

S1, Y2 (2023-2024)

1
Contents
➢What is Variables?
➢Variables and their types in Python
➢Basic operations
• 1. Arithmetic Operations
• 2. Assignment Operation
• 3. Comparison Operations
• 4. Logical Operations
• 5. Membership Operations
➢String manipulation
2
What is Variables?
❖ Variable is a symbolic name or identifier associated with a storage location (memory address) that contains some
known or unknown quantity of information, often referred to as a “value”.
❖ Variables are fundamental to programming because they allow developers to store and manipulate data within a
program.
❖ Key characteristics of variables:
➢ Name: Variables have a name that uniquely identifies them within a program. The name is used to reference
the stored value.
➢ Value: Variables hold a value, which can be of various types such as integers, floats, strings, etc. The value can
change during the execution of a program.
➢ Memory Location: Variables are stored in a specific location in the computer's memory. When you use a
variable in your code, you are essentially referring to the data stored at that memory location.
➢ Type: Variables have a data type that determines the kind of data they can hold (e.g., integer, float, string). In
some languages, like Python, the type is dynamically inferred, while in others, it may need to be explicitly
declared.
➢ Scope: Variables may have different scopes, indicating where in the code they can be accessed. Local variables
are confined to a specific block or function, while global variables can be accessed from anywhere in the
program.
➢ Mutability: Depending on the programming language, variables can be mutable (allow changes) or immutable
(cannot be changed after assignment).
3
What is Variables?
❖In programming languages like Python, the process of creating a variable involves
assigning a value to a name using the assignment operator (=).
❖For example:

➢ x = 42 # Assigning the value 42 to the variable named x

❖In this example, the variable x is assigned the integer value 42. Later in the program,
you can use the variable x to refer to the stored value and perform various operations
with it.
❖Understanding variables is fundamental to writing code because they allow you to
store and manipulate data, making it possible to create dynamic and interactive
programs.

4
Variables and their types in Python
❖In Python, variables are used to store and reference data in a program. Unlike some
other programming languages, Python is dynamically typed, meaning you don't need
to declare the type of a variable explicitly.
❖Here are common variable types in Python:
❖Integers (int):
➢ Whole numbers without decimal points.
➢ Example: x = 10
❖Floats (float):
➢ Numbers with decimal points or in exponential form.
➢ Example: y = 3.14
❖Strings (str):
➢ Sequences of characters enclosed in single or double quotes.
➢ Example: name = "Sok"
5
Variables and their types in Python
❖Here are common variable types in Python:
❖Booleans (bool):
➢ Represents either True or False.
➢ Used in logical operations and conditional statements.
➢ Example: is_valid = True
❖Lists (list):
➢ Ordered, mutable sequences of elements.
➢ Elements can be of different types.
➢ Example: numbers = [1, 2, 3]
❖Tuples (tuple):
➢ Ordered, immutable sequences of elements.
➢ Similar to lists but cannot be modified after creation.
➢ Example: coordinates = (4, 5)

6
Variables and their types in Python
❖Here are common variable types in Python:
❖Dictionaries (dict):
➢ Unordered collection of key-value pairs.
➢ Example: person = {'name': 'Alice', 'age': 25}
❖Sets (set):
➢ Unordered collection of unique elements.
➢ Example: unique_numbers = {1, 2, 3}
❖NoneType (None):
➢ Represents the absence of a value or a null value.
➢ Often used as a default value or to indicate that a variable has no value assigned.
➢ Example: result = None
❖These types cover the basic building blocks of Python variables. When you assign a value
to a variable, Python dynamically determines its type based on the assigned value.
7
Variables and their types in Python
❖Example:

❖It's important to note that variables in Python are case-sensitive (myVar is


different from myvar).
❖Additionally, variable names cannot start with a number and should
follow the conventions outlined in PEP 8 for code style.

8
Basic operations
❖In programming, basic operations refer to the fundamental actions you can perform
on variables and values. These operations are common across many programming
languages and include arithmetic, assignment, comparison, logical, and Membership
operations.
❖Here's an overview of some basic operations:
❖1. Arithmetic Operations:
➢ Addition (+): Adds two values together.
• Example: result = 10 + 5 # result is now 15

➢ Subtraction (-): Subtracts the right operand from the left operand.
• Example: result = 20 - 8 # result is now 12

➢ Multiplication (*): Multiplies two values.


• Example: result = 6 * 3 # result is now 18
9
Basic operations
❖Here's an overview of some basic operations:
❖1. Arithmetic Operations:
➢Division ( / ): Divides the left operand by the right operand.
• Example: result = 15 / 3 # result is now 5.0 (floating-point division)

➢Floor Division ( // ): Divides and rounds down to the nearest integer.


• Example: result = 17 // 5 # result is now 3 (integer division)

➢Modulus (%): Returns the remainder of the division.


• Example: result = 17 % 5 # result is now 2 (remainder of 17 divided by 5)

➢Exponentiation (**): Raises the left operand to the power of the right operand.
• Example: result = 2 ** 3 # result is now 8 (2 to the power of 3)
10
Basic operations
❖Here's an overview of some basic operations:

❖2. Assignment Operation:


➢Assignment (=): Assigns a value to a variable.
• Example: x = 10

➢In-Place Operations (+=, -=, *=, /=): Perform an operation and update the variable
in-place.
• Example: y=5
• y += 3 # Equivalent to y = y + 3, y is now 8

11
Basic operations
❖Here's an overview of some basic operations:
❖3. Comparison Operations:
➢Equality (==): Checks if two values are equal.
• Example: result = (3 == 3) # result is True

➢Inequality (!=): Checks if two values are not equal.


• Example: result = (4 != 7) # result is True

➢Greater Than (>), Less Than (<), Greater Than or Equal To (>=), Less Than or Equal
To (<=): Compare numerical values.
• Example: result = (10 > 5) # result is True
• result = (7 <= 7) # result is True
12
Basic operations
❖Here's an overview of some basic operations:

❖4. Logical Operations:


➢Logical AND (and): Returns True if both conditions are true.
• Example: result = (True and False) # result is False

➢Logical OR (or): Returns True if at least one condition is true.


• Example: result = (True or False) # result is True

➢Logical NOT (not): Inverts the truth value of a condition.


• Example: result = not True # result is False

13
Basic operations
❖Here's an overview of some basic operations:
❖5. Membership Operations:
➢Membership (in): Returns True if a value is found in the sequence.
• Example: result = (2 in [1, 2, 3]) # result is True
➢Not in (not in): Returns True if a value is not found in the sequence.
• Example: result = (4 not in [1, 2, 3]) # result is True
➢Logical NOT (not): Inverts the truth value of a condition.
• Example: result = not True # result is False
❖These basic operations are the building blocks for more complex computations
and control flow in programming. Understanding how to use these operations is
essential for writing effective and expressive code.
14
String manipulation
❖String manipulation is a common and essential task in programming. It involves
working with strings, which are sequences of characters, to modify, analyze, and
manipulate the text.
❖Here are some common string manipulation operations in Python:
❖1. Concatenation:
➢Joining two or more strings together.
➢Example: str1 = "Hello"
• str2 = "World"
• result = str1 + " " + str2 # result is "Hello World“
❖2. Length of a String:
➢Determining the number of characters in a string.
➢Example: text = "Python"
• length = len(text) # length is 6
15
String manipulation
❖Here are some common string manipulation operations in Python:
❖3. String Formatting:
➢Creating formatted strings using placeholders or f-strings.
➢Example: name = "Sopheap"
• age = 30
• result = f"My name is {name} and I am {age} years old.”
• print("My name is {} and I am {} years old.".format("John", 18))

❖4. Slicing Characters:


➢Retrieving characters at specific positions.
➢Example: text = "Python"
• first_char = text[0] # first_char is ‘P’
• first_char = text[0:2] # retrieve 2 chars from index 0-1
16
String manipulation
❖Here are some common string manipulation operations in Python:
❖5. Slicing Characters:
➢Retrieving characters at specific positions.
➢Example: text = "Python"
• first_char = text[0] # first_char is ‘P’
• first_char = text[-1] # first_char is ‘n’
• first_char = text[0:2] # retrieve 2 chars from index 0-1

❖6. Conversion:
➢Converting between uppercase and lowercase.
➢Example: text = "Hello"
• uppercase_text = [Link]() # uppercase_text is "HELLO"
• lowercase_text = [Link]() # lowercase_text is "hello"
17
String manipulation
❖Here are some common string manipulation operations in Python:
❖7. Stripping Whitespace:
➢Removing leading and trailing whitespace.
➢Example: text = " Python "
• stripped_text = [Link]() # stripped_text is "Python“

❖8. Replacing Substrings:


➢Replacing occurrences of a substring with another.
➢Example: text = "I like Java"
• updated_text = [Link]("Java", "Python")
• # updated_text is "I like Python"

18
String manipulation
❖Here are some common string manipulation operations in Python:
❖9. Checking for Substrings:
➢Verifying if a substring is present in a string.
➢Example: text = "Python is fun"
• is_fun_present = "fun" in text # is_fun_present is True
• print([Link](“is”)) # return index, or -1 if not found
❖10. Splitting:
➢Breaking a string into a list of substrings based on a delimiter.
➢Example: sentence = "This is a sentence."
• words = [Link]() # words is ['This', 'is', 'a', 'sentence.’]

❖These are just a few examples of string manipulation operations in Python. The key is to understand the
available string methods and how to use them effectively to achieve the desired results. Python's rich
set of string manipulation functions makes it versatile for working with text data in various applications.
19
Input & Type Conversion
❖Input in Python
➢To interact with the user by use the input() function.
➢The input() function takes a prompt as an argument and returns the
user's input as a string.
user_input = input("Enter your name: ")
❖Type Conversion
➢Python provides built-in functions like int(), float(), str(), etc., for type
conversion.
# Convert string to integer
age_str = input("Enter your age: ")
age = int(age_str)

20
Input & Type Conversion - Example

# Input
name = input("Enter your name: ")
age_str = input("Enter your age: ")

# Type Conversion
age = int(age_str)

# Display
print("Hello,", name + "!")
print("Next year, you'll be", age + 1, "years old.")

21
Exercise 1 – Data Type

# Data Type Exercise

# 1. Create variables of different types: integer, float,


boolean.
integer_var = 42
float_var = 3.14
boolean_var = True

# 2. Print the type of each variable.


print("Type of integer_var:", type(integer_var))
print("Type of float_var:", type(float_var))
print("Type of boolean_var:", type(boolean_var))

22
Exercise 2 - Operators
# Operators Exercise

# 1. Perform arithmetic operations on two variables (addition, subtraction, multiplication, division).


a = 10
b = 5
result_add = a + b
result_sub = a - b
result_mul = a * b
result_div = a / b

# 2. Use in-place operators to modify a variable.


x = 5
x += 3 # equivalent to x = x + 3

# 3. Perform comparison operations and print the result.


comparison_result = a > b

# 4. Use logical operators to combine boolean values.


logical_result = (a > b) and (x < 10)

# 5. Print the results of all the operations.


print("Arithmetic Results:", result_add, result_sub, result_mul, result_div)
print("In-Place Operation Result:", x)
print("Comparison Result:", comparison_result)
print("Logical Result:", logical_result)
23
Exercise 3 – Membership Operation

# Membership Operation Exercise

# 1. Create a list of fruits.


fruits = ["apple", "orange", "banana", "grape"]

# 2. Check if a specific fruit is in the list using membership


operators.
fruit_to_check = "banana"
is_fruit_in_list = fruit_to_check in fruits

# 3. Print the result.


print(f"Is {fruit_to_check} in the list? {is_fruit_in_list}")

24
Exercise 4.1 – String Manipulation
# 1. Create a string.
original_string = "Hello, World!"

# 2. Concatenate the string with another.


concatenated_string = original_string + " Welcome to Python!"
print("Concatenated String:", concatenated_string)

# 3. Use format to insert values into a string.


formatted_string = "My name is {} and I am {} years
old.".format("Alice", 25)
print("Formatted String:", formatted_string)
name = "John"
age = 18
print(f"My name is {name} and I am {age} years old.")

25
Exercise 4.2 – String Manipulation
# 4. Get the length of the string.
string_length = len(original_string)
print("Length of String:", string_length)

# 5. Retrieve a substring.
substring = original_string[7]
substrings = original_string[7:9]
print("Extracted Substring:", substring)
print("Extracted Substring:", substrings)

# 6. Convert the string to uppercase and lowercase.


uppercase_string = original_string.upper()
print("Uppercase String:", uppercase_string)
lowercase_string = original_string.lower()
print("Lowercase String:", lowercase_string)

26
Exercise 4.3 – String Manipulation

# 7. Check if a substring is present in the string.


substring_to_check = "World"
is_substring_present = substring_to_check in original_string
print(f"Is '{substring_to_check}' present in the string? {is_substring_present}")

# 8. Split the string into a list using a delimiter.


split_string = original_string.split(',')
print("Split String:", split_string)

27
Homework 1

28
Thanks for attention,

Any Question?

29

You might also like