0% found this document useful (0 votes)
20 views

python notes

Uploaded by

premprakashsliet
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
20 views

python notes

Uploaded by

premprakashsliet
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 54

Day04: Print func on in python

PRINT () FUNCTION IN PYTHON

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

print("Name:", name, "Age:", age)

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

print("Hello" + " " + "World!")

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.

b. String Concatena on:

- 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.

d. print()` Func on:

- The `print()` func on is a built-in func on in Python used to display output on the console.

e. Prin ng the Result:

- The `print("Hello" + " " + "World!")` statement prints the result of the string concatena on to the
console.

f. Output:

- The output of this code will be:

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 string forma ng:

print("{} {}".format("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

print(f"Name: {name}, Age: {age}")

Let's break down the code `print(f"Name: {name}, Age: {age}")` in detail:

name = "Bob"

age = 25

print(f"Name: {name}, Age: {age}")

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.

b. f-String (Forma ed String Literal):

- 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.

c. String Format Expression:

- Inside the f-string, expressions enclosed in curly braces `{}` are evaluated, and their values are
inserted into the string at those posi ons.

d. Prin ng Forma ed String:

- 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:

- The output of this code will be:

Name: Bob, Age: 25


The f-string is evaluated, and the values of the variables `name` and `age` are inserted into the
string at the specified posi ons.

**Advantages of f-Strings:**

- F-strings provide a concise and readable way to format strings in Python.

- 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:

- Using the `format()` method:

print("Name: {}, Age: {}".format(name, age))

- Using concatena on:

print("Name: " + name + ", Age: " + str(age))

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.

3. Forma ng with the `format()` method:

name = "Charlie"

age = 35

print("Name: {}, Age: {}".format(name, age))

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.

b. String Forma ng:


- The `print()` statement uses string forma ng to create a forma ed string. The string `"Name: {},
Age: {}"` contains placeholder curly braces `{}` that will be replaced with actual values during
forma ng.

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.

d. Values Passed to `.format()`:

- 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.

e. Prin ng Forma ed 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 output of this code will be:

Name: Charlie, Age: 35

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:

print(f"Name: {name}, Age: {age}")

- Using concatena on:

print("Name: " + name + ", Age: " + str(age))

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:

with open("output.txt", "w") as file:

print("This will be wri en to the file.", file=file)

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:

with open("output.txt", "w") as file:

print("This will be wri en to the file.", file=file)

a. `with open(...)` Statement:

- 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.

c. `print("This will be wri en to the file.", file=file)`:

- 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."

e. File Mode (`"w"`):

- 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.

f. Automa c File Closure:


- The use of the `with` statement ensures that the file is properly closed a er the indented block,
even if an excep on occurs during the execu on of the block.

**Alterna ve Approach:**

- The same result could be achieved using the `write()` method directly on the file object:

with open("output.txt", "w") as file:

file.write("This will be wri en to the file.")

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("Hello", end=" ")

print("World!")

Let's break down the code `print("Hello", end=" ")` and `print("World!")` in detail:

a. `print("Hello", end=" ")`:

- 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.

b. Effect of `end=" "`:

- The `end=" "` parameter determines what character is printed at the end of the `print()`
statement. In this case, it's a space.

c. Result of the First `print()`:

- 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.

**Result of the Second `print()`:**

- 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

print("Hello" + " " + "World!")

```

**Use of `end` Parameter:**

- 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:

print("One", "Two", "Three", sep=", ")

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.

Day 5 - Comments, Escape sequence & Print in Python


Welcome to Day 5 of 100DaysOfCode. Today we will talk about Comments, Escape Sequences and
li le bit more about print statement in Python. We will also throw some light on Escape Sequences

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:

To write a comment just add a ‘#’ at the start of the line.

Example 1

#This is a 'Single-Line Comment'

print("This is a print statement.")

Output:

This is a print statement.

Example 2

print("Hello World !!!") #Prin ng Hello World


Output:

Hello World !!!

Example 3:

print("Python Program")

#print("Python Program")

Output:

Python Program

Mul -Line Comments:


To write mul -line comments you can use ‘#’ at each line or you can use the mul line string.

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.

Example 1: The use of ‘#’.

#It will execute a block of code if a specified condi on is true.

#If the condi on is false then it will execute another block of code.

p=7

if (p > 5):

print("p is greater than 5.")

else:

print("p is not greater than 5.")

Output:

p is greater than 5.

Example 2: The use of mul line string.

"""This is an if-else statement.


It will execute a block of code if a specified condi on is true.

If the condi on is false then it will execute another block of code."""

p=7

if (p > 5):

print("p is greater than 5.")

else:

print("p is not greater than 5.")

Output

p is greater than 5.

'''

This is a mul -line comment.

It can span mul ple lines.

'''

"""

Another way to create a mul -line comment.

"""

def my_func on():

"""

This is a docstring for the func on.

It provides informa on about the func on's purpose, parameters, and return values.

"""

# Func on code here

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.

Escape Sequence Characters


To insert characters that cannot be directly used in a string, we use an escape sequence character.

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:

print("This doesnt "execute")

print("This will \" execute")

Here are some common escape sequences in Python:

1. `\n`: Newline

- Used to represent a newline character.

print("Line 1\nLine 2")

2. `\t`: Tab

- Used to represent a horizontal tab.

print("First\tSecond\tThird")

3. `\r`: Carriage Return

- Used to move the cursor to the beginning of the line.

print("Hello\rWorld")

4. `\\`: Backslash

- Represents a literal backslash character.

print("This is a backslash: \\")


5. `\'` and `\"`: Single and Double Quotes

- Used to represent literal single and double quote characters within strings.

print('This is a single quote: \'')

print("This is a double quote: \"")

6. `\a`: Bell (Alert)

- Produces a system-specific alert sound.

print("Beep!\a")

7. `\b`: Backspace

- Moves the cursor back one posi on.

print("Back\bSpace")

8. `\f`: Formfeed

- Advances the cursor to the next page or form.

print("Page 1\fPage 2")

9. `\v`: Ver cal Tab

- Moves the cursor to the next ver cal tab stop.

print("Line 1\vLine 2")

10. `\u` and `\U`: Unicode Escape

- Used to represent Unicode characters. `\u` is followed by four hexadecimal digits, and `\U` is
followed by eight hexadecimal digits.

print("\u03A9") # Omega symbol (Ω)

print("\U0001F609") # Smiling face with smiling eyes 😊

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:

print(object(s), sep=separator, end=end, file=file, flush=flush)

Other Parameters of Print Statement

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

Parameters 2 to 4 are op onal

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

Let's break down the parameters:

- `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` (Op onal, Default is a space):

- `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` (Op onal, Default is a newline character):

- `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.

- `file` (Op onal, Default is `sys.stdout`):


- `file` is the file-like object where the output will be sent. The default is `sys.stdout`, which
represents the standard output (console). You can specify a different file, such as a text file opened in
write mode.

- `flush` (Op onal, Default is `False`):

- 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

print("Name:", name, "Age:", age, sep=" | ", end=" *** ")

# Output will be: Name: | John | Age: | 30 ***

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.

Day 6 - Variables and Data Types


What is a variable?

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

These are four variables of different data types.


What is a Data Type?

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))

By default, python provides the following built-in data types:

1. Numeric data: int, float, complex

 int (Integer type (whole numbers)): 3, -8, 0

 float (Floa ng-point type (decimal numbers)) : 7.349, -9.0, 0.0000001

 complex (Complex numbers with a real and imaginary part): 6 + 2i

2. Text data: str

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.

Here are some examples of working with text data in Python:

a. Crea ng a String:

text = "Hello, Python!"

In this example, `text` is a variable of type `str`, and it contains the string "Hello, Python!".

b. String Concatena on:

gree ng = "Hello"

name = "Alice"

full_gree ng = gree ng + " " + name

print(full_gree ng)

This will output: `Hello Alice`


c. String Indexing and Slicing:

word = "Python"

print(word[0]) # Output: P (first character)

print(word[1:4]) # Output: yth (slicing from index 1 to 3)

d. String Methods:

sentence = "This is a sample sentence."

print(sentence.lower()) # Output: this is a sample sentence.

print(sentence.upper()) # Output: THIS IS A SAMPLE SENTENCE.

print(sentence.split()) # Output: ['This', 'is', 'a', 'sample', 'sentence.']

print(sentence.replace('sample', 'example')) # Output: This is a example sentence.

e. Forma ng Strings:

name = "Bob"

age = 25

forma ed_string = "Name: {}, Age: {}".format(name, age)

print(forma ed_string)

This will output: `Name: Bob, Age: 25`

f. Triple-Quoted Strings (Mul line Strings):

mul line_text = """This is a

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.

str: String type (sequence of characters).

str: "Hello World!!!", "Python Programming"

name = "John" # str

3. Boolean data:

Boolean data consists of values True or False.

Note: In True T is always capital, and in False F is always capital.

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:

- Comparison operators return boolean values. For example:

result = (5 > 3) # result will be True

c. Logical Operators:

- Logical operators (`and`, `or`, `not`) are used to perform logical opera ons, and they return
boolean values.

result_and = True and False # result_and will be False

result_or = True or False # result_or will be True

result_not = not True # result_not will be False


d. Truthy and Falsy 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.

truthy_example = [1, 2, 3] # truthy_example is truthy

falsy_example = [] # falsy_example is falsy

e. Comparison and Equality:

- Comparison and equality operators return boolean values. For example:

result_eq = (10 == 10) # result_eq will be True

result_not_eq = (10 != 5) # result_not_eq will be True

f. Boolean Func ons:

- Some func ons and methods return boolean values, such as `isinstance()`.

value = 42

is_integer = isinstance(value, int) # is_integer will be True

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.

4.Sequenced data: list, tuple

list: List type (ordered, mutable sequence).

tuple: Tuple type (ordered, immutable sequence).

numbers = [1, 2, 3] # list

coordinates = (4, 5) # tuple

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:

list1 = [8, 2.3, [-4, 5], ["apple", "banana"]]

print(list1)

Output:

[8, 2.3, [-4, 5], ['apple', 'banana']]


In Python, sequence data types represent an ordered collec on of items, where each item can be
accessed using its index. Sequences are iterable and support various opera ons like indexing, slicing,
and itera on. The three main built-in sequence data types in Python are:

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.

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

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.

my_tuple = (1, 2, 3, "apple", "banana")

c. Strings:

- Strings are immutable sequences of characters. They are created using single (`'`) or double (`"`)
quotes.

my_string = "Hello, Python!"

These sequence types share common characteris cs and opera ons:

- Indexing: Elements of a sequence can be accessed using their index. Indexing starts at 0.

print(my_list[0]) # Access the first element of the list

print(my_tuple[2]) # Access the third element of the tuple

print(my_string[7]) # Access the eighth character of the string

- Slicing: You can extract sub-sequences (slices) from a sequence using slicing nota on.

print(my_list[1:4]) # Extract a slice from index 1 to 3 (exclusive)

print(my_tuple[:3]) # Extract a slice from the beginning up to index 2

print(my_string[7:]) # Extract a slice from index 7 to the end

- Concatena on: You can concatenate sequences using the `+` operator.
new_list = my_list + [4, 5, 6]
new_tuple = my_tuple + (4, 5, 6)

new_string = my_string + " Welcome!"

- Repe on: Sequences can be repeated using the `*` operator.


repeated_list = my_list * 2

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:

tuple1 = (("parrot", "sparrow"), ("Lion", "Tiger"))

print(tuple1)

Output:

(('parrot', 'sparrow'), ('Lion', 'Tiger'))

5. Mapped data: dict

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:

dict1 = {"name":"Sakshi", "age":20, "canVote":True}

print(dict1)

Output:

{'name': 'Sakshi', 'age': 20, 'canVote': True}


In Python, "mapped data" typically refers to a collec on of key-value pairs where each key is
associated with a specific value. This mapping is implemented using a data structure called a
dic onary, which is denoted by curly braces `{}`.

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.

Here's a simple example of mapped data using a dic onary in Python:

# Crea ng a dic onary (mapped data)

student_info = {

"name": "Alice",

"age": 25,

"grade": "A",

"subject": "Math"

# Accessing values using keys

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.

Key characteris cs of mapped data (dic onary) in Python:

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.

Here's an example of adding a new key-value pair to the dic onary:

# Adding a new key-value pair

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:

Day 07: Calculator using python


a. Local Variables:

- Local variables are defined within a specific func on or block of code.

- 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:

def my_func on():

# This is a local variable

local_var = 10

print("Inside the func on:", local_var)

my_func on()

# This will result in an error because local_var is not accessible here

# print("Outside the func on:", local_var)


Ouput: Inside the function: 10

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.

- Changes made to global variables within a func on are reflected globally.


Example:

# This is a global variable

global_var = 20

def my_func on():

# Accessing the global variable within the func on

print("Inside the func on:", global_var)

my_func on()

# Modifying the global variable

global_var = 30

# Accessing the modified global variable

print("Outside the func on:", global_var)


Output: Inside the function: 20
Outside the function: 30

It's important to note the following:

- 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

1. Floor Division //:


 Divides the le operand by the right operand and returns the floor of the
result (rounded down to the nearest integer).
result = 8 // 3 # result is 2
2. Modulus %:
 Returns the remainder when the le operand is divided by the right operand.
 The modulus operator, denoted by %, is a mathema cal operator in Python
that returns the remainder when one number (dividend) is divided by
another number (divisor). In other words, it calculates the remainder of the
integer division.
result = 8 % 3 # result is 2
# Example 1
result = 10 % 3
print(result) # Output: 1

# 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. Wrapping Around Indices:


 It's used to wrap around indices in circular data structures or arrays.
colors = ["red", "green", "blue"] index = 5 print(colors[index % len(colors)])
In this example, if index is 5, it wraps around to 2 (5 % 3), ensuring it stays within the valid
range for the colors list.
The modulus operator is a versa le tool for handling scenarios where you need to work with
cyclic pa erns, remainders, or wrapping around values.

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

print("Subtrac on of",n,"and",m,"is", ans2)


ans3 = n*m
print("Mul plica on of",n,"and",m,"is", ans3)
ans4 = n/m
print("Division of",n,"and",m,"is", ans4)
ans5 = n%m
print("Modulus of",n,"and",m,"is", ans5)
ans6 = n//m
print("Floor Division of",n,"and",m,"is", ans6)

Day 08: Calculator solu on


# Calculator Solu on
a=50
b=5
print("The value of",a,"+",b,"is:",a+b)
Output:- The value of 50 + 5 is: 55

print("The value of",a,"-",b,"is:",a-b)


Output:- The value of 50 - 5 is: 45

print("The value of",a,"*",b,"is:",a*b)


Output:- The value of 50 * 5 is: 250

print("The value of",a,"/",b,"is:",a/b)


Output:- The value of 50 / 5 is: 10.0
Day09: Typecasting in Python
Typecasting, also known as type conversion, is the process of converting one data type into
another in a programming language. In Python, typecasting allows you to change the data ty
pe of a variable or a value. Python provides several built-in functions for typecasting. Here a
re some common typecasting functions:

a. `int(x)` - Convert to Integer:


- Converts `x` to an integer. If `x` is a float, it truncates the decimal part.

float_number = 3.14
int_number = int(float_number)
print(int_number) # Output: 3

b. `float(x)` - Convert to Float:


- Converts `x` to a floating-point number.

int_number = 42
float_number = float(int_number)
print(float_number) # Output: 42.0

c. `str(x)` - Convert to String:


- Converts `x` to a string.

number = 123
str_number = str(number)
print(str_number) # Output: '123'

d.`list(x)` - Convert to List:


- Converts `x` to a list. If `x` is a string, it creates a list of characters.

text = "Hello"
char_list = list(text)
print(char_list) # Output: ['H', 'e', 'l', 'l', 'o']

e. `tuple(x)` - Convert to Tuple:


- Converts `x` to a tuple.

my_list = [1, 2, 3]
tuple_version = tuple(my_list)
print(tuple_version) # Output: (1, 2, 3)

f. `bool(x)` - Convert to Boolean:


- Converts `x` to a boolean. Returns `False` for numeric types if `x` is zero; otherwise, retur
ns `True`.
number = 0
bool_value = bool(number)
print(bool_value) # Output: False

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).

Some common types of typecasting:

1. Implicit Typecasting (Automatic Type Conversion):


- Python automatically converts data types in certain situations without explicit user interv
ention. This typically occurs in operations where the types are compatible.
- For example, in expressions involving different numeric types, Python automatically pro
motes the smaller type to the larger type.

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)

2. Explicit Typecasting (Manual Type Conversion):


- Explicit typecasting involves manually converting one data type to another using predefin
ed functions.
- Common functions for explicit typecasting include `int()`, `float()`, `str()`, `list()`, `tuple()`,
`bool()`, etc.
float_number = 3.14
int_number = int(float_number)
print(int_number) # Output: 3 (float_number is explicitly converted to an int)

3. String to Numeric Conversion:


- Converting a string containing numeric characters to an integer or float.
numeric_string = "123"
integer_value = int(numeric_string)
float_value = float(numeric_string)

4. Numeric to String Conversion:


- Converting a numeric value to a string.
integer_value = 42
float_value = 3.14
str_integer = str(integer_value)
str_float = str(float_value)
5. List and Tuple Conversion:
- Converting between lists and tuples.
my_list = [1, 2, 3]
tuple_version = tuple(my_list)
my_tuple = (4, 5, 6)
list_version = list(my_tuple)

6. Boolean Conversion:
- Converting values to boolean.
zero = 0
non_zero = 42
bool_zero = bool(zero) # False
bool_non_zero = bool(non_zero) # True

7. Custom Type Conversion:


- In certain situations, you might need to define custom functions or methods for more co
mplex type conversions, especially when working with user-defined classes.
class CustomType:
def __init__(self, value):
self.value = value
custom_instance = CustomType(42)
# Custom type to integer conversion
custom_to_int = int(custom_instance.value)

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.

Two Types of Typecasting:


Explicit Conversion (Explicit type casting in python)
Implicit Conversion (Implicit 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 .

Example of explicit typecasting:


string = "15"
number = 7
string_number = int(string) #throws an error if the string is not a valid integer
sum= number + string_number
print("The Sum of both the numbers is: ", sum)

Output:
The Sum of both the numbers is 22

Implicit type casting:


Data types in Python do not have the same level i.e. ordering of data types is not the same in Python
. Some of the data types have higher-order, and some have lower order. While performing any opera
tions on variables with different data types in Python, one of the variable's data types will be change
d to the higher data type. According to the level, one data type is converted into other by the Python
interpreter itself (automatically). This is called, implicit typecasting in python.

Python converts a smaller data type to a higher data type to prevent data loss.

Example of implicit type casting:


# Python automatically converts
# a to int
a=7
print(type(a))

# Python automatically converts b to float


b = 3.0
print(type(b))

# Python automatically converts c to float as it is a float addition


c=a+b
print(c)
print(type(c))

Ouput:
<class 'int'>
<class 'float'>
10.0
<class 'float'>

Day09: Taking user input in python


In Python, there are several ways to take user input. The most common method is by using
the `input()` func on, but there are also other methods depending on specific requirements.
Here are different ways to take user input in Python:
1. Using `input()` Func on:
- The `input()` func on is the most straigh orward way to get user input. It reads a line of
text from the user and returns it as a string.
user_input = input("Enter something: ")
print("You entered:", user_input)

2. Conver ng Input to Other Data Types:


- If you need the user input as a specific data type (e.g., integer or float), you can use
typecas ng.
user_number = int(input("Enter an integer: "))
print("You entered:", user_number)
Keep in mind that if the user enters a non-numeric value, a `ValueError` will occur. You can
handle this by using a try-except block.
3. Using `raw_input()` in Python 2:
- In Python 2, the `raw_input()` func on is used to take user input. Unlike `input()`, it
always returns the user input as a string.
user_input = raw_input("Enter something: ")
print("You entered:", user_input)
In Python 3, `input()` is used, and it behaves similarly to `raw_input()` in Python 2.
4. Command-Line Arguments:
- You can also take input from command-line arguments using the `sys.argv` list or the
`argparse` module.
import sys
user_input = sys.argv[1]
print("You entered:", user_input)

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".')

b. Mul line Strings:


 To create mul line strings, you can use triple single (''') or double (""") quotes.
If our string has mul ple lines, we can create them like this:
a = """Lorem ipsum dolor sit amet,

consectetur adipiscing elit,


sed do eiusmod tempor incididunt
ut labore et dolore magna aliqua."""
print(a)

c. Accessing Characters of a String


In Python, string is like an array of characters. We can access parts of string by using its index
which starts from 0.
Square brackets can be used to access elements of the string.
Python uses zero-based indexing.
print(name[0])
print(name[1])

d. Looping through the string


We can loop through strings using a for loop like this:
for character in name:
print(character)
Above code prints all the characters in the string name one by one!

e. String Slicing:
 You can extract a por on of a string using slicing.
my_string = "Python"
slice_result = my_string[1:4] # 'yth'

f. String Concatena on:


 You can concatenate strings using the + operator.

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

h. String Forma ng:


You can format strings using the % operator or using the format() method.
name = "Alice"

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.

String forma ng in detail


String forma ng in Python refers to the process of crea ng forma ed strings by inser ng
values into a template string. There are several ways to achieve string forma ng in Python,
and each method has its own advantages. Here are the main methods of string forma ng:

1. Using `%` Operator (Old Style Forma ng):

name = "Alice"
age = 25
forma ed_string = "My name is %s and I am %d years old." % (name, age)
print(forma ed_string)

- `%s` is a placeholder for a string.


- `%d` is a placeholder for an integer.
- The values to be inserted are specified a er the `%` operator in a tuple.

2. Using `format()` Method:


name = "Alice"
age = 25
forma ed_string2 = "My name is {} and I am {} years old.".format(name, age)
print(forma ed_string2)
- `{}` is a placeholder.
- The values to be inserted are provided as arguments to the `format()` method.

3. Using f-strings (Python 3.6 and later):


name = "Alice"
age = 25
forma ed_string = f"My name is {name} and I am {age} years old."
- The `f` before the string denotes an f-string.
- Expressions inside curly braces `{}` are evaluated and inserted into the string.

4. Using `join()` with Iterables:


name = "Alice"
age = 25
forma ed_string = "My name is {} and I am {} years old.".format(name, age)
- Values are provided as elements of an iterable (e.g., a tuple, list).

### Common Forma ng Op ons:


- Specifying Width and Precision:
pi = 3.14159
forma ed_pi = "The value of pi is {:.2f}".format(pi)

This example rounds `pi` to two decimal places.

- Padding and Alignment:


name = "Alice"
aligned_string = "|{:>10}|".format(name)
This example right-aligns the string within a field of width 10.

- 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.

- Using `%` with Dic onaries (Old Style):


person = {'name': 'Alice', 'age': 25}
forma ed_string = "My name is %(name)s and I am %(age)d years old." % person

## Best Prac ces:


- Use f-strings for simplicity and readability (Python 3.6 and later).
- Use `format()` for compa bility with earlier Python versions.
- Avoid using the `%` operator for new code as it is considered legacy.

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

Loop through a String:


Strings are arrays and arrays are iterable. Thus we can loop through strings.
Example:
alphabets = "ABCDE"
for i in alphabets:
print(i)
Output:
A
B
C
D
E

String slicing chatgpt result


String slicing in Python is a way to extract a por on of a string by specifying a range of
indices. It allows you to create substrings or extract specific characters from a string. The
syntax for string slicing is `string[start:stop:step]`, where:

- `start` is the index from which the slicing begins (inclusive).


- `stop` is the index at which the slicing ends (exclusive).
- `step` (op onal) is the step size between characters.

Here are some examples to illustrate string slicing:


# Basic String Slicing:
my_string = "Hello, World!"
# Extrac ng characters from index 7 to 11 (exclusive)

substring = my_string[7:12]
print(substring) # Output: World

# Omi ng Start or Stop:


my_string = "Python is great!"

# Omi ng start (from the beginning of the string)


substring1 = my_string[:6]
print(substring1) # Output: Python

# Omi ng stop (un l the end of the string)


substring2 = my_string[7:]
print(substring2) # Output: is great!

# Using Nega ve Indices:


my_string = "Python is awesome!"
# Using nega ve indices (coun ng from the end of the string)
substring = my_string[-7:-1]
print(substring) # Output: some

# Slicing with a Step:


my_string = "123456789"
# Slicing with a step of 2
substring = my_string[1:8:2]
print(substring) # Output: 2468
# Reversing a String:
my_string = "Hello, World!"

# Reversing a string using slicing


reversed_string = my_string[::-1]
print(reversed_string) # Output: !dlroW ,olleH

### Important Points:


- Slicing is flexible and allows you to extract substrings or individual characters from a string.
- The `start` index is inclusive, and the `stop` index is exclusive, meaning that the character at
the `stop` index is not included in the slice.
- Omi ng `start` or `stop` uses the beginning or end of the string, respec vely.
- Nega ve indices count from the end of the string.
- The `step` parameter determines the interval between characters in the slice.

- Slicing can be used to reverse a string by using a step of `-1`.

String slicing is a powerful tool for working with text data in Python, and it provides a
concise and expressive way to manipulate strings.

Day 13: String Method


String methods
Python provides a set of built-in methods that we can use to alter and modify the strings.

upper() : format- .upper()


The upper() method converts a string to upper case.
Example:
str1 = "AbcDEfghIJ"
print(str1.upper())
Output:
ABCDEFGHIJ
lower(): format- .lower()
The lower() method converts a string to lower case.
Example:
str1 = "AbcDEfghIJ"

print(str1.lower())
Output:
Abcdefghij

strip() : format- .strip


The strip() method removes any white spaces before and a er the string.
Example:

str2 = " Silver Spoon "


print(str2.strip)
Output:
Silver Spoon

rstrip() : format- .rstrip


the rstrip() removes any trailing characters. Example:

str3 = "Hello !!!"


print(str3.rstrip("!"))
Output:
Hello

replace() : format- .replace


The replace() method replaces all occurrences of a string with another string. Example:
str2 = "Silver Spoon"

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.

capitalize() : format- .capitalize


The capitalize() method turns only the first character of the string to uppercase and the rest
other characters of the string are turned to lowercase. The string has no effect if the first
character is already uppercase.
Example:
str1 = "hello"
capStr1 = str1.capitalize()
print(capStr1)
str2 = "hello World"
capStr2 = str2.capitalize()
print(capStr2)
Output:
Hello
Hello world

center() : format- .center


The center() method aligns the string to the center as per the parameters given by the user.
Example:
str1 = "Welcome to the Console!!!"
print(str1.center(50))
Output:
Welcome to the Console!!!
We can also provide padding character. It will fill the rest of the fill characters provided by
the user.
Example:
str1 = "Welcome to the Console!!!"
print(str1.center(50, "."))
Output:
............Welcome to the Console!!!.............

count() : format- .count


The count() method returns the number of mes the given value has occurred within the
given string.
Example:
str2 = "Abracadabra"
countStr = str2.count("a")
print(countStr)
Output:
4

endswith() : format- .endswith


The endswith() method checks if the string ends with a given value. If yes then return True,
else return False.
Example :
str1 = "Welcome to the Console !!!"
print(str1.endswith("!!!"))
Output:
True
We can even also check for a value in-between the string by providing start and end index
posi ons.
Example:
str1 = "Welcome to the Console !!!"
print(str1.endswith("to", 4, 10))
Output:
True

find() : format- .find


The find() method searches for the first occurrence of the given value and returns the index
where it is present. If given value is absent from the string then return -1.
Example:
str1 = "He's name is Dan. He is an honest man."
print(str1.find("is"))
Output:
10
As we can see, this method is somewhat similar to the index() 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. He is an honest man."
print(str1.find("Daniel"))
Output:
-1

index() : format- .index


The index() method searches for the first occurrence of the given value and returns the
index where it is present. If given value is absent from the string then raise an excep on.
Example:
str1 = "He's name is Dan. Dan is an honest man."

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

isalnum() : format- .isalnum


The isalnum() method returns True only if the en re string only consists of A-Z, a-z, 0-9. If
any other characters or punctua ons are present, then it returns False.
Example 1:
str1 = "WelcomeToTheConsole"
print(str1.isalnum())
Output:
True

isalpha() : format- .isalpha


The isalnum() method returns True only if the en re string only consists of A-Z, a-z. If any
other characters or punctua ons or numbers(0-9) are present, then it returns False.
Example :
str1 = "Welcome"
print(str1.isalpha())
Output:
True

islower() : format- .islower


The islower() method returns True if all the characters in the string are lower case, else it
returns False.
Example:
str1 = "hello world"
print(str1.islower())
Output:
True

isprintable() : format- .isprintable


The isprintable() method returns True if all the values within the given string are printable, if
not, then return False.
Example :
str1 = "We wish you a Merry Christmas"

print(str1.isprintable())
Output:
True

isspace() : format- .is tle


The isspace() method returns True only and only if the string contains white spaces, else
returns False.
Example:
str1 = " " #using Spacebar
print(str1.isspace())
str2 = " " #using Tab
print(str2.isspace())
Output:
True
True

is tle() : format- .is tle


The is le() returns True only if the first le er of each word of the string is capitalized, else it
returns False.
Example:
str1 = "World Health Organiza on"
print(str1.is tle())
Output:
True
Example:
str2 = "To kill a Mocking bird"
print(str2.is tle())
Output:
False
isupper() : format- .isupper
The isupper() method returns True if all the characters in the string are upper case, else it
returns False.
Example :
str1 = "WORLD HEALTH ORGANIZATION"
print(str1.isupper())
Output:
True

startswith() : format- .startswith


The endswith() method checks if the string starts with a given value. If yes then return True,
else return False.
Example :
str1 = "Python is a Interpreted Language"
print(str1.startswith("Python"))
Output:
True

swapcase() : format- .swapcase


The swapcase() method changes the character casing of the string. Upper case are converted
to lower case and lower case to upper case.
Example:
str1 = "Python is a Interpreted Language"
print(str1.swapcase())
Output:
pYTHON IS A iNTERPRETED lANGUAGE

tle() : format- . tle


The tle() method capitalizes each le er of the word within the string.
Example:
str1 = "He's name is Dan. Dan is an honest man."
print(str1. tle())
Output:
He'S Name Is Dan. Dan Is An Honest Man.

Day 14: if else statement

Condi onal operators:


Condi onal operators, also known as comparison or rela onal operators, are used in
programming languages to perform comparisons between values. These operators return a
Boolean result (either true or false) based on evalua ng the specified condi ons.
Common condi onal operators include:
1. Equal to (==): Checks if the values on both sides of the operator are equal.
x == y # True if x is equal to y
2. Not equal to (!=): Checks if the values on both sides of the operator are not equal.
x != y # True if x is not equal to y
3. Greater than (>): Checks if the value on the le is greater than the value on the right.
x > y # True if x is greater than y
4. Less than (<): Checks if the value on the le is less than the value on the right.

x < y # True if x is less than y


5. Greater than or equal to (>=): Checks if the value on the le is greater than or equal to the
value on the right.
x >= y # True if x is greater than or equal to y
6. Less than or equal to (<=): Checks if the value on the le is less than or equal to the value
on the right.
x <= y # True if x is less than or equal to y
These operators are widely used in condi onal statements (such as if statements) to control
the flow of a program based on certain condi ons. For example, in Python:
if x > y:
print("x is greater than y")
elif x < y:
print("x is less than y")
else:

print("x and y are equal")


This code uses the greater than, less than, and equal to operators to determine the
rela onship between the variables `x` and `y` and then prints a corresponding message.

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.

An if……else statement evaluates like this:


if the expression evaluates True:
Execute the block of code inside if statement. A er execu on return to the code out of the
if……else block.\
if the expression evaluates False:
Execute the block of code inside else statement. A er execu on return to the code out of
the if……else block.
Example:
applePrice = 210
budget = 200
if (applePrice <= budget):
print ("Alexa, add 1 kg Apples to the cart.")
else:
print ("Alexa, do not add Apples to the cart.")
Output:
Alexa, do not add Apples to the cart.

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")

elif (num > 10 and num <= 20):


print("Number is between 11-20")
else:
print("Number is greater than 20")
else:
print("Number is zero")
Output:
Number is between 11-20

# 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

The case clause consists of a pa ern to be matched to the variable, a condi on to be


evaluated if the pa ern matches, and a set of statements to be executed if the pa ern
matches.
Syntax:
match variable_name:
case ‘pa ern1’ : //statement1
case ‘pa ern2’ : //statement2

case ‘pa ern n’ : //statement n
Example:
x=4
# x is the variable to match
match x:
# if x is 0
case 0:
print("x is zero")
# case with if-condi on
case 4 if x % 2 == 0:
print("x % 2 == 0 and case is 4")
# Empty case with if-condi on
case _ if x < 10:

print("x is < 10")


# default case(will only be matched if the above cases were not matched)
# so it is basically just an else:
case _:
print(x)
Output:
x % 2 == 0 and case is 4

You might also like