Day 2: Data Types & String Manipulation

Data Types, Numbers, Operations, Type Conversions, f-Strings

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])

      • 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

  • Integers - Whole numbers

  • Floats - Numbers with decimal points

  • Boolean - True or False (Notice the capital T and F. They do not have quotes around them)

Type Error, Type Checking and Type Conversion

Functions

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

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

Type Checking

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

Type Conversion

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

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

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.

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 The spaces around the plus and minus signs here are optional (the code would work without them), but they make it easier to read.

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

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

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 (//)

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.

Remainder (%)

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

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: print (9 % 6 % 2)

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

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: -

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

  • 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

  • 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 -

  • 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

Rounding off Numbers

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

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 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

# 🚨 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.")

End of Day Project - Tip Calculator

Create a tip calculator showing the following elements:

Ugly code I know - hopefully it will improve :)

#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)

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:

Last updated

Was this helpful?