Day2-Faciltation Guide (Variables and Operators)
Day2-Faciltation Guide (Variables and Operators)
Index
I. Recap
II. Variables and Constants
III. Python Operators and its Precedence
I. Recap
In our last introductory session we learned:
● Writing programs (or programming) is a very creative and rewarding activity. You
can write programs for many reasons, ranging from making your living to solving
a difficult data analysis problem, to having fun, to helping someone else solve a
problem.
● Computer hardware architecture involves various components to execute and
define a particular task.
● Every programming language has a vocabulary and Grammar.
● Interpreter executes code line by line, whereas the compiler executes the code
as a whole.
● Program is a set of instructions used to execute a particular task.
In this session we are going to learn about Variables and constants,Operators and its
Precedence.
● Mutable: Variables are mutable, which means their values can change during the
program's execution. You can assign different values to a variable as needed.
● Storage: Variables are used to store and manage data that may change or vary
over time. For example, you can use variables to store user input, calculation
results, or intermediate values in your program.
● Declaration: In many programming languages, you need to declare variables
before using them. The declaration specifies the variable's name and data type
Data types
Data types are used to categorize and specify the type of data that a variable can hold
or the type of value that an expression can produce. Data types are essential for
efficient memory allocation, defining the operations that can be performed on the data,
and ensuring type safety.
Common programming languages, including Python, Java, C++, and JavaScript, have
their own data types. Here are some commonly used data types:(e.g., integer, string,
float).
Example :
Constants:
● Immutable: Constants are immutable, meaning their values remain fixed and
cannot be changed once they are assigned.
● Storage: Constants are used to represent values that are known and unchanging
throughout the program. They provide a way to give meaningful names to such
values, enhancing code readability.
● Declaration: Depending on the programming language, constants may require
explicit declaration or follow specific naming conventions (e.g., all uppercase).
Example :
Note: Python does not have built-in support for constants in the same way they do for
variables. In such cases, programmers use naming conventions (e.g., uppercase) to
indicate that a variable's value should not be changed.
Syntax
Python syntax refers to the rules and structure that dictate how Python code should be
written in order for it to be valid and interpretable by the Python interpreter. Proper
adherence to Python syntax is crucial for writing correct and functional Python
programs. Here are some key aspects of Python syntax:
if 10> 5:
print("x is greater than 5")
Naming conventions for variables are vital in programming to create code that is
readable, maintainable, and steady. Different programming languages and groups may
also have slightly various conventions, but a few popular concepts are observed across
many languages. Here are common variable naming conventions.
1. Use Descriptive Names: Choose variable names that clearly and concisely describe
the data they store or represent. Avoid single-letter or cryptic names whenever possible.
● CamelCase: Words are concatenated without spaces, and each word (except
the first) begins with a capital letter. This convention is often used in languages
like Java and JavaScript.
● snake_case: Words are separated by underscores, and all letters are typically
lowercase. This convention is commonly used in Python and some other
languages.
3. Start with a Letter: Variable names must start with a letter (A-Z or a-z) or an
underscore (_) in many programming languages. While some languages allow digits
(0-9) after the first character, it's a good practice to start with a letter.
You can use Python's keyword module to programmatically check and list the reserved
keywords in Python. Here's a Python program to do that:
import keyword
# Get the list of reserved keywords
reserved_keywords = keyword.kwlist
print(reserved_keywords)
`Output:
● Prefix for Booleans: Prefix boolean variables with "is," "has," or a similar word
to indicate their purpose.
● Suffix for Arrays and Collections: You can add a suffix like "_list," "_array," or
"_set" to variables that store collections.
8. Keep Names Concise but Not Too Short: Variable names should be concise and
meaningful but not overly short.
9. Avoid One-Character Names: With rare exceptions (e.g., loop counters in small
scopes), avoid using single-character variable names. Meaningful names are much
more helpful for understanding your code.
Remember that clear and consistent variable naming is a crucial aspect of writing clean,
maintainable, and understandable code. Follow the conventions of the programming
language you're using and consider any specific guidelines or standards used in your
development team or community.
Python Operators :In Python, operators are symbols or special keywords that are used
to perform operations on values or variables. Python provides a wide range of operators
that can be categorized into several groups based on their functionality. Here are some
of the most commonly used operators in Python:
Arithmetic Operators:
● + (Addition): Adds two values.
● - (Subtraction): Subtracts the right operand from the left operand.
● * (Multiplication): Multiplies two values.
● / (Division): Divides the left operand by the right operand.
● % (Modulus): Returns the remainder of the division.
● ** (Exponentiation): Raises the left operand to the power of the right operand.
● // (Floor Division): Returns the integer part of the division result (floor value).
Example:
x = 10
y=3
addition = x + y
division = x / y
modulus = x % y
print(addition)
print(division )
print(modulus)
Comparison Operators
a=5
b = 10
is_equal = (a == b)
is_not_equal = (a != b)
is_less_than = (a < b)
print(is_equal)
print(is_not_equal)
print(is_less_than)
Logical Operators
● and (Logical AND): Returns True if both conditions are True.
● or (Logical OR): Returns True if at least one condition is True.
● not (Logical NOT): Inverts the result of the condition.
Example:
x = True
y = False
result_and = x and y
result_or = x or y
result_not = not x
print(result_and)
print(result_or)
print(result_not)
Assignment Operators:
x=5
x += 2 # Equivalent to x = x + 2
print(x)
a = 5 # Binary: 0101
b = 3 # Binary: 0011
bitwise_and = a & b # Result: 0001 (Decimal: 1)
print(bitwise_and)
Example:
#declare list
fruits = ["apple", "banana", "cherry"]
#Declare string
is_apple_in_list = "apple" in fruits
is_mango_not_in_list = "mango" not in fruits
print(is_apple_in_list)
print(is_mango_not_in_list)
● is (Identity)
● is not (Negated Identity)
Example:
x = [1, 2, 3]
y=x
is_same_object = x is y
print(is_same_object)
Example:
age = 20
is_adult = True if age >= 18 else False
print(is_adult)
These are some of the commonly used operators in Python. Depending on your
programming needs, you'll use various operators to perform operations, comparisons,
and logical evaluations in your code.
Operator precedence
Operators in Python have a specific precedence, which determines the order in which
they are evaluated in an expression. When an expression contains multiple operators,
Python follows the operator precedence rules to determine which operations to perform
first. If needed, you can use parentheses to override the default precedence and
explicitly specify the order of operations.
Here is a summary of common operators in Python and their precedence, from highest
to lowest:
x=5
y = 10
z = 15
result = x < y <= z # Chained comparison operators have left-to-right
precedence
print(result) # Output: True
BODMAS (or PEMDAS in some regions) is an acronym that represents the order of
operations to evaluate mathematical expressions. It stands for:
Expression: 2 * (3 + 4) - 5^2
Result: -11
So, following the BODMAS rule, the value of the expression is -11. This rule ensures
that mathematical expressions are evaluated in a consistent and unambiguous manner.
In each of these examples, the operators are evaluated based on their precedence, and
the expressions are computed accordingly. Understanding operator precedence is
essential to write correct and predictable code, as it helps you avoid unexpected results
or the need for excessive parentheses to clarify the order of evaluation. You can refer to
the documentation of your specific programming language to learn more about operator
precedence rules, as they may vary between languages.
Exercise ChatGPT
1. Hi, can you help me to write a program in Python using a ternary operator to
check whether the given number is even or odd. We need to specify a dummy
number in the code.
2. Please help me with a program in Python to calculate the power of any number.
We need to specify a dummy number in the code.