# Day 2: Data Types & String Manipulation

## Data Types

* Strings - Strings are unicode characters enclosed in quotes.
  * "Hello" is a string and as such we are able to pull out each character individually. This method of pulling out a particular element from a string is called **"SUBSCRIPTING"**\
    For example with the "Hello" string we will include the square brackets and identify which character we want (say the "e") we will write it as:

    * **`print("Hello" [1])`** -------> Remember we start counting always from 0 (binary) so H would be \[0] and o would be \[4]  **`print("Hello" [4])`**
    * <mark style="color:yellow;">We can also use negative numbers and the 'o' we can use \[-1] . So the last digit will always be -1 and f\then left from the last number would be -2.-3.-4 etc</mark>

* Integers - Whole numbers

* Floats - Numbers with decimal points

* Boolean - <mark style="color:green;">**True or False**</mark> (Notice the capital T and F. They do not have quotes around them)

## Type Error, Type Checking and Type Conversion

### Functions&#x20;

Think of it as some machine in a factory that you give it potatoes and out come chips. Now lets feed in a rock and we will get an error or a"TypeError"\
Just as we used the **len("hello")** function to count how many characters (5 in this case), if we triesd to use the len(4837) - we will get  type error. It was expecting a sting but it got integers !!! TypeError !!!

How can we check what **data types** we are using? We can use the type function. For example&#x20;

**`num_char = len(input("What is your name? ")`**\
**`print("Your name has " + num_char + "charachters")`**

From the below output we get a TypeError saying you cannot concatenate integers and strings but you can on strings only

![](https://3018064759-files.gitbook.io/~/files/v0/b/gitbook-legacy-files/o/assets%2F-LudO0LP3BbNbyBiBB3l%2F-MLvkyiBA3o7iL098Nle%2F-MLxxfSz03sgIc3Ar_3b%2Fimage.png?alt=media\&token=cd27d034-1389-4433-a4ac-4aaf5c0c49f1)

### <mark style="color:purple;">Type Checking</mark>

So, to check what data type it is - we can run the following:

**`print(type(num_char))`**\
**`<class 'int'>`**

**`print(type(len(input("What is your name"))))`**\
**`<class 'int'>`**

We can see that this function returns an 'Integer' data type

### <mark style="color:purple;">Type Conversion</mark>

Going back to our code that broke because we tried to concatenate a string with an integer

**`num_char = len(input("What is your name? ")`**\
**`print("Your name has " + num_char + "charachters")`**

We will **convert the integer to a string** using the **`str`** function

**`num_char = len(input("What is your name? "))`** \
**`new_num_char = str(num_char)`** \
**`print("Your name has " + new_num_char + " charachters")`**

![UPDATE: This is a cleaner and more elegant way IMHO](https://3018064759-files.gitbook.io/~/files/v0/b/gitbook-legacy-files/o/assets%2F-LudO0LP3BbNbyBiBB3l%2F-MZy_WTPoCRhAyVx45z9%2F-MZyb6IvFpkRKvQ5-0Y3%2Fimage.png?alt=media\&token=47ae78a8-59b6-4a9e-bb8f-5aa4a0e9e9d5)

Another example:

**`a = float(123)`**\
**`print(type(a))`** \
**`<class "float">`**

**`print( 70 + float("100.5"))`**\
**`170.5`**

**`print(str(70) + str(100))`**\
**`70100`**

## Data Types Exercises -2.1

![](https://3018064759-files.gitbook.io/~/files/v0/b/gitbook-legacy-files/o/assets%2F-LudO0LP3BbNbyBiBB3l%2F-MLy2K7JKr656HVQwrBr%2F-MLy2eCOvyp6zNaGqbQh%2Fimage.png?alt=media\&token=2f97bdeb-d478-445c-932a-abb3dc2f23b6)

![](https://3018064759-files.gitbook.io/~/files/v0/b/gitbook-legacy-files/o/assets%2F-LudO0LP3BbNbyBiBB3l%2F-MLy2K7JKr656HVQwrBr%2F-MLy2k5eogO9WuAjUBSF%2Fimage.png?alt=media\&token=5572f318-3d82-45b4-9b88-671ad2649d08)

**Hint**

1. Try to find out the data type of two\_digit\_number.
2. Think about what you learnt about subscripting.
3. Think about type conversion.

![](https://3018064759-files.gitbook.io/~/files/v0/b/gitbook-legacy-files/o/assets%2F-LudO0LP3BbNbyBiBB3l%2F-MLy2K7JKr656HVQwrBr%2F-MLyAjCQkr2ViLzsSz8J%2Fimage.png?alt=media\&token=018fabc4-a4ba-4ef0-9830-387d61581b85)

![](https://3018064759-files.gitbook.io/~/files/v0/b/gitbook-legacy-files/o/assets%2F-LudO0LP3BbNbyBiBB3l%2F-MZtdQn-SrkNOVBQwxdD%2F-MZwvu6wQmqPw1oX8yMe%2Fimage.png?alt=media\&token=1c4cb9e5-031f-4099-9961-88aa656e7426)

Ahem...\<cough>\<cough> .. I started this course 3 times as I left it for a while and forgot how to do stuff so kept starting at the beginning... the last bit of code was on my 3rd attempt which I think is cleaner than the original just above it. The orange was to remind what data type the 'input' was - and as usual , its ALWAYS a string (even though you ask for a number, it will always be a string ............ :)

## Mathematical Operations

## Simple Operations

Python has the capability of carrying out calculations. \
Enter a calculation directly into the print statement:\
`print(2 + 2)`         Answer = 4\
`print(5 + 4 - 3)` Answer = 6\
&#x20;The spaces around the plus and minus signs here are **optional** (the code would work without them), but they make it easier to read.

&#x20;Python also carries out multiplication and division, using an **asterisk \*** to indicate multiplication and a **forward slash /** to indicate division.\
\
Use **parentheses** to determine which operations are performed first.\
print (2\*(3+4))       Answer = 14\
print (10/2)            Answer = 5.0

&#x20;Using a **single slash** to divide numbers produces a decimal (or **float**, as it is called in programming)

![](https://3018064759-files.gitbook.io/~/files/v0/b/gitbook-legacy-files/o/assets%2F-LudO0LP3BbNbyBiBB3l%2F-MM09xu1gYYE2o7AiUM1%2F-MM0AHLUXD34v7KALQz5%2Fimage.png?alt=media\&token=869f9cac-9b27-40b9-bd6b-e8f682fd4f29)

The order of their appearance is not accidental. We'll talk more about it once we've gone through them all.

### Exponentiation (\*\*)

A double asterisk `**` sign is an exponentiation operator

`print( 2**5 )`\
`print( 9 ** (1/2) )`

You can chain exponentiations together. In other words, you can rise a number to multiple powers. For example **2\*\*3\*\*2**

### **Quotient (//)**

&#x20;**Floor division** is done using two forward `//` slashes and is used to determine the **quotient** of a division (the quantity produced by the division of two numbers).\
Remember, this returns an **INTEGER (a  whole number!!)**\
\
**For example:**\
`print( 20 // 6 )` `Ans = 3` \[6 goes into 20 three times] remainder 2 but we check if the remainder is 2, rounded off to the **LESSER** integer, so the answer remain a= 3 \
You can also use floor division on floats.

{% hint style="danger" %}
Lets look at \
`print (6//4)  Ans = 1`\
`print (6.//4) Ans = 1.0`

There are 2 things at play here:

* Remember when we divide an integer by an integer we **ALWAYS** get a float as the result. Here, using the **QUOTIENT or FLOOR DIVISION** the we can see that we get **another integer!!! VERY IMPORTANT.**\
  **To check:**\
  \&#xNAN;*print(type(6//4))*\
  *\<class 'int'>*
* The second thing is that the ***real result*** of 6 /4 is  **1.5** But because we are doing floor division (//)  the actual answer is 1!! How did we get 1? The rule with floor quotients is that the result of the integer division is **ALWAYS ROUNDED OFF** to the **LESSER** integer!! In this case the real answer is 1.5 and normally we would round this of to 2, but we have to go to the lesser integer - so in this case its 1

**NOW!!! Lets try this**:

`print (6 //`**`-4`**`)   Ans =`` `**`-2`**&#x20;

How did we get a 2 here ? Well if we divide this the **real** answer is -1.5 and we are doing floor division so we will be **ROUNDING OFF TO THE LESSER** integer, and so in this case the lesser integer would then be **`-2`** :)
{% endhint %}

### Remainder (%)

&#x20;The **modulo operator** is carried out with a percent symbol (%) and is used to get the **remainder** of a division.\
\
**For example:**

`print(20 % 6)      Ans = 2` \
`20 // 6 = 3` \
`3*6 = 18` \
`20-18=2`

`print(1.25 % 0.5)  Ans = 0.25`\
`1.25 // 0.5 = 2.0`\
`2.0 * 0.5 = 1.0`\
`1.25 -1 = 0.25`

`print(12 % 4.5)     Ans = 3.0`\
`12 // 4.5 = 2.0`\
`2 * 4.5 =9.0`\
`12 - 9.0 = 3.0`

**Remember integer divided by a float is always a float !!**

### **Operators and their Binding**&#x20;

Don't forget **PEMDAS(Parentheses, Exponents, Multiplication and Division\[left to right], Addition and Subtraction\[left to right])** when it comes to figuring which to do first :) **PEMDASLR - (LR=Left to Right)**

The binding of the operator determines the order or computations performed by some operators with equal priority, put side by side in one expression.\
Most of Pythons options have **left-sided** binding, which means that the calculation of expressions is handled from **left to right**. For example:\
\&#xNAN;**`print (9 % 6  %  2)`**

![](https://3018064759-files.gitbook.io/~/files/v0/b/gitbook-legacy-files/o/assets%2F-LudO0LP3BbNbyBiBB3l%2F-MM09xu1gYYE2o7AiUM1%2F-MM0AjEfIJI3Er0roLZV%2Fimage.png?alt=media\&token=9af9499d-f14c-4447-8a6e-82a1c836f4b1)

As can be seen, this occurs by Python using the **left-sided binding -** But there is **one** interesting exception!! - EXPONENTIATION

### Exponentiation - Use Right-Sided Binding

**`print (2 ** 2 ** 3)`**

**`2**3 = 8`**\
**`2**8 = 256`**

### Operators and Parentheses

&#x20;`print((5 * ((25 % 13) + 100) / (2 * 13)) // 2)`\
`print[((5 * ((25 % 13) + 100) / 26]` \
`25 // 13 = 1, remainder 12`\
\
`12 + 100 = 112`\
`112 * 5  = 560`\
`---------------`\
`560 / 26 = 21.53`\
`21.53 // 2`\
\
`Answer = 10.0`

### List of Priorities

#### Learnt Lists of Priorities so far: -

![](https://3018064759-files.gitbook.io/~/files/v0/b/gitbook-legacy-files/o/assets%2F-LudO0LP3BbNbyBiBB3l%2F-MM09xu1gYYE2o7AiUM1%2F-MM0Az0BpbO8me8eisw-%2Fimage.png?alt=media\&token=41f66a66-230c-4553-ade4-b475e977676e)

## Key Takeaways

* An EXPRESSION is a combination of values (or variables, operators, calls to functions) which evaluates to a value eg `( 1 + 2 )`
* Operators are special symbols or keywords which are able to operate on the values and perform (mathematical) operations eg the `*` operator multiplies 2 values `x * y`&#x20;
* Arithmetic operators `(+, -, *, /)` returns a float if ONE of the values is of the float type
  * `%` (modulus - divides left operand by right operand and returns the remainder of the operation eg. 5 % 2 = 1
  * `**` Exponentiation - left operand raised to the power or right operand eg. `2 * *3 = 8`
  * / / Floor/integer division - returns a number resulting from division, but rounded DOWN to the nearest whole number eg `3 // 2.0 = 1.0`&#x20;
* A **unary** operator is an operator with only 1 operand eg `-1` or `+3`
* A **binary** operator is an operator with 2 operands eg. `4 + 5,` or `12 % 5`
* Some operators act before others - **the hierarchy of priorities**
  * unary `+` and `-` have the highest priority
  * then \*\*,  then \*  ,  /  , and %  and then the lowest priority: binary `+` and `-`&#x20;
* Sub-expressions in parenthesis are always calculated first eg `15 - 1 * (5 * (1 + 2)) = 0`
* The exponentiation operator uses **right-sided binding** eg `2 ** 2 ** 3 = 256`

## BMI Calculator Challenge

![](https://3018064759-files.gitbook.io/~/files/v0/b/gitbook-legacy-files/o/assets%2F-LudO0LP3BbNbyBiBB3l%2F-MLy2K7JKr656HVQwrBr%2F-MLz-5godwj2bBCc6A1C%2Fimage.png?alt=media\&token=c0cec0ea-59c9-4a15-8411-ee499a5fc9a2)

![](https://3018064759-files.gitbook.io/~/files/v0/b/gitbook-legacy-files/o/assets%2F-LudO0LP3BbNbyBiBB3l%2F-MLy2K7JKr656HVQwrBr%2F-MLyzlWVXX25gVM6_pAB%2Fimage.png?alt=media\&token=38539f07-fe42-436b-b0b9-4a95be0d946c)

## Rounding off Numbers

We use the "round" function with a parameter indicating to how many digits we want to round off to.\
For example: &#x20;

**`print (8 / 3)`**\
**`2.666666666`**

We could convert this to an integer

**`print(int( 8 / 3))`**\
**`2`**

But instead we will use the 'round' function to 2 decimal places

**`print(round(8 /3,   2)`**\
**`2.67`**

Lets say we saved the results of this calculation into a variable instead:

result = 4 / 2\
We can continue performing calculations on this variable. SO for example we used the initial result of 4/2 which equals to 2 and we wanted to divide this again by 2 we could say **`"result / = 2"`**

SO lets say we are want to keep  a users score in a game\
`score = 0`

`#User scores a point`\
`score = score + 1 -----> We can write this as:`\
\
`score + = 1`\
`[We can use this in all types eg`\
`score -+ 1`\
`score *= 1`\
`score /= 1`\
\
`print(score)`\
`Really handy where you have to manipulate a value based on its PREVIOUS value`

## f-String

An f-String makes it really easy to **MIX strings and different data types**. So far if we wanted to print different data types we had to convert them to integers or strings etc, \
This is where the F-String does this automatically in the background which makes it so much easier instead of us having to make all these conversions etc.\
For example:

`score = 0`\
`print( "Your score is " + score) ------ get DataType error`\
`print ( " Your score is " + str (score)) ----- O, Data Types are the same`

Step up the F-String  - where you place an '**f' in FRONT** of the double quotes and the **variables INSIDE CURLY brackets**\
\&#xNAN;**`score = 0`**\
**`height = 1.8`**\
**`isWinning = True`**\
\
**`Here we have three different data types, an integer, a float and a Boolean`**\
**`and in FRONT of the double quotes of a string`**\
**`print(f" Your score is {score}, your height is {height}, and you are winning is {isWinning}")`**\
\
**`Your score is 0, your height is 1.8 and you are winning is True`**

### Coding Challenge = Life in Weeks

![](https://3018064759-files.gitbook.io/~/files/v0/b/gitbook-legacy-files/o/assets%2F-LudO0LP3BbNbyBiBB3l%2F-MM0BiGHZDgo6tFTJEZY%2F-MM0U-Dy1Iui6jytyMDe%2Fimage.png?alt=media\&token=b46d4ceb-e30a-4b80-afc6-7a3689d9fae9)

![](https://3018064759-files.gitbook.io/~/files/v0/b/gitbook-legacy-files/o/assets%2F-LudO0LP3BbNbyBiBB3l%2F-MM0BiGHZDgo6tFTJEZY%2F-MM0UPHKfXvn0K5wOLx9%2Fimage.png?alt=media\&token=d49ea882-5115-4eea-b3e4-bde9765cae69)

![](https://3018064759-files.gitbook.io/~/files/v0/b/gitbook-legacy-files/o/assets%2F-LudO0LP3BbNbyBiBB3l%2F-MM0BiGHZDgo6tFTJEZY%2F-MM0ahQrUOLvh9iblCIG%2Fimage.png?alt=media\&token=9e7bbfdd-6085-4280-9177-a31124494a58)

{% tabs %}
{% tab title="My Solution" %}

```
# 🚨 Don't change the code below 👇
age = input("What is your current age? ")
# 🚨 Don't change the code above 👆

#Write your code below this line 👇
yrs = 90 - int(age)
months = yrs*12
weeks = yrs*52
days = yrs*365


print(f"You have {days} days, {weeks} weeks, and {months} months left.")
```

{% endtab %}

{% tab title="Angela's Solution" %}

```
# 🚨 Don't change the code below 👇
age = input("What is your current age? ")
# 🚨 Don't change the code above 👆

#Write your code below this line 👇
#----------------------------------
age_as_int = int(age)

years_remaining = 90 - age_as_int
days_remaining = years_remaining*365
weeks_remaining = years_remaining*52
months_remaining = years_remaining*12

message = f"You have {days_remaining} days, {weeks_remaining} weeks, {months_remaining} months left"
print(message)



```

{% endtab %}
{% endtabs %}

## End of Day Project - Tip Calculator

Create a tip calculator showing the following elements:

![](https://3018064759-files.gitbook.io/~/files/v0/b/gitbook-legacy-files/o/assets%2F-LudO0LP3BbNbyBiBB3l%2F-MM0BiGHZDgo6tFTJEZY%2F-MM1o0XbbPNxprrJBi47%2Fimage.png?alt=media\&token=256e2726-eb4f-445e-8906-2503ed9bf7fc)

![Ugly code I know - hopefully it will improve :)](https://3018064759-files.gitbook.io/~/files/v0/b/gitbook-legacy-files/o/assets%2F-LudO0LP3BbNbyBiBB3l%2F-MM0BiGHZDgo6tFTJEZY%2F-MM1p6NztQz_uPIQlRxf%2Fimage.png?alt=media\&token=bec70aa0-b89d-46b8-ae6f-a8da26bb5d54)

{% tabs %}
{% tab title="My Solution" %}

```
#If the bill was $150.00, split between 5 people, with 12% tip. 
#Each person should pay (150.00 / 5) * 1.12 = 33.6
#Format the result to 2 decimal places = 33.60
#Tip: You might need to do some research in Google to figure out how to do this.

print("Welcome to the tip calculator.")
bill_total = input("What was the total bill? R")
tip = input("What percentage tip would like to give? 10, 12, or 15? ")
people = input("How many people to split the bill? ")

tip_percent = (round(int(tip)/100, 2)) + 1
bill_with_tip = (round(float(bill_total) * tip_percent, 2))
each_pay = round(bill_with_tip/int(people), 2)
print("Each person should pay: R",each_pay)
```

{% endtab %}

{% tab title="Angela's Solution" %}

```
print("Welcome to the tip calculator!")

bill= float(input("What was the total bill? $"))
tip = int(input("How much tip would you like to give? 10, 12, 15? "))
people = int(input("How many people to split the bill?"))

tip_as_percent = tip/100
total_tip_amount = bill * tip_as_percent
total_bill = bill + total_tip_amount
bill_per_person = total_bill / people
final_amount = round(bill_per_person, 2)

print(f"Each person should pay ${final_amount}")


```

{% endtab %}

{% tab title="Updated Solution- Better??" %}

```
print("Welcome to the tip calculator.")
total_bill = float(input("What was the total bill? $"))
tip = int(input("What percentage tip would you like to give? 10, 12, or 15? "))
split = int(input("How many people to split the bill? "))

cost = total_bill * (1+(tip/100))
each_cost = round(cost/split, 2)

print(f"Each person should pay ${each_cost}")

-------------------------------------------------------
Welcome to the tip calculator.
What was the total bill? $3768.12
What percentage tip would you like to give? 10, 12, or 15? 12
How many people to split the bill? 7
Each person should pay $602.9
```

{% endtab %}
{% endtabs %}

As can be seen above - the round function gave a price for each person as $602.9 to pay whereby we want it to show $602.90.\
This is a formatting issue and not a rounding issue because the price was exactly $602.9. To fix this we use (good ol google search) a format function:

![](https://3018064759-files.gitbook.io/~/files/v0/b/gitbook-legacy-files/o/assets%2F-LudO0LP3BbNbyBiBB3l%2F-MZyqqS5RnFhRGvEkSr-%2F-MZyz139waLCKN10NioX%2Fimage.png?alt=media\&token=0888b84d-1362-4f04-9d0f-7a8187d3b1c8)

![](https://3018064759-files.gitbook.io/~/files/v0/b/gitbook-legacy-files/o/assets%2F-LudO0LP3BbNbyBiBB3l%2F-MZyqqS5RnFhRGvEkSr-%2F-MZyzF2TEb0RroqWJqRd%2Fimage.png?alt=media\&token=0b5d5b86-9444-43fd-9cb8-2d3703e17437)
