2 + 46
(CSE331) Python for Data Science
2 + 46
6.+, -, *, /, ** (power), // (floor division), % (modulus)(59 + 73 + 2) / 3 44.666666666666664
10**(3+1) # exponentiation (** is power, not ^)10000
3**2 # 3 squared9
10 // 3 # 3: floor of the quotient3
10 % 3 # remainder (modulus)1
With negative numbers, floor division rounds down, rather than toward zero:
print(-10 // 3) # -4
print(-10 % 3) # 2, because -10 = 3 * (-4) + 2-4
2
Use parentheses to make the intended order of operations clear.
=) binds the name (left) to the object (right).x = 48a, b, c, d = 7, 5, 8, 4
print(a, b, c, d)7 5 8 4
a, b = b, a
print(a, b)5 7
A–Z, a–z)0–9)_)_ (e.g., _cache), but that implies “internal” by convention.True, False, None, and, class, def, …).snake_case for variables/functions: total_count, is_ready.UPPER_CASE for constants: PI = 3.14159.Every value has a type describing what it represents and how it behaves.
0, -7, 42)3.14, -0.001, 1.0)True, False): behave like ints (True==1, False==0)"Dhaka", "Data Science")x = 10 # int
y = 3.5 # float
name = "Rasel" # str
is_ready = True # bool
print(type(x), type(y), type(name), type(is_ready))<class 'int'> <class 'float'> <class 'str'> <class 'bool'>
Avoid assigning to built-in names such as list, str, sum, and max; doing so hides the corresponding built-in object.
' or double " quotes.a = 'one way of writing a string'
b = "another way"c = """
This is a longer string that
spans multiple lines
"""
print(c)
This is a longer string that
spans multiple lines
Positions start at 0. Negative positions count backward from the end.
word = "Python"
print(word[0], word[-1])
print(word[1:4]) # positions 1, 2, 3; stop is excluded
print(len(word))P n
yth
6
Strings are immutable. An operation such as word.upper() returns a new string.
A method is called using object.method(...).
raw_name = " Ayesha Rahman "
clean_name = raw_name.strip()
print(clean_name)
print(clean_name.lower())
print(clean_name.replace("Rahman", "Islam"))
print(raw_name) # original string is unchangedAyesha Rahman
ayesha rahman
Ayesha Islam
Ayesha Rahman
fields = "Dhaka,25,72.5".split(",")
print(fields) # a list; studied in the next lecture
print(" | ".join(fields))
print("Dhaka" in "Dhaka, Bangladesh")['Dhaka', '25', '72.5']
Dhaka | 25 | 72.5
True
strip() removes leading and trailing whitespace. split() separates text; join() combines strings. Use a CSV reader for real CSV files, which may contain quoted commas.
17 + 4.321.3
17 + "seventeen" # raises TypeError (number + string)"This" + "That"'ThisThat'
str, bool, int, and float are callable: use them to convert values to those types:s = '3.14159'
fval = float(s) # string → float
type(fval)float
ival = int(fval) # float → int (truncates toward zero)
print(ival)3
bval = bool(ival) # non-zero → True; zero → False
print(bval)True
int("3.5") fails; you must convert to float first, then to int if needed.
input() always returns a string. Convert it when a calculation requires a number.
Run this example interactively in your notebook:
age = int(input("Enter your age in whole years: "))
print(f"Next year you will be {age + 1}.")Entering text such as twenty causes a ValueError. We will handle conversion errors later. For reproducible analysis, put known values in code cells or read them from data files instead of repeatedly entering them by hand.
None TypeNone that is used to indicate the absence of a value.None is similar to NULL in Ra = None
a is NoneTrue
None.is None or is not None to check for this value.None is not zero or an empty string. Missing values in NumPy and pandas will need additional conventions.== checks whether values are equal.is checks whether two names refer to the same object.== for ordinary numeric and string comparisons; use is None for a missing-value sentinel.print() to display values intentionally.name = "Rasel"
score = 83.4567
print(f"Hello, {name}! Your score is {score:.1f}.")
print(f"Score to two decimal places: {score:.2f}")Hello, Rasel! Your score is 83.5.
Score to two decimal places: 83.46
n = 10
n += 5 # same as n = n + 5
n *= 2
n30
a = 0.1 + 0.2
a == 0.3, a(False, 0.30000000000000004)
math.isclose()import math
math.isclose(a, 0.3)True
Used to compare two operands and return a Boolean result (True or False).
Comparison operators (similar to R’s symbols):
| Meaning | Operator |
|---|---|
| equal to | == |
| not equal | != |
| greater / greater-equal | >, >= |
| less / less-equal | <, <= |
10 <= 15True
14 != 16True
x = 3
0 < x < 5, (0 < x and x < 5)(True, True)
and, or, not(2 < 5) and (10 > 3), (2 > 5) or (10 > 3), not False(True, True, True)
Zero, None, empty strings, and empty collections are false in a condition. Other ordinary nonempty strings are true, including the string "False".
print(bool(0), bool(""), bool(None))
print(bool("False"), bool(-2))False False False
True True
For Boolean expressions, and, or, and not express logical operations. More generally, and and or return one of their operands; not returns a Boolean.
a = 17 and b = 5, calculate their quotient, floor quotient, and remainder. Verify a == b * (a // b) + a % b.temperature = "37.65" to a number and display it to one decimal place using an f-string.name = " RASEL BISWAS " by removing surrounding spaces and converting to lowercase.word = "statistics", obtain its first character, last character, and first four characters.input() results would behave differently.score lies between 0 and 100 inclusive.bool("0"), bool(0), and bool(""), then check your answers.** for power, not ^.== vs is.math.isclose for comparisons.
12 Comments & Help
# this is a comment