Contents

Python Quick Guide - Step 1: Basic Syntax and Data Types (2) - int, float

Info
  • This course is designed to help you learn the basics of Python programming as quickly as possible through hands-on practice.
  • The “Style Guide” sections primarily cover guidelines from PEP8 for writing clean Python code.
  • You can run and see the results of each code example.
    Feel free to experiment with the code - reloading the page will reset the content.
  • Python allows you to work with various kinds of data, such as strings and numbers. These different kinds of data are called types.
  • You can use the type() function to check the type of data.
  • From the execution result, we can see that the string "Hello!" is of type str and the number 100 is of type int.
  • In Python, there are two basic numeric types: integers (int) and floating-point numbers (float).
  • You can perform addition (+), subtraction (-), multiplication (*), and division (/) operations with numbers.
  • You can also use the print function to display numeric values on the screen.
  • You can also calculate the quotient (//) and remainder (%) in division.
  • You can also perform exponentiation (**) calculations.
📚 Exercise

BMI (Body Mass Index) is calculated by dividing weight (kg) by the square of height (m). Calculate and display the BMI for a person weighing 65kg with a height of 170cm.

Style Guide
  • For large numbers, you can use underscores (_) as digit separators
  • Put spaces before and after binary operators
  • You can use the int function to convert a decimal to an integer (removing the decimal portion).
  • You can use the float function to convert an integer to a decimal.
  • The int type has no upper or lower limit.
    • You can work with numbers of any size as long as memory allows.
  • With float type, you can use scientific notation.
    • For example, $3.14 \times 10^{5}$ can be written as 3.14e5.
  • The float type has upper and lower limits.
  • In float type, values exceeding the upper (lower) limit become inf (-inf).
  • In some operations, an OverflowError occurs if the calculation result exceeds the upper (lower) limit.
  • The float type also has limitations in precision.
  • Special care is needed for float calculations.

This type of error is called a “rounding error” and occurs because decimal numbers are represented internally in binary. For calculations requiring high precision, Python provides the Decimal data type.

📚 Exercise

The area of a circle is calculated by multiplying the square of the radius by pi ($\pi$).
Calculate the area of a circle with a diameter of 10cm, and display the result as an integer by truncating the decimal part. (Use 3.14 for pi)

Related Content