Day 02

Data Types, f-string -Tip Calculator

While python doesn't require you to declare your variable along with the data type, the following data types are supported.

Data Types

image.png

myString = "helu"  #strings need quotes
myNum = 123  #numbers do not
myFloat = 3.141  # neither do floats
flag = True  #Boolean

Concatenating and Printing

When you use values and variable in the print statements, depending upon their type, the print statement behaves accordingly.


print("hello" + "world")
#helloworld - both values are strings so concatenated

print(10 + 20)
#30 - performs the operation and returns the result

print("10" + "20")
#1020 - treats both as string and concats

print("hello" + 11)
#TypeError - doesn't know how to add a string and int

Type Errors

TypeErrors are raised whenever an operation is performed between incorrect/unsupported object type. Basically if you try to add a string and int, it is a TypeError.

How to deal with this? Check the type and convert all values to the type you want.


print(type("hello"))
#<class 'str'>

print(type(13))
#<class 'int'>

Type Casting

Type casting is converting your variable from one data type to the other.


my_num = 10
type(my_num)  #<class 'int'>

my_str_num = str(my_num)
type(my_str_num)  #<class 'str'>

The input function returns values of the type . So even if the user inputs a int, you have to type case it to a value. A common practice is:


lucky_num = int(input("Enter you lucky number"))

Math operations

image.png

f-strings

When you have to display a string that consists of various variables and text in it, concatenating them with '+' and keeping track of all the ' ' can be a pain.

f-string to the rescue. They allow us to easily embed variable and even logic in our string.


lucky_num1 = 7
lucky_num2 = 13

print(f'Is your lucky number {lucky_num1} or {lucky_num2} or {lucky_num1 + lucky_num2}? ')
#Is your lucky number 7 or 13 or 20?

Variable are enclosed within {}.

Project - Tip Calculator

02-op.png

02-ip.png