Unit 2 Python Programming Basics
Unit 2 Python Programming Basics
Comments:
In Python, you can add comments to your code using the '#' symbol. Any text after the '#' symbol in a
line of code will be ignored by the interpreter. Comments can be used to explain the purpose of your
code, add notes to yourself or other developers, or disable lines of code without deleting them.
Example:
# This is a comment
Indentations:
In Python, indentations are used to define blocks of code. Code blocks are defined by the same level of
indentation. Indentation is typically 4 spaces or 1 tab, and it is recommended to stick to one or the other
throughout your code.
Example:if x > 5:
else:
Operators:
Python has a wide range of operators that can be used for arithmetic, comparison, logical operations,
and more.
Arithmetic operators:
+ Addition
- Subtraction
* Multiplication
/ Division
Assignments
Python are used to give a name (or a variable) to a value. For example, if you wanted to store the
value 5 in a variable called "x", you would use the assignment operator "=" like this: x = 5. Now,
you can use the variable "x" in your code to refer to the value 5.
Example:
▪ In these examples, the value on the right side of the = operator is assigned to the variable on the
left side of the = operator.
Assignments can also be done using compound operators that combine an arithmetic operation
with an assignment. Here are some examples:
x=5
y = 10
z=3
▪ In these examples, the compound operators (+=, -= and *=) combine an arithmetic operation
with an assignment. For example, x += 2 is equivalent to x = x + 2, which assigns the value 7 to x.
Expressions
1. Simple expressions:
Example:
x=5
# A variable is an expression
y=x+2
z = abs(-3)
In these examples, x, y, and z are all expressions. x is a simple expression, since it is just a single
value. y is a more complex expression, since it involves a variable (x) and an operator (+). z
involves a function call (abs(-3)), which returns a value that is assigned to z.
2. Arithmetic expressions:
Example:
# Addition
x=5+3
# Subtraction
y = 10 - 2
# Multiplication
z=3*4
# Division
w = 20 / 5
# Exponentiation
v = 2 ** 3
▪ In these examples, each expression involves one or more arithmetic operators. For example, x =
5 + 3 adds the values 5 and 3 together, and assigns the result (8) to the variable x.
3. Comparison expressions:
Example:
# Equal to
x = 5 == 5
# Not equal to
y = 10 != 5
# Greater than
z=3>2
# Less than
w = 20 < 30
v = 5 >= 3
u = 10 <= 10
▪ In these examples, each expression involves a comparison operator that compares two
values and returns a Boolean value (True or False). For example, x = 5 == 5 compares the
values 5 and 5, and assigns the result (True) to the variable x.
4. Logical expressions:
Example:
# Logical AND
# Logical OR
y = True or False
# Logical NOT
z = not True
▪ In these examples, each expression involves one or more logical operators. For example,
x = True and False uses the logical AND operator to combine the Boolean values True
and False, and assigns the result (False) to the variable x.
5. Conditional expressions:
Example:
# Ternary operator
x = 10 if 5 > 3 else 2
# If-else statement
if 5 > 3:
y = 10
else:
y = 20
▪ In these examples, conditional expressions are used to assign values to variables based
on certain conditions. For example, x = 10 if 5 > 3 else 20 assigns the value 10 to x if the
condition 5 > 3 is True, and 20 otherwise. The if-else statement in the second example
does the same thing, but uses a block of code to determine the value to be assigned to
y.
▪ These are just a few examples of expressions in Python. Expressions are a fundamental
concept in programming and understanding how they work is important for writing
effective code.
Data Type:
In programming, a data type is a classification of data that determines the type of operations that can be
performed on it and the values that it can hold. Different programming languages support different
types of data, but here are some common data types:
1. Integers: Integers are whole numbers, such as -3, -2, -1, 0, 1, 2, 3, etc. They are typically used to
represent counts or numerical values.
Example:
# Addition of integers
x=5
y = 10
result = x + y
print(result) # Output: 15
# Division of integers
x = 20
y=3
result = x / y
2. Floats: Floats (or floating-point numbers) are decimal numbers, such as 3.14, -0.25, or 1.0. They
are typically used to represent values that can have decimal places.
Example:
# Addition of floats
x = 3.14
y = 2.5
result = x + y
# Division of floats
x = 10.0
y = 3.0
result = x / y
3. Strings: Strings are sequences of characters, such as "hello" or "world". They are typically used
to represent text or other types of data that can be represented as a sequence of characters.
Example:
# Concatenation of strings
x = "Hello"
y = "world"
# String slicing
x = "Hello world"
result = x[0:5]
4. Booleans: Booleans are logical values that can be either True or False. They are typically used to
represent the truth value of an expression.
Example:
# Boolean expressions
x=5
y = 10
result = x > y
# Boolean operators
x = True
y = False
result = x and y
5. Lists: Lists are ordered collections of elements, such as [1, 2, 3] or ["apple", "banana", "orange"].
They are typically used to store a sequence of related values.
Example:
# Creating a list
fruits[1] = "kiwi"
6. Dictionaries: Dictionaries are unordered collections of key-value pairs, such as {"name": "John",
"age": 30}. They are typically used to store related data in a structured format.
Example:
# Creating a dictionary
person["age"] = 35
7. Tuples: Tuples are similar to lists, but they are immutable (i.e., their values cannot be changed
once they are defined). They are typically used to store a fixed set of values.
.Example:
# Creating a tuple
Selection Control
In Python, selection control is a programming construct that allows you to execute certain code blocks
based on certain conditions. This is typically achieved using if, elif, and else statements.
The basic idea behind selection control is to have the program check if a certain condition is true, and if
it is, execute a specific code block. If the condition is false, the program can either execute a different
code block or simply move on to the next line of code.
Selection control is a programming language construct that allows a program to execute different blocks
of code depending on whether certain conditions are true or false. Here are the details of selection
control:
1. If statement: The if statement is the most basic selection control statement. It allows a program
to execute a block of code if a particular condition is true. The syntax of an if statement is as
follows:
Example:
x = 10 if x > 5:
In this example, the if statement checks if x is greater than 5. If the condition is true, the code inside the
if statement (in this case, printing the string "x is greater than 5") will be executed.
2. If-else statement: The if-else statement allows a program to execute one block of code if a
particular condition is true, and another block of code if the condition is false. The syntax of an
if-else statement is as follows:
Example:
x=3
if x > 5:
else:
print("x is less than or equal to 5")
In this example, the if statement checks if x is greater than 5. If the condition is true, the first
code block will be executed. If the condition is false, the code inside the else statement (in this
case, printing the string "x is less than or equal to 5") will be executed.
3. Nested if-else statement: The nested if-else statement is used when multiple conditions need
to be checked. It consists of one if statement inside another. The syntax of a nested if-else
statement is as follows:
Example:
x = 10
y=5
if x > 5:
if y > 2:
else:
else:
In this example, the outer if statement checks if x is greater than 5. If the condition is true, the
code inside the if statement will be executed, which includes a nested if-else statement that
checks if y is greater than 2. If y is greater than 2, the code inside the first if block (in this case,
printing the string "y is greater than 2") will be executed. If y is less than or equal to 2, the code
inside the else block (in this case, printing the string "y is less than or equal to 2") will be
executed.
If the condition in the outer if statement is false, the code inside the else block (in this case,
printing the string "x is less than or equal to 5") will be executed.
4. Switch statement: The switch statement is used when a program needs to execute different
blocks of code based on the value of a variable or expression. The syntax of a switch statement
is as follows:
Example:
int day = 3;
switch (day) {
case 1:
System.out.println("Monday");
break;
case 2:
System.out.println("Tuesday");
break;
case 3:
System.out.println("Wednesday");
break;
default:
System.out.println("Invalid day");
▪ In this example, the switch statement checks the value of the day variable and executes
the code block associated with that value. In this case, the output would be
"Wednesday" because day is set to 3. If day had been set to a value other than 1, 2, or 3,
the code inside the default block would have been executed.
▪ These are just a few examples of selection control constructs. There are many more
ways to use selection control in programming languages.
5. Ternary operator: The ternary operator is a shorthand way of writing an if-else statement. It
consists of a single line of code that evaluates a condition and returns one value if the condition
is true, and another value if the condition is false. The syntax of a ternary operator is as follows:
▪ In summary, selection control allows a program to execute different blocks of code based on
certain conditions. The most common selection control statements are the if, if-else, nested
if-else, switch, and ternary statements.
Iterative Control
Iterative control is a programming language construct that enables a program to repeat a set of
instructions multiple times until a certain condition is met. This allows programs to perform repetitive
tasks without requiring the developer to write the same code over and over again.
1. for loops: A for loop repeats a set of instructions a specific number of times. The number of
times the loop repeats is determined by the size of a specified collection, such as a list or an
array.
Example:
Here's an example of a for loop in Python that iterates over a list of numbers and prints each number:
numbers = [1, 2, 3, 4, 5]
print(num)
In this example, the for loop iterates over the numbers list and prints each number.
2. while loops: A while loop repeats a set of instructions until a specific condition is met. The loop
will continue to execute as long as the condition is true.
Example:
Here's an example of a while loop in Python that repeatedly asks the user to enter a number until a valid
input is provided:
while True:
try:
break
except ValueError:
▪ These are just a few examples of iterative control constructs. There are many more ways to use
iterative control in programming languages.