Python bootcamp Day002
Strings¶
From Day 001 we learned that strinds are declere with " or ' just like "Hello world". Now we can think of this string as a chain where every character is an individual entity and all of them are link together, this means that any character within a string is adressable by using an index.
For example: print("Hello"[0]) will print an H because it is the first character
print("Hello"[0])
print("Hello"[1])
print("Hello"[4])
H e o
Integer¶
This are numbre, without any decimals.
Unlike strings there is no need to add declaration, just type the numbers. To make the code human readable large number can be "separated " by underscore such as 1,500=1_500 and 1,000,000,000 = 1_000_000_000
print(12+3) #output:15
print(1_200+500) #output:1700
print(1_000_000_000) #output 1000000000
15 1700 1000000000
Type¶
Type Error¶
This errors occurs when you try to do an operation to the wrond data type.
For example: you will get "Type Error" if you try to concatenate a string and an integer. You will also get it if try toobtain the lenghg of an integer.
print("Hello"+24)
--------------------------------------------------------------------------- TypeError Traceback (most recent call last) Input In [3], in <cell line: 1>() ----> 1 print("Hello"+24) TypeError: can only concatenate str (not "int") to str
print(len(24))
Type Checking¶
The type function can be use to check the data type, the output says class but we will deal wih that later
type(24)
Type Conversion¶
(Type Casting)
There are some function that will change a data type to some other data type.
- str() will try to outout a string
- int() will try to outout a integer
num_char = len(input("What is your name?"))
print("Your name has " + num_char + " characters") #output: type error concatenation of string and int
Let's do some casting
num_char = len(input("What is your name?"))
new_num_char = str(num_char)
print("Your name has " + new_num_char + " characters")
Code Challenge¶
Instructions
Write a program that adds the digits in a 2 digit number. e.g. if the input was 35, then the output should be 3 + 5 = 8
Warning. Do not change the code on lines 1-3. Your program should work for different inputs. e.g. any two-digit number.
# π¨ Don't change the code below π
two_digit_number = input("Type a two digit number: ")
# π¨ Don't change the code above π
####################################
#Write your code below this line π
num0 = two_digit_number[0] #input allways outputs a string
num1 = two_digit_number[1] #input allways outputs a string
print(int(num0)+int(num1))
Mathematical operators in python¶
operacion | operator | example | notes | |
---|---|---|---|---|
sum | + | 5+3 = 8 | ||
minus | - | 5-3 = 2 | ||
times | * | 5*3 = 15 | ||
divison | / | 6/2 = 3.0 | Allways is a FLOAT | |
exponent | ** | 5**3 = 125 |
print(3 * 3 + 3 / 3 - 3) #output: 7.0 Division is allways flaot
Chancge previous code to output 3.0 instead of 7.0
print(3 * (3 + 3) / 3 - 3)
Code Chalenge - BMI Calculator¶
Instructions
Write a program that calculates the Body Mass Index (BMI) from a user's weight and height.
The BMI is a measure of some's weight taking into account their height. e.g. If a tall person and a short person both weigh the same amount, the short person is usually more overweight.
The BMI is calculated by dividing a person's weight (in kg) by the square of their height (in m):
Warning you should convert the result to a whole number.
# π¨ Don't change the code below π
height = input("enter your height in m: ")
weight = input("enter your weight in kg: ")
# π¨ Don't change the code above π
#Write your code below this line π
bmi = float(weight) / float(height)**2
print(int(bmi))
round() Function¶
This of course round a float into an integer. First argument is the float to round and 2nd argument is the amount of decimals in the rounding
print(round(10/3))
print(round(10/3,4))
Floor Division //¶
This operator does the same as using int to conver a float so:
print(10/3)
print(int(10/3))
print(10//3)
F strings¶
Also called “formatted string literals,” f-strings are string literals that have an f at the beginning and curly braces containing expressions that will be replaced with their values. The expressions are evaluated at runtime and then formatted using the format protocol. As always, the Python docs are your friend when you want to learn more.
Here are some of the ways f-strings can make your life easier.
score = 0
height = 1.8
is_winning = True
print(f"your score is {score}, your height is {height}, and your winning status is {is_winning}")
Exercise 3 - Life in Weeks¶
Instructions
I was reading this article by Tim Urban - Your Life in Weeks and realised just how little time we actually have.
https://waitbutwhy.com/2014/05/life-weeks.html
Create a program using maths and f-Strings that tells us how many days, weeks, months we have left if we live until 90 years old.
It will take your current age as the input and output a message with our time left in this format:
You have x days, y weeks, and z months left.
Where x, y and z are replaced with the actual calculated numbers.
Warning your output should match the Example Output format exactly, even the positions of the commas and full stops.
Example Input
56
Example Output
You have 12410 days, 1768 weeks, and 408 months left.
# π¨ 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_int = int(age)
years = 90 - age_int
days = years*365
weeks = years*52
months = years*12
print(f"You have {days} days, {weeks} weeks, and {months} months left.")
print("Welcome to the tip calculator")
bill = float(input("Whats was the total bill?"))
tip_per = int(input("What percentage tip would you like tu give?"))
split = int(input("How many people to split the bill?"))
bill_w_tip = (bill)*(1+tip_per/100)
payment = bill_w_tip / split
message = f"Each person should pay: ${round(payment,2)}"
print(message)
With a total bill of $150 and 12\% tip the final output is $33.6 instead of $33.60
This is a formating problem, use:
"{:.2f}".format(payment)
print("Welcome to the tip calculator")
bill = float(input("Whats was the total bill?"))
tip_per = int(input("What percentage tip would you like tu give?"))
split = int(input("How many people to split the bill?"))
bill_w_tip = (bill)*(1+tip_per/100)
payment = bill_w_tip / split
payment_2d = "{:.2f}".format(payment)
message = f"Each person should pay: ${payment_2d}"
print(message)
Comments
Post a Comment