Wednesday, January 6, 2021

Python - Data Type and Manipulate Strings (Day 2)

This is a 100 Days challenge to learn a new language (Python). 100 Days of Code - The Complete Python Pro Bootcamp 

I will post some notes to motivate myself to finish this challenge.


Data Type


String



Ex:
print("Hello"[0])
print("123" + "456")

Result:
H 123456


Ex:
# It will be a pure integer calculation if quotation marks are removed
print(123 + 456)

Result:
579


Ex:
# Adding underscores between numbers can help the large number to be
readable, and python will remove it once it was executed.
print(123_456)

Result:
123456


Float



* 3.14159

Boolean



* True
* False


Type Conversion


Checking the data type



* type()


Ex:
# Checking data type
print(type(123))
print(type("123"))

Result:
<class 'int'> <class 'str'>


Converting



Convert to String
    str(123)

String to float
    float("3.14")

String to integer
    int("123")


Mathematical Operations



+        addition
-         subtraction
*        multiplication
/         division
**      exponent


Ex:
# 2 to the power of 3
print(2 ** 3)

Result:
8


Ex:
# checking the type after division
# After division, the data type will turn into 'float' not 'integer'
print(type(9/3))

Result:
<class 'float'>


Also, the order matters. 
Order Rules: PEMDAS
        ()      Parentheses
        **     Exponents
        *       Multiplication
        /        Division
        +       Addition
        -        Subtraction


Manipulate



round()         Return the nearest integer
//                  Floor division


Ex:
print(round(2.66666, 2))
print(3 / 2)
print(3 // 2)

Result:
2.67 1.5 1



f-string



It is a handy way to concatenate and print string with different data type.


Ex:
score = 60
print(f"your score is { score }")

Result:
your score is 60


No comments:

Post a Comment