Python Diaries ….. Day 2
Welcome back to Python Diaries! Its Numbers String and Booleans….
Today we’ll focus on three fundamental concepts: numbers, strings, and Booleans. These elements form the bedrock of any Python program, enabling you to perform calculations, manipulate text, and control program flow.
Let’s embark on this journey to solidify your understanding of these crucial components in Python. Get ready to explore numbers, dive into the world of strings, and master the art of using operators effectively. Let’s get started!
Numbers
Strings
Boolean
Numbers
In Python, numbers come in different flavors:
1. Integers (int
)
Floats, also known as floating-point numbers, represent real numbers and can have a decimal point.
x = 42
2. Floats (float
)
Floats, also known as floating-point numbers, represent real numbers and can have a decimal point.
pi = 3.14
3. Complex Numbers (complex
)
Complex numbers have both a real and an imaginary part. They are written in the form a + bj
, where a
is the real part and b
is the imaginary part.
z = 2 + 3j
Strings
Strings are sequences of characters, enclosed in either single (' '
) or double (" "
) quotes.
message = "Hello, Python!"
Strings are incredibly versatile and support various operations like concatenation, slicing, and more.
String Operations
String Length:
The len()
function returns the length of a string.
my_string = 'Hello, World!'
length = len(my_string) # length will be 13
String Indexing:
Strings are indexed, meaning you can access individual characters using their position in the string.
my_string = 'Hello'
first_char = my_string[0] # Accessing the first character (index 0)
String Slicing:
String slicing in Python allows you to extract a portion of a string by specifying a start and end index. It follows the syntax:
string[start:end:step]
- Inclusive Start, Exclusive End:
my_string = "Hello, World!"
sliced_string = my_string[7:12]
print(sliced_string) # Output: 'World'
2. Negative Indices:
my_string = "Hello, World!"
last_char = my_string[-1]
second_last_char = my_string[-2]
print(last_char, second_last_char) # Output: '!', 'd'
3. Omitted Indices:
my_string = "Hello, World!"
start_omitted = my_string[:5]
end_omitted = my_string[7:]
print(start_omitted, end_omitted) # Output: 'Hello', 'World!'
4. Step Size:
my_string = "Hello, World!"
every_second_char = my_string[0:5:2]
print(every_second_char) # Output: 'Hlo'
5. Reversing a String:
my_string = "Hello, World!"
reversed_string = my_string[::-1]
print(reversed_string) # Output: '!dlroW ,olleH'
6. Out of Range Indices:
my_string = "Hello, World!"
out_of_range_slice = my_string[0:100]
print(out_of_range_slice) # Output: 'Hello, World!'
String Concatenation:
Strings can be combined using the +
operator.
str1 = 'Hello'
str2 = ' World'
combined_str = str1 + str2
You can search for more python string exercises here!!!!
String Methods:
Python provides numerous built-in methods for working with strings. Some common ones include:
str.upper()
: Converts all characters to uppercase.str.lower()
: Converts all characters to lowercase.
my_string = "Hello, World!"
upper_case = my_string.upper() # Output: 'HELLO, WORLD!'
lower_case = my_string.lower() # Output: 'hello, world!'
str.capitalize()
: This method returns a new string with the first character capitalized and the rest in lowercase.
my_string = "hello, world!"
capitalized = my_string.capitalize() # Output: 'Hello, world!'
str.strip()
: Removes leading and trailing whitespace.lstrip()
removes leading whitespace.rstrip()
removes trailing whitespace.
my_string = " Hello, World! "
stripped = my_string.strip() # Output: 'Hello, World!'
str.isalpha()
,str.isdigit()
, andstr.isalnum()
: These methods returnTrue
if all the characters in the string are alphabetic, numeric, or alphanumeric, respectively.
alpha_check = "Hello".isalpha() # Output: True
digit_check = "123".isdigit() # Output: True
alnum_check = "Hello123".isalnum() # Output: True
str.startswith(prefix)
andstr.endswith(suffix)
: These methods returnTrue
if the string starts or ends with the specified prefix or suffix, respectively.
my_string = "Hello, World!"
starts_with_hello = my_string.startswith("Hello") # Output: True
ends_with_world = my_string.endswith("World") # Output: False
str.replace(old, new)
: Replaces occurrences ofold
withnew
.
my_string = "Hello, World!"
new_string = my_string.replace("Hello", "Hi") # Output: 'Hi, World!'
str.split(delimiter)
: Splits a string into a list of substrings based on thedelimiter
.str.join(iterable)
: Joins a list of strings with thestr
as a separator.
my_string = "apple,banana,cherry"
fruits = my_string.split(",") # Output: ['apple', 'banana', 'cherry']
joined_string = "-".join(fruits) # Output: 'apple-banana-cherry'
find()
returns the lowest index of the substring in the string, or -1 if not found.rfind()
does the same, but searches from the right.
my_string = "Hello, World!"
index = my_string.find("l") # Output: 2
rindex = my_string.rfind("l") # Output: 9
String Formatting:
You can format strings using the %
operator or using f-strings (formatted string literals).
name = 'Alice'
age = 30
formatted_string = 'My name is %s and I am %d years old.' % (name, age)
# or
formatted_string = f'My name is {name} and I am {age} years old.'
Using the str.format()
Method: This method allows you to format strings by inserting variables or values into placeholders within a string.
name = "Charlie"
age = 35
formatted_string = "My name is {} and I am {} years old.".format(name, age)
Additional formatting options can be specified within the curly braces or the %
operator to control the alignment, precision, and other aspects of the output.
For example, %10s
will ensure that a string is at least 10 characters wide, while {:0.2f}
will format a floating-point number with 2 decimal places.
pi = 3.14159265359
formatted_pi = "The value of pi is approximately: {:0.2f}".format(pi)
Escape Sequences:
Escape sequences are used to include special characters in a string. Some common escape sequences include:
\n
: Newline\t
: Tab\\
: Backslash\'
or\"
: Single or double quote
Raw Strings:
Raw strings are denoted by placing an r
before the string literal. They treat backslashes as literal characters, which is useful for regular expressions and file paths.
path = r'C:\Users\John\Documents'
You can search for more python string exercises here!!!!
Python Booleans
In Python, Booleans are a built-in data type used to represent truth values. A Boolean value can either be True
or False
. These values are the result of comparison operations or logical operations in Python.
True and False:
True
andFalse
are the only two Boolean values in Python. They are case-sensitive, so you must use an uppercase 'T' and 'F'.
x = True
y = False
Boolean Operators:
- Comparison and logical operators in Python return Boolean values. For example:
x = 5
y = 10
greater_than = x > y # Result: False
equal_to = x == y # Result: False
logical_and = (x < 10) and (y > 5) # Result: True
Truthiness and Falsiness:
- In addition to
True
andFalse
, other objects in Python have an associated truth value. Generally, any non-zero number or non-empty object is consideredTrue
, while0
,None
, empty containers, and instances of user-defined classes with a__bool__()
or__len__()
method that returns0
orFalse
are consideredFalse
.
bool(0) # False
bool(1) # True
bool([]) # False (empty list)
bool([1, 2]) # True
Logical Operations:
- The logical operators
and
,or
, andnot
are used to perform logical operations. These operators work with Boolean values.
x = True
y = False
result_and = x and y # Result: False
result_or = x or y # Result: True
result_not_x = not x # Result: Fals
Short-Circuit Evaluation:
- Python uses short-circuit evaluation for logical operations. For
and
, if the left operand isFalse
, the right operand is not evaluated. Foror
, if the left operand isTrue
, the right operand is not evaluated.
x = False
y = True
result_and = x and y # Since x is False, y is not evaluated. Result: False
result_or = x or y # Since x is False, y is evaluated. Result: True
Comparisons:
- Comparison operators like
<
,>
,==
,!=
,<=
,>=
return Boolean values.
x = 5
y = 10
greater_than = x > y # Result: False
less_than_or_equal = x <= y # Result: True
Today, we’ve explored the world of numbers, strings, and booleans in Python. These are the fundamental elements you’ll use in almost every program you write.
You can access the other topics in this tutorial series right here:
- Day 1: Data types, Comment, Type casting and User input.
- Day 2: Numbers, Strings, and Booleans.
- Day 3: Operators
- Day 4: Lists
- Day 5: Tuples and Sets
- Day 6: Dictionaries
- Day 7: If , If Else, If elif else Condition statements
- Day 8: While loops
- Day 9: For loops
- Day 10: Functions
- Day 11: File handling
- Day 12: Error Handling
- Day 13: Regular expressions
- Day 14: OOPS in python (class)
- Day 15: Python GUI libraries
Practice with them, and in the next entry, we’ll dive into more complex data structures like lists, tuples, and dictionaries. Happy coding!