<jupyter_start><jupyter_text>Python Basic Data Types    Python Primitive Data Types- Data types are the classification or categorization of data items. - Data types represent a kind of value which determines what operations can be performed on that data.- Every value in Python has a datatype.Python has four primitive data types:* Integer* Float* Boolean* StringWe will cover the above data types in addition to complex numbers.  Concept of Variables* Variables are nothing but reserved memory locations to store values. This means that when you create a variable you reserve some space in memory.* Python variables do not need explicit declaration to reserve memory space.* The declaration happens automatically when you assign a value to a variable. * The equal sign (`=`) is used to assign values to variables.* Based on the data type of a variable, the Python interpreter allocates memory and decides what can be stored in the reserved memory. * A variable can change its type over the course of the program's execution.* By assigning different data types to variables, you can store integers, decimals or characters in these variables.   Integers  * An integer is a whole number that could hold a zero, positive or negative value.* Integers can be of any length, it is only limited by the memory available.<jupyter_code>a = 12345678901234567890123456789012345678901234567890
print(a)
b = a + 11
print(b)<jupyter_output><empty_output><jupyter_text>The following strings can be prepended to an integer value to indicate a base other than 10:| Prefix |	Interpretation	| Base || --- | --- | --- | | 0b (zero + lowercase letter 'b') | Binary| 	2|| 0B (zero + uppercase letter 'B')|	 | 0o (zero + lowercase letter 'o')|  Octal| 	8|| 0O (zero + uppercase letter 'O')|| 0x (zero + lowercase letter 'x')|  Hexadecimal| 	16|| 0X (zero + uppercase letter 'X')|<jupyter_code>print(0o10)
print(0x10)
print(0b001)<jupyter_output><empty_output><jupyter_text>- The underlying type of a Python integer, irrespective of the base used to specify it, is called `int`.- We can use the `type()` function to determine the type of any Python data item.<jupyter_code>type(10)
type(0o10)
type(0x10)<jupyter_output><empty_output><jupyter_text>- We can also use the `isinstance()` function to check if a data item belongs to a particular data type.<jupyter_code>a = 12345678901234567890123456789012345678901234567890
print(a, "is of type", type(a))
print(a, "is integer?", isinstance(a, int))<jupyter_output><empty_output><jupyter_text>Integer Arithmetic In Python, __variables are not declared__. The type of a variable is determined when it is assigned a value.<jupyter_code>a = 1
b = 2
c = 3
d = 4
e = 5
f = 6
g = 7
h = 8
print(a + b)
print(c - d)
print(e * f)
print(g / h)
x = 17
y = 3

print(x /  y)  # gives 5.66666666667
print(x // y)  # gives 5
print(x %  y)   # gives 2<jupyter_output><empty_output><jupyter_text>Floating Point Numbers  * The float type in Python designates a floating-point number. * Float values are specified with a decimal point.* A floating-point number is accurate up to 15 decimal places.* The character e or E followed by a positive or negative integer may be appended to specify scientific notation.<jupyter_code>7.94
type(7.94)
.56
56.
2.6e-5
a = 0.1234567890123456789
print(a, "is of type", type(a))
print(a, "is float?", isinstance(a, float))<jupyter_output><empty_output><jupyter_text>* Floating point numbers are represented internally as binary (base-2) fractions. * Most decimal fractions cannot be represented exactly as binary fractions, so in most cases the internal representation of a floating-point number is an approximation of the actual value.  Operations on Floats<jupyter_code>print(int(1.3))   # gives 1
print(int(1.7))   # gives 1
print(int(-1.3))  # gives -1
print(int(-1.7))  # gives -1<jupyter_output><empty_output><jupyter_text>The `round()` function returns a floating-point number rounded to the specified number of decimals. It takes two parameters:+ **number** - the number to be rounded+ **ndigits (optional)** - number up to which the given number is rounded; defaults to 0.When the second argument is present, it will round to the number of places given. The return type will be a float.<jupyter_code>float_num1 = 10.60 
float_num2 = 10.40
float_num3 = 10.3456 
float_num4 = 10.3445 
print("Rounded value without num_of_decimals is :", round(float_num1))
print("Rounded value without num_of_decimals is :", round(float_num2))
print("Rounded value with num_of_decimals as 2 is :", round(float_num3, 2))
print("Rounded value with num_of_decimals as 2 is :", round(float_num4, 2))<jupyter_output><empty_output><jupyter_text>Let us see few examples of how rounding works on negative numbers:<jupyter_code>num = -2.8
num1 = -1.5
print("The value after rounding is", round(num))
print("The value after rounding is", round(num1))
x = float(input("Give me a number: "))
print(x)<jupyter_output><empty_output><jupyter_text>Complex Numbers - A complex number consists of an ordered pair of real floating point numbers denoted by a + bj, where a is the real part and b is the imaginary part of the complex number.<jupyter_code>3.0 + 9j
type(3.0+9j)
a = complex(3.0,9)
print("a = ", a)
print('Real Part =         ', a.real)
print('Imaginary Part =    ', a.imag)
print('Complex conjugate = ', a.conjugate())
b = complex(1,2)
print ("a*a=",a*a)
print ("a/b=",a/b)
print ("a*b=",a*b)<jupyter_output><empty_output><jupyter_text>Booleans * The python data type `bool` is used to store two values i.e `True` and `False`.* Booleans are used to test whether the result of an expression is true or false.<jupyter_code>true=True
type(true)
true=123
type(true)
type(False)<jupyter_output><empty_output><jupyter_text>- A Boolean expression is an expression that evaluates to produce a result which is a Boolean value.- We can store a Boolean value in a variable:<jupyter_code>my_bool = 5 > 8<jupyter_output><empty_output><jupyter_text>and then print the Boolean value with a call to the `print()` function:<jupyter_code>print(my_bool)<jupyter_output><empty_output><jupyter_text>To check the boolean value of an expression or a variable, pass it as a parameter to the bool function:```python   print(bool(expression))```or```python   print(expression)``` Booleans can be used when there is a need to compare two or more values.```python   x == y     x is equal to y   x != y     x is not equal to y   x > y      x is greater than y   x < y      x is less than y   x >= y     x is greater than or equal to y   x <= y     x is less than or equal to y``` Check if x and y are equal:<jupyter_code>print(3==4) 
print(bool(3==4))<jupyter_output><empty_output><jupyter_text>Check if x and y are not equal:<jupyter_code>print(3!=4) 
print(bool(3!=4))<jupyter_output><empty_output><jupyter_text>Check if x is greater than y:<jupyter_code>print(3>4) 
print(bool(3>4))<jupyter_output><empty_output><jupyter_text>Check if x is less than y:<jupyter_code>print(3<4) 
print(bool(3<4))<jupyter_output><empty_output><jupyter_text>Check if x is greater than or equal to y:<jupyter_code>print(3>=4)
print(bool(3>=4))<jupyter_output><empty_output><jupyter_text>Check if x is less than equal to y:<jupyter_code>print(3<=4)
print(bool(3<=4))<jupyter_output><empty_output><jupyter_text>Strings * Strings are sequences of character data. * The string type in Python is called str.* String literals may be delimited using either single or double quotes.* All the characters between the opening delimiter and matching closing delimiter are part of the string.* Are immutable.<jupyter_code>print("Welcome to the Python Camp!")
type("Welcome to the Python Camp!")<jupyter_output><empty_output><jupyter_text>* A string in Python can contain as many characters as you wish.* The only limit is your machine’s memory resources.<jupyter_code>print("This string contains a single quote (') character.")
print('This string contains a double quote (") character.')<jupyter_output><empty_output><jupyter_text>Escape Sequences in Strings<jupyter_code>print('This string contains a single quote (\'* character.')
print("This string contains a double quote (\") character.")
print('abc')
print('a\
b\
c')
print('foo\\bar')<jupyter_output><empty_output><jupyter_text>Applying Special Meaning to CharactersWe want to represent escape sequences that are typically used to insert characters that are not readily generated from the keyboard or are not easily readable or printable.Here is a list of escape sequences that cause Python to apply special meaning instead of interpreting literally:| Escape Sequence| “Escaped” Interpretation || --- | --- || \a	| ASCII Bell (BEL) character| \b	| ASCII Backspace (BS) character| \f	| ASCII Formfeed (FF) character| \n	| ASCII Linefeed (LF) character| \N{}| 	Character from Unicode database with given | \r	| ASCII Carriage Return (CR) character| \t	| ASCII Horizontal Tab (TAB) character| \uxxxx	| Unicode character with 16-bit hex value xxxx| \Uxxxxxxxx	| Unicode character with 32-bit hex value xxxxxxxx| \v	| ASCII Vertical Tab (VT) character| \ooo	| Character with octal value ooo| \xhh	| Character with hex value hh<jupyter_code>print("a\t\t\tb")
print("\141", "\x61")
print("a\n\tb ")
print('\u2192 \N{rightwards arrow}')<jupyter_output><empty_output><jupyter_text>Raw Strings- A raw string literal is preceded by `r` or `R`, which specifies that escape sequences in the associated string are not translated. - The backslash character is left in the string.<jupyter_code>print('foo\nbar')
print(r'foo\nbar')
print('foo\\bar')
print(R'foo\\bar')<jupyter_output><empty_output><jupyter_text>Triple Quotes- Triple-quoted strings are delimited by matching groups of three single quotes or three double quotes. - Escape sequences still work in triple-quoted strings, but single quotes, double quotes, and newlines can be included without escaping them. - Provide a convenient way to create a string with both single and double quotes in it.<jupyter_code>print('''This string has a single (') and a double (") quote.''')
print("""This is a
string that spans
across several lines""")<jupyter_output><empty_output><jupyter_text>Accessing Values in Strings- Python does not support a character type; these are treated as strings of length one, thus also considered a substring.- To access substrings, use the square brackets for slicing along with the index or indices to obtain your substring<jupyter_code>astring1 = "Welcome To the Python Camp!"
astring2 = "A Training Course for Beginners."
print(astring1[3:10])
print(astring1[3:15:1])
print(astring1[3:15:2])
print(astring1[-2])<jupyter_output><empty_output><jupyter_text>- Python allows to index from the zeroth position in Strings. - Python also supports negative indexes. - Index of ‘-1’ represents the last character of the String. Similarly, using ‘-2’, we can access the penultimate element of the string and so on.| P | Y | T | H | O | N | - | S | T | R | I | N | G ||---|---|---|---|---|---|---|---|---|---|---|---|---|| 0 | 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | 9 |10 |11 |12 ||-13|-12|-11|-10|-9 |-8 |-7 |-6 |-5 |-4 |-3 |-2 |-1 |  Updating Strings- You cannot modify a string for a **string is immutable**.    - A data item is considered to be immutable if once it is created, it cannot be changed.- You can "update" an existing string by (re)assigning a variable to another string. - The new value can be related to its previous value or to a completely different string altogether. We can use the `id()` function to obtain the identity of an object. The identity is a unique integer for that object during its lifetime. This is also the address of the object in memory.<jupyter_code>id_before_astring1 = id(astring1)
print(id_before_astring1)
astring1[8] = 't'
astring1 = astring1[0:8]+'t'+astring1[9:]
print(astring1)
id_after_astring1 = id(astring1)
print(id_after_astring1)
astring3 = astring1 + " " + astring2[0] + " " + astring2[11:]
print(astring3)
print(astring1*2)
print(astring2 * -1)
print ( "Python" in astring1)
print ( "python" in astring1)
print ( "python" not in astring1)<jupyter_output><empty_output><jupyter_text>Built-in in String Operators `capitalize()`:<jupyter_code>"funKY tOwn".capitalize()<jupyter_output><empty_output><jupyter_text>`lower()` and `upper()`:<jupyter_code>"funky tOwn".lower()
"fuNky toWn".upper()<jupyter_output><empty_output><jupyter_text>`split()`:<jupyter_code>"funKY tOwn".split()
"funKY tOwn".capitalize().split()
"I want to take you to, funKY tOwn".split("u")<jupyter_output><empty_output><jupyter_text>`strip()`:<jupyter_code>csv_string = 'Dog,Cat,Spam,Defenestrate,1, 3.1415   \n\t'
csv_string.strip()<jupyter_output><empty_output><jupyter_text>`.join()`: allows you to glue a list of strings together with a certain string<jupyter_code>clean_list = [x.strip() for x in csv_string.split(",")]
print(clean_list)
print(",".join(clean_list))
print("\t".join(clean_list))<jupyter_output><empty_output><jupyter_text>`.replace()` strings in strings<jupyter_code>csv_string = 'Dog,Cat,Spam,Defenestrate,1, 3.1415   \n\t'
alt_csv = csv_string.strip().replace(',', ' ')
print(alt_csv)
print(csv_string.strip().replace(' ','').replace(',','\t'))<jupyter_output><empty_output><jupyter_text>`.index()`:<jupyter_code>s = 'My Funny Valentine'
s.index("y")<jupyter_output><empty_output><jupyter_text>`.count()`:<jupyter_code>s.count("y")<jupyter_output><empty_output><jupyter_text>`.find()`: useful searching, and returning the index of the search<jupyter_code>s.find("y")
s.find("y",2)
s[s.find("Funny"):]<jupyter_output><empty_output><jupyter_text>Length of a string:<jupyter_code>len(s)<jupyter_output><empty_output><jupyter_text>**Boolean Methods**| Method	| True if || --- | --- || `str.isalnum()` |	String consists of only alphanumeric characters (no symbols) || `str.isalpha()` |	String consists of only alphabetic characters (no symbols) || `str.islower()` |	String’s alphabetic characters are all lower case || `str.isnumeric()` |	String consists of only numeric characters || `str.isspace()` |	String consists of only whitespace characters || `str.istitle()` |	String is in title case || `str.isupper()` |	String’s alphabetic characters are all upper case || `str.startswith()` | String starts with the specified value || `str.endswith()` | String ends with the specified value |<jupyter_code>number = "24579"
print(number.isnumeric())
letters = "PyTHoN"
print(letters.isnumeric())
movie = "2001: A SAMMY ODYSSEY"
book = "A Thousand Splendid Sharks"
poem = "sammy lived in a pretty how town"
print(movie.islower())
print(movie.isupper())
print(movie.startswith("20"))
print(movie.endswith("sSEY"))
print(book.istitle())
print(book.isupper())
print(poem.istitle())
print(poem.islower())<jupyter_output><empty_output><jupyter_text>String Formatting Operator **Old Way** (Python 2): still valid```python   “  %(format)” % (variable)```<jupyter_code>my_string = "There will be sunny day"
print("Big Announcement: %s tomorrow" %(my_string))
import math
print("My favorite integer is %i and my favorite float is %f,\n" \
    " which to three decimal places is %.3f and in exponential form is %e" \
     % (3,math.pi,math.pi,math.pi))<jupyter_output><empty_output><jupyter_text>> % escapes “%”<jupyter_code>print("I promise to give 100%% effort whenever asked of %s." % ("me"))<jupyter_output><empty_output><jupyter_text>> \+ and zero-padding<jupyter_code>print("%f\n%+f\n%f\n%010f\n%10s" % (math.pi,math.pi,-1.0*math.pi,math.pi,"pi"))<jupyter_output><empty_output><jupyter_text>**New Way** (Python 3)```pythonstring.format(value0,value1,....)```<jupyter_code>'On {}, I feel {}'.format("Saturday", "groovy")
'On {0}, I feel {1}'.format("Saturday", "groovy")
'On {0}, I feel {0}'.format("Saturday", "groovy")<jupyter_output><empty_output><jupyter_text>You can assign by argument position or by name:<jupyter_code>'{desire} to {place}'.format(desire='Fly me', place='the Moon')
'{desire} to {place} or else I wont visit {place}.'.format( \
                 desire='Fly me',place='the Moon')
f = {"desire": "I want to take you", "place": "funky town"}
'{desire} to {place}'.format(**f)<jupyter_output><empty_output><jupyter_text>**Formatting comes after a colon (:)**<jupyter_code>("%03.2f" % 3.14159) ==  "{:03.2f}".format(3.14159)
"{0:03.2f}".format(3.14159, 42)
"{1:03.2f}".format(3.14159, 42)<jupyter_output><empty_output><jupyter_text>Format also supports binary numbers:<jupyter_code>"int: {0:d};  hex: {0:x};  oct: {0:o};  bin: {0:b}".format(42)<jupyter_output><empty_output><jupyter_text>Type Casting- Type casting is the process of converting data from one type into another.- There are a number of functions built in to Python which allow us to do these type conversions on basic data types. **Convert to Integer**<jupyter_code>v1 = int(2.7)        # 2
v2 = int(-3.9)       # -3
v3 = int("2")        # 2
v4 = int("11", 16)   # 17, base 16
v5 = int(False)
print(v1, v2, v3, v4, v5)<jupyter_output><empty_output><jupyter_text>**Convert to Float**<jupyter_code>v6 = float(2)        # 2.0
v7 = float("2.7")    # 2.7
v8 = float("2.7E-2") # 0.027
v9 = float(False)    # 0.0
vA = float(True)     # 1.0
print(v6, v7, v8, v9, vA)<jupyter_output><empty_output><jupyter_text>**Convert to String**<jupyter_code>vB = str(4.5)        # "4.5"
vC = str(True)
print(vB, vC, type(vC))<jupyter_output><empty_output><jupyter_text>**Convert to Bolean**<jupyter_code>vD = bool(0)         #       False; 
vE = bool(3)         # True
vF = bool("PyTHoN")
vG = bool(list())
print(vD, vE, vF, vG)
int1 = 4

# 4 converted to float
float1 = int1 + 2.1 

# str1 = "My int:" + int1 
# Error: no implicit type conversion from int to string
str1 = "My int:" + str(int1)

int2 = 4 + True # 5: bool is implicitly converted to int
print("float1 = {} \n str1  = {} \n".format(float1, str1, int2))
age = 21
sign = 'You must be  {}-years-old to enter this bar'.format(age)
print(sign)<jupyter_output><empty_output><jupyter_text>Exercise Try to fix the code to print out the correct information by changing the string.<jupyter_code>s = "Hey there! what should this string be?"
# Length should be 20
print("Length of s = {}".format(len(s)))

# First occurrence of "a" should be at index 8
print("The first occurrence of the letter a = {}".format(s.index("a")))

# Number of a's should be 2
print("a occurs {} times".format(s.count("a")))<jupyter_output><empty_output>
{'fraction_non_alphanumeric': 0.1310438811665304, 'fraction_numerical': 0.03025347506132461, 'mean_word_length': 5.348096885813149, 'pattern_counts': {'":': 2, '<': 207, '<?xml version=': 0, '>': 210, 'https://': 0, 'lorem ipsum': 0, 'www.': 0, 'xml': 0}, 'pii_count': 0, 'substrings_counts': 3, 'word_list_counts': {'cursed_substrings.json': 7, 'profanity_word_list.json': 0, 'sexual_word_list.json': 0, 'zh_pornsignals.json': 0}}
{'chain_length': '50', 'dir': 'jupyter-structured-clean-dedup', 'id': '576356', 'license': 'MIT', 'n_tokens_mistral': 6544, 'n_tokens_neox': 6080, 'n_words': 2034, 'path': 'Python/1. Python Basics/Notebooks/0. Core Basics/0.1 Beginning to Code/2a. Python Data Types.ipynb', 'repo_name': 'okara83/Becoming-a-Data-Scientist', 'size': '18345'}