python notes
python notes
In Python, the `print()` func on is used to output text or other data to the console. It is a built-in
func on and is commonly used for debugging, displaying informa on to the user, or simply prin ng
the results of a program. Here's a basic explana on of how the `print()` func on works:
1. Basic Usage:
print("Hello, World!")
In this example, the `print()` func on is used to display the string "Hello, World!" in the console. You
can also print variables, expressions, and mul ple items by separa ng them with commas:
name = "Alice"
age = 30
Forma ng Output:
The `print()` func on supports various forma ng op ons, allowing you to control how the output is
presented. Some examples include:
1. String Concatena on
Let's break down the code `print("Hello" + " " + "World!")` in detail:
a . Strings
- `"Hello"` and `"World!"` are string literals in Python. Strings are sequences of characters and can
contain le ers, numbers, symbols, and spaces.
- The `+` operator is used for string concatena on, which means joining two or more strings
together. In this case, the code is concatena ng three strings: `"Hello"`, a space (`" "`) and `"World!"`.
c. Result of Concatena on:
- The result of the concatena on is a single string: `"Hello World!"`. The space (`" "`) between
`"Hello"` and `"World!"` ensures that there is a space separa ng the words in the final output.
- The `print()` func on is a built-in func on in Python used to display output on the console.
- The `print("Hello" + " " + "World!")` statement prints the result of the string concatena on to the
console.
f. Output:
Hello World!
The concatenated string is printed to the console, with a space between "Hello" and "World!".
**Alterna ve Approaches:**
- The same result could be achieved using different approaches, such as using commas to separate
items in the `print()` func on:
print("Hello", "World!")
Or using an f-string:
print(f"Hello World!")
In summary, the code combines the strings "Hello", a space, and "World!" using the `+` operator, and
then prints the resul ng string using the `print()` func on, producing the output "Hello World!".
2. String Interpola on (using f-strings):
name = "Bob"
age = 25
Let's break down the code `print(f"Name: {name}, Age: {age}")` in detail:
name = "Bob"
age = 25
a. Variables:
- `name` is a variable assigned the value `"Bob"`. It stores a string represen ng a person's name.
- `age` is a variable assigned the value `25`. It stores an integer represen ng a person's age.
- The `f` prefix before the string indicates that it is an f-string, also known as a forma ed string
literal. F-strings allow for the embedding of expressions inside string literals.
- Inside the f-string, expressions enclosed in curly braces `{}` are evaluated, and their values are
inserted into the string at those posi ons.
- The `print(f"Name: {name}, Age: {age}")` statement prints a forma ed string to the console. The
expressions within curly braces (`{}`) are replaced with the values of the corresponding variables.
e. Output:
**Advantages of f-Strings:**
- They allow direct embedding of variable values, making the code more expressive and reducing
the need for explicit conversions.
**Alterna ve Approaches:**
- The same result could be achieved using other string forma ng methods, such as:
In summary, the code uses an f-string to create a forma ed string that includes the values of the
`name` and `age` variables, and then it prints this forma ed string to the console. The output is a
string that provides informa on about a person's name and age.
name = "Charlie"
age = 35
Let's break down the code `print("Name: {}, Age: {}".format(name, age))` in detail:
a. Variables:
- `name` is a variable assigned the value `"Charlie"`. It stores a string represen ng a person's name.
- `age` is a variable assigned the value `35`. It stores an integer represen ng a person's age.
c. `.format()` Method:
- The `.format()` method is called on the string `"Name: {}, Age: {}"`. It is used for forma ng the
string by replacing the curly braces with the values provided in the `format()` method.
- Inside the `.format()` method, the values of the variables `name` and `age` are passed. These
values will replace the corresponding curly braces in the original string.
- The `print("Name: {}, Age: {}".format(name, age))` statement prints the forma ed string to the
console. The values of `name` and `age` are inserted into the string at the specified posi ons.
f. Output:
The forma ed string is printed to the console, with the values of the variables `name` and `age`
inserted at the specified posi ons.
**Alterna ve Approaches:**
- The same result could be achieved using other string forma ng methods, such as:
- Using f-strings:
In summary, the code uses the `.format()` method for string forma ng to create a forma ed string
that includes the values of the `name` and `age` variables. It then prints this forma ed string to the
console, resul ng in output that provides informa on about a person's name and age.
4. Output to File:
You can also redirect the output to a file by using the `file` parameter:
The code you provided uses the `with open(...)` statement to open a file named "output.txt" in write
mode (`"w"`), and then it uses the `print()` func on to write a string to that file. Let's break it down:
- The `with` statement in Python is used to manage resources, such as files. In this case, it is
opening the file "output.txt" in write mode (`"w"`).
b. `as file`:
- The `as file` part is assigning the opened file to the variable named `file`. This allows you to
interact with the file through the `file` variable within the indented block.
- The `print()` func on is used to write the specified string to the file. The `file` parameter is used to
specify the file to which the output should be directed.
d. File Content:
- The content wri en to the file "output.txt" will be the string "This will be wri en to the file."
- The `"w"` mode in the `open()` func on stands for write mode. If the file "output.txt" already
exists, it will be truncated (emp ed), and if it doesn't exist, a new file will be created.
**Alterna ve Approach:**
- The same result could be achieved using the `write()` method directly on the file object:
In summary, this code opens the file "output.txt" in write mode, writes the specified string to the file
using the `print()` func on, and then automa cally closes the file. It's a common and concise way to
write content to a file in Python.
5. End Parameter:
print("World!")
Let's break down the code `print("Hello", end=" ")` and `print("World!")` in detail:
- The first `print()` statement prints the string "Hello" to the console.
- The `end=" "` argument specifies that, instead of the default newline character (`\n`) at the end of
the printed content, a space character should be used.
- The `end=" "` parameter determines what character is printed at the end of the `print()`
statement. In this case, it's a space.
- The output of the first `print()` statement will be: `Hello ` (with a space at the end).
d. `print("World!")`:**
- The second `print()` statement prints the string "World!" to the console.
- Since there is no `end` parameter specified, the default behavior is to add a newline character
(`\n`) at the end.
- The output of the second `print()` statement will be: `World!\n` (with a newline character at the
end).
**Overall Output:**
- When both `print()` statements are executed sequen ally, the combined output will be:
Hello World!
The space from the first `print()` statement seperates "Hello" and "World!" without crea ng a new
line.
**Alterna ve Approach:**
- The same result could be achieved by concatena ng the two strings and using a single `print()`
statement:
```python
```
- The `end` parameter is useful when you want to control the character or sequence of characters
printed at the end of the `print()` statement. It allows you to customize the forma ng of the output.
In summary, this code demonstrates the use of the `print()` func on with the `end` parameter to
print two strings sequen ally with a space separa ng them, and the default newline character a er
the second string. The combined output is "Hello World!" with a space between "Hello" and "World".
By default, `print()` adds a newline character at the end. You can change this behaviour using the
`end` parameter.
6. Separator Parameter:
The `sep` parameter allows you to specify a separator between different items printed.
The `print()` func on is versa le and can be adapted to various output requirements, making it a
fundamental tool for displaying informa on during the development and execu on of Python
programs.
Python Comments
A comment is a part of the coding file that the programmer does not want to execute, rather the
programmer uses it to either explain a block of code or to avoid the execu on of a specific part of
code while tes ng.
Single-Line Comments:
Example 1
Output:
Example 2
Example 3:
print("Python Program")
#print("Python Program")
Output:
Python Program
For mul -line comments or comments that span mul ple lines, you can use triple-quotes (''' or """).
These are o en referred to as docstrings, and they are also used for documenta on purposes.
#If the condi on is false then it will execute another block of code.
p=7
if (p > 5):
else:
Output:
p is greater than 5.
p=7
if (p > 5):
else:
Output
p is greater than 5.
'''
'''
"""
"""
"""
It provides informa on about the func on's purpose, parameters, and return values.
"""
Pass
It's important to note that while triple-quotes are o en used for comments, they are also
used for docstrings, which are a form of documenta on. Docstrings are typically used to
provide informa on about modules, classes, func ons, or methods.
Choose the appropriate style based on the context. Single-line comments are suitable for
short, inline explana ons, while docstrings are more appropriate for detailed
documenta on.
An escape sequence character is a backslash \ followed by the character you want to insert.
Escape sequences in Python are special characters that are preceded by a backslash (\). These
sequences are used to represent characters that are difficult to type directly, such as newline
characters, tabs, or special characters.
An example of a character that cannot be directly used in a string is a double quote inside a string
that is surrounded by double quotes:
1. `\n`: Newline
2. `\t`: Tab
print("First\tSecond\tThird")
print("Hello\rWorld")
4. `\\`: Backslash
- Used to represent literal single and double quote characters within strings.
print("Beep!\a")
7. `\b`: Backspace
print("Back\bSpace")
8. `\f`: Formfeed
- Used to represent Unicode characters. `\u` is followed by four hexadecimal digits, and `\U` is
followed by eight hexadecimal digits.
These escape sequences are helpful for crea ng strings with specific forma ng, handling special
characters, or producing certain visual effects. Keep in mind that the interpreta on of escape
sequences may vary based on the context in which they are used.
More on Print statement
The syntax of a print statement looks something like this:
1. object(s): Any object, and as many as you like. Will be converted to string before printed
2. sep='separator': Specify how to separate the objects, if there is more than one. Default is ' '
3. end='end': Specify what to print at the end. Default is '\n' (line feed)
4. file: An object with a write method. Default is sys.stdout
The `print()` func on in Python is used to display output to the console or write it to a file. The
func on has the following signature:
print(object(s), sep=separator, end=end, file=file, flush=flush) # this code will not run. It is just a
format of code
- `object(s)` (Required):
- This represents the object or objects you want to print. You can provide one or more objects,
separated by commas. These objects will be converted to strings and concatenated to form the final
output.
- `sep` is the separator between the objects. It specifies how the objects passed to `print()` should
be separated in the output. The default is a space character. You can change it to any string.
- `end` is the string that is printed at the end of the line. By default, it is a newline character (`'\n'`),
which means each call to `print()` will start a new line. You can change it to any string.
- If `flush` is `True`, the output buffer is forcibly flushed. This means that the printed text will be
wri en to the output immediately. The default is `False`, which allows the system to decide when to
flush the output.
### Example:
name = "John"
age = 30
# Using print() with mul ple objects and custom separator and end
In this example, the `print()` func on is used to print mul ple objects (`"Name:"`, `name`, `"Age:"`,
`age`) with a custom separator (`" | "`) and a custom end (`" *** "`).
Remember that the default values for `sep`, `end`, `file`, and `flush` are o en suitable for many cases,
and you may not need to specify them explicitly unless you have specific forma ng or output
requirements.
Variable is like a container that holds data. Very similar to how our containers in kitchen holds sugar,
salt etc Crea ng a variable is like crea ng a placeholder in memory and assigning it some value. In
Python its as easy as wri ng:
a=1
b = True
c = "Harry"
d = None
Data type specifies the type of value a variable holds. This is required in programming to do various
opera ons without causing an error.
Common data types include integers, floats (decimal numbers), strings, booleans, lists, etc.
In python, we can print the type of any operator using type func on:
a=1
print(type(a))
b = "1"
print(type(b))
In Python, text data is represented using the `str` (string) data type. Strings are sequences of
characters and are used to represent textual data. Python's `str` type is versa le and can store a wide
range of characters, including le ers, digits, symbols, and whitespace.
a. Crea ng a String:
In this example, `text` is a variable of type `str`, and it contains the string "Hello, Python!".
gree ng = "Hello"
name = "Alice"
print(full_gree ng)
word = "Python"
d. String Methods:
e. Forma ng Strings:
name = "Bob"
age = 25
print(forma ed_string)
mul line
string."""
print(mul line_text)
Output:
This is a
mul line
string.
g. Raw Strings:
raw_string = r"C:\Users\Alice\Documents"
print(raw_string)
Output:
C:\Users\Alice\Documents
In this example, the `r` before the string indicates a raw string, where backslashes are treated as
literal characters and not as escape characters.
In summary, the `str` type in Python is used to represent text data, and it provides various methods
and opera ons to manipulate and work with strings.
3. Boolean data:
In Python, the boolean data type is used to represent truth values, and it has only two possible
values: `True` and `False`. Booleans are o en used in control flow statements and logical opera ons
to make decisions in a program.
Here are some key points about boolean data types in Python:
a. Boolean Values:
- The boolean literals are `True` and `False`. They are case-sensi ve.
x = True
y = False
b. Comparison Operators:
c. Logical Operators:
- Logical operators (`and`, `or`, `not`) are used to perform logical opera ons, and they return
boolean values.
- In Python, values other than `True` and `False` have truthy or falsy proper es. For example, `0`,
`None`, and empty containers (e.g., empty lists, empty strings) are considered falsy, while non-zero
integers, non-empty containers, and non-empty strings are considered truthy.
- Some func ons and methods return boolean values, such as `isinstance()`.
value = 42
Boolean values are fundamental for controlling the flow of a program, making decisions, and
implemen ng condi onal logic. They are extensively used in `if` statements, loops, and other control
structures to determine the execu on path of a program.
list: A list is an ordered collec on of data with elements separated by a comma and enclosed within
square brackets. Lists are mutable and can be modified a er crea on.
Example:
print(list1)
Output:
a. Lists:
- Lists are mutable sequences, meaning you can modify their elements. They are created using
square brackets `[]` and can contain elements of different data types.
b. Tuples:
- Tuples are immutable sequences, meaning their elements cannot be changed a er crea on. They
are created using parentheses `()` and can also contain elements of different data types.
c. Strings:
- Strings are immutable sequences of characters. They are created using single (`'`) or double (`"`)
quotes.
- Indexing: Elements of a sequence can be accessed using their index. Indexing starts at 0.
- Slicing: You can extract sub-sequences (slices) from a sequence using slicing nota on.
- Concatena on: You can concatenate sequences using the `+` operator.
new_list = my_list + [4, 5, 6]
new_tuple = my_tuple + (4, 5, 6)
repeated_tuple = my_tuple * 3
repeated_string = my_string * 4
- Length: You can find the length of a sequence using the `len()` func on.
length_list = len(my_list)
length_tuple = len(my_tuple)
length_string = len(my_string)
print(length_list)
print(len(my_list))
These sequence types are versa le and are widely used in Python for various purposes. Depending
on the specific requirements of your program, you may choose a list, tuple, or string.
Tuple: A tuple is an ordered collec on of data with elements separated by a comma and enclosed
within parentheses. Tuples are immutable and can not be modified a er crea on.
Example:
print(tuple1)
Output:
dict: A dic onary is an unordered collec on of data containing a key:value pair. The key:value pairs
are enclosed within curly brackets.
Example:
print(dict1)
Output:
A dic onary in Python is an unordered and mutable collec on that is used to store and retrieve data
in a key-value format. Each key in the dic onary must be unique, and it is associated with a specific
value. The key-value pairs in a dic onary allow for efficient and fast retrieval of data.
student_info = {
"name": "Alice",
"age": 25,
"grade": "A",
"subject": "Math"
print("Name:", student_info["name"])
print("Age:", student_info["age"])
print("Grade:", student_info["grade"])
print("Subject:", student_info["subject"])
In this example, `student_info` is a dic onary represen ng informa on about a student. Each piece
of informa on (name, age, grade, subject) is associated with a key, and you can access the values
using those keys.
a.Uniqueness of Keys: Each key in a dic onary must be unique. If you try to use the same key again, it
will overwrite the exis ng value associated with that key.
b. Mutability: Dic onaries are mutable, meaning you can add, modify, or remove key-value pairs.
c. Ordering: Star ng from Python 3.7, dic onaries maintain the order in which items were inserted.
In Python 3.6 and earlier, dic onaries are unordered.
student_info["gender"] = "Female"
# Accessing the updated dic onary
print("Gender:", student_info["gender"])
The concept of mapped data is crucial in scenarios where you need to associate pieces of
informa on (values) with specific iden fiers (keys), allowing for efficient retrieval and manipula on
of data.
In Python, the concepts of local and global variables refer to the scope in which a variable is defined
and can be accessed. The scope defines the region of the code where a variable has visibility and can
be referenced. There are two main types of variable scopes:
- They are only accessible and visible within that func on or block.
- Once the func on or block of code completes its execu on, the local variables are destroyed.
- Local variables are useful for temporary storage of data within a specific context.
Example:
local_var = 10
my_func on()
b. Global Variables:
- Global variables are defined at the top level of a script or module, outside of any func on or
block.
- They are accessible throughout the en re script or module, including within func ons.
- Global variables retain their values as long as the script or module is in execu on.
global_var = 20
my_func on()
global_var = 30
- If a variable is assigned a value within a func on without being declared as `global`, Python
considers it a local variable within that func on.
- If a variable is referenced within a func on and is not found locally, Python looks for it in the
enclosing func on or the global scope.
Best prac ces o en suggest minimizing the use of global variables, as they can make code less
modular and more difficult to understand. Instead, func ons should generally take parameters and
return values, allowing for a more controlled and modular structure.
Operators
Python has different types of operators for different opera ons. To create a calculator we
require arithme c operators.
Arithme c operators
Operator Operator Name Example
+ Addi on 15+7
- Subtrac on 15-7
* Mul plica on 5*7
** Exponen al 5**3
/ Division 5/3
% Modulus 15%7
// Floor Division 15//7
# Example 2
result = 15 % 7
print(result) # Output: 1
The modulus operator is commonly used in programming for various purposes, including:
1. Checking for Even or Odd Numbers:
If n % 2 is 0, then n is an even number; otherwise, it's an odd number.
number = 17 if number % 2 == 0: print(f"{number} is even.") else: print(f"{number} is odd.")
2. Cycling Through Values:
The modulus operator is o en used in cyclic pa erns, such as cycling through
a range of values.
for i in range(10): print(i % 3)
This will output the values 0, 1, 2, 0, 1, 2, 0, 1, 2, 0, represen ng a cyclic pa ern.
3. Exponen a on **:
Raises the le operand to the power of the right operand.
result = 2 ** 3 # result is 8
4. Unary Nega on - (Negate):
Negates the value of the operand.
result = -5 # result is -5
Keep in mind the order of opera ons (PEMDAS/BODMAS) when using mul ple operators in
an expression:
1. Parentheses ()
2. Exponents ** (or pow())
3. Mul plica on *, Division /, Floor Division //, Modulus %
4. Addi on +, Subtrac on –
Exercise
Calculator
n = 15
m=7
ans1 = n+m
print("Addi on of",n,"and",m,"is", ans1)
ans2 = n-m
float_number = 3.14
int_number = int(float_number)
print(int_number) # Output: 3
int_number = 42
float_number = float(int_number)
print(float_number) # Output: 42.0
number = 123
str_number = str(number)
print(str_number) # Output: '123'
text = "Hello"
char_list = list(text)
print(char_list) # Output: ['H', 'e', 'l', 'l', 'o']
my_list = [1, 2, 3]
tuple_version = tuple(my_list)
print(tuple_version) # Output: (1, 2, 3)
Typecasting is useful in situations where you need to ensure that a variable or value is of a s
pecific data type before performing certain operations. It allows you to adapt data to the re
quirements of a particular algorithm or function. However, it's essential to be aware of the p
otential loss of information when converting between certain types (e.g., converting a float t
o an int may result in loss of decimal information).
integer_value = 5
float_value = 3.14
result = integer_value + float_value
print(result) # Output: 8.14 (integer_value is implicitly converted to a float)
6. Boolean Conversion:
- Converting values to boolean.
zero = 0
non_zero = 42
bool_zero = bool(zero) # False
bool_non_zero = bool(non_zero) # True
Understanding these different types of typecasting is essential for writing flexible and robust
Python code, especially when dealing with data of various types.
Typecasting in python
The conversion of one data type into the other data type is known as type casting in python or type
conversion in python.
Python supports a wide variety of functions or methods like: int(), float(), str(), ord(), hex(), oct(), tupl
e(), set(), list(), dict(), etc. for the type casting in python.
Explicit typecasting:
The conversion of one data type into another data type, done via developer or programmer's interve
-ntion or manually as per the requirement, is known as explicit type conversion.
It can be achieved with the help of Python’s built-in type conversion functions such as int(), float(), h
ex(), oct(), str(), etc .
Output:
The Sum of both the numbers is 22
Python converts a smaller data type to a higher data type to prevent data loss.
Ouput:
<class 'int'>
<class 'float'>
10.0
<class 'float'>
or using `argparse`:
import argparse
parser = argparse.ArgumentParser()
parser.add_argument("user_input", help="Enter something")
args = parser.parse_args()
print("You entered:", args.user_input)
5. File Input/Output:
- If you have input stored in a file, you can read it using file I/O func ons like `open()`.
with open("input_file.txt", "r") as file:
user_input = file.readline().strip()
print("You entered:", user_input)
Choose the method that best fits your use case based on simplicity, flexibility, and the nature
of the input you are expec ng. The `input()` func on is commonly used for interac ve user
input scenarios.
Day11: Strings
What are strings?
In python, anything that you enclose between single or double quota on marks is
considered a string. A string is essen ally a sequence or array of textual data. Strings are
used when working with Unicode characters.
Strings are used to represent textual data and are one of the fundamental data types in the
language. Strings in Python are immutable, meaning their values cannot be changed a er
crea on.
Example
a. Crea ng strings: You can create a string by enclosing a sequence of characters in single or
double quotes
name = "Harry"
print("Hello, " + name)
Output
Hello, Harry
Note: It does not ma er whether you enclose your strings in single or double quotes, the
output remains the same.
Some mes, the user might need to put quota on marks in between the strings. Example,
consider the sentence: He said, “I want to eat an apple”.
How will you print this statement in python?:
He said, "I want to eat an apple". We will definitely use single quotes for our convenience
print('He said, "I want to eat an apple".')
e. String Slicing:
You can extract a por on of a string using slicing.
my_string = "Python"
slice_result = my_string[1:4] # 'yth'
first_name = "John"
last_name = "Doe"
full_name = first_name + " " + last_name # 'John Doe'
g. String Methods:
Strings have many built-in methods for various opera ons such as conver ng case, finding
substrings, spli ng, joining, and more.
my_string = "Hello, World!"
print( my_string.upper()) # 'HELLO, WORLD!'
print(my_string.lower()) # 'hello, world!'
print(my_string.find('World')) # 7
age = 25
forma ed_string = "My name is %s and I am %d years old." % (name, age)
Or using format():
forma ed_string = "My name is {} and I am {} years old.".format(name, age)
i. Raw Strings:
Raw strings are prefixed with r and treat backslashes as literal characters, useful for regular
expressions and file paths.
raw_string = r"C:\Users\Username\Documents"
Strings in Python are versa le and widely used for various purposes, including text
processing, data manipula on, and building user interfaces. They provide a rich set of
methods and opera ons to work with textual data efficiently.
name = "Alice"
age = 25
forma ed_string = "My name is %s and I am %d years old." % (name, age)
print(forma ed_string)
- Named Placeholders:
person = {'name': 'Alice', 'age': 25}
forma ed_string = "My name is {name} and I am {age} years old.".format(**person)
This example uses named placeholders with values from a dic onary.
Choose the method that best fits your Python version and coding style. String forma ng is a
powerful feature that allows you to create readable and dynamic output by embedding
values within strings.
Day 12:String Slicing & Opera ons on
String
Length of a String
We can find the length of a string using len() func on.
Example:
fruit = "Mango"
len1 = len(fruit)
print("Mango is a", len1, "le er word.")
Output:
Mango is a 5 le er word.
String as an array
A string is essen ally a sequence of characters also called an array. Thus, we can access the
elements of this array.
Example:
pie = "ApplePie"
print(pie[:5])
print(pie[6]) #returns character at specified index
Output:
Apple
i
Note: This method of specifying the start and end index to specify a part of a string is called
slicing.
Slicing Example:
pie = "ApplePie"
print(pie[:5]) #Slicing from Start
print(pie[5:]) #Slicing ll End
print(pie[2:6]) #Slicing in between
print(pie[-8:]) #Slicing using nega ve index
Output:
Apple
Pie
pleP
ApplePie
substring = my_string[7:12]
print(substring) # Output: World
String slicing is a powerful tool for working with text data in Python, and it provides a
concise and expressive way to manipulate strings.
print(str1.lower())
Output:
Abcdefghij
print(str2.replace("Sp", "M"))
Output:
Silver Moon
split() : format- .split
The split() method splits the given string at the specified instance and returns the seperated
strings as list items.
Example:
str2 = "Silver Spoon"
print(str2.split(" ")) #Splits the string at the whitespace " ".
Output:
['Silver', 'Spoon']
There are various other string methods that we can use to modify our strings.
print(str1.index("Dan"))
Output:
13
As we can see, this method is somewhat similar to the find() method. The major difference
being that index() raises an excep on if value is absent whereas find() does not.
Example:
str1 = "He's name is Dan. Dan is an honest man."
print(str1.index("Daniel"))
Output:
ValueError: substring not found
print(str1.isprintable())
Output:
True
if-else Statements
Some mes the programmer needs to check the evalua on of certain expression(s), whether
the expression(s) evaluate to True or False. If the expression evaluates to False, then the
program execu on follows a different path than it would have if the expression had
evaluated to True.
Based on this, the condi onal statements are further classified into following types:
if
if-else
if-else-elif
nested if-else-elif.
elif Statements
Some mes, the programmer may want to evaluate more than one condi on, this can be
done using an elif statement.
Working of an elif statement
Execute the block of code inside if statement if the ini al expression evaluates to True. A er
execu on return to the code out of the if block.
Execute the block of code inside the first elif statement if the expression inside it evaluates
True. A er execu on return to the code out of the if block.
Execute the block of code inside the second elif statement if the expression inside it
evaluates True. A er execu on return to the code out of the if block.
.
.
.
Execute the block of code inside the nth elif statement if the expression inside it evaluates
True. A er execu on return to the code out of the if block.
Execute the block of code inside else statement if none of the expression evaluates to True.
A er execu on return to the code out of the if block.
Example:
num = 0
if (num < 0):
print("Number is nega ve.")
elif (num == 0):
print("Number is Zero.")
else:
print("Number is posi ve.")
Output:
Number is Zero.
Nested if statements
We can use if, if-else, elif statements inside other if statements as well.
Example:
num = 18
if (num < 0):
print("Number is nega ve.")
elif (num > 0):
if (num <= 10):
print("Number is between 1-10")
# DAY -15
# DAY -16: Match case statement
Match Case Statements
To implement switch-case like characteris cs very similar to if-else func onality, we use a
match case in python. If you are coming from a C, C++ or Java like language, you must have
heard of switch-case statements. If this is your first language, dont worry as I will tell you
everything you need to know about match case statements in this video!
A match statement will compare a given variable’s value to different shapes, also referred to
as the pa ern. The main idea is to keep on comparing the variable with all the present
pa erns un l it fits into one.
The match case consists of three main en es :
1. The match keyword
2. One or more case clauses
3. Expression for each case