Lecture # 5 - Strings and Number Data Types

Lecture # 5 - Strings and Number Data Types

Strings (str):

In Python, the string data type is used to represent and manipulate textual data.

How to Write Strings:

Strings are sequences of characters, enclosed within either single quotes (' ') or double quotes (" "). Python treats single quotes and double quotes in strings exactly the same, so you can use either depending on your preference or to avoid escaping characters.

Checking Data Type:

print(type("Hello, World"))
print(type('Hello, World'))

type() is a built-in-function in python that tells the datatype of the parameter passed in the function.

Output:

Number:

In Python, there are several built-in numeric data types to represent different kinds of numbers. Some of the primary numeric data types include:

  1. Integer (int):

Integers represent whole numbers without any decimal point. They can be positive, negative, or zero. e.g. -2, 0, 1248.

Checking Data Type:

print(type(-2))
print(type(0))
print(type(1248))

Output:

  1. Floating Point Numbers (float):

    Floating-point numbers represent real numbers with a decimal point. e.g. -2.1, 0.0, 12.48 .

Checking Data Type:

print(type(-2.1))
print(type(0.0))
print(type(12.48))

Output:

String Concatenation:

In Python, string concatenation refers to the process of combining multiple strings into a single string. This can be achieved using the + operator.

Example 1:

print("Hello, " + "World")

Output:

Example 2:

print("I am " + str(17) + " Years Old")

If you want to concatenate any number or anything that is not string you'll have to first convert into string using a built-in-function str() .

Output:

Example 3:

print(f"I am in class {12}")

This is another way of concatenating the non strings with strings. f is used for formatting the string. This can only be done in python3.

Output:

Example 4:

print(f"2 + 2 = {2 + 2}")

You can also perform calculations.

Output:

Comments:

Comments are used to include explanatory notes or annotations within the code. Comments are ignored by the Python interpreter and are purely for human readers. They are useful for providing context, explaining complex code, or temporarily disabling code during development. There are two types of comments in Python:

Single-Line Comments:

Single-line comments begin with the hash character # and continue until the end of the line. They are typically used for short comments on the same line as the code.

#This is a Single-Line Comment

Multi-Line Comments:

Python doesn't have a built-in syntax for multi-line comments like some other programming languages. However, multi-line strings (docstrings) enclosed in triple quotes (''' or """) are often used for multi-line comments, even though they serve a different purpose (documentation).

'''
This is a 
Multi-Line Comment.
'''

"""
This is also a 
Multi-Line Comment.
"""