In this lesson, you will master the foundational building blocks of programming: strings and numbers. By the end, you will understand how Python treats different types of data and how to manipulate them to perform calculations and process text.
At the core of every program, Python requires you to specify what kind of data you are handling. The two most fundamental types are integers (whole numbers like 5 or -10) and floats (numbers with decimal points like 3.14). When you need to represent text, you use strings, which are sequences of characters enclosed in quotation marks.
Python is a statically inferred language, meaning it determines the type of a variable based on the value assigned to it. However, you cannot perform mathematical operations between incompatible typesβfor example, trying to add a string to an integer will result in a TypeError. Understanding these boundaries is the first step toward writing bug-free code.
One common pitfall is the difference between a number and a string representation of a number. While 5 is a math-ready integer, "5" is just text. You cannot perform operations like 5 * 5 on the latter without first converting it using type casting.
Python functions as a powerful calculator. Beyond basic addition () and subtraction (), it supports multiplication () and division (). A crucial detail for newcomers is that the division operator () always returns a float, even if the numbers divide perfectly. If you want to drop the decimal portion, you use floor division ().
You will also frequently use the modulo operator (), which returns the remainder of a division operation. This is incredibly useful for determining if a number is even or odd. Finally, Python includes an exponentiation operator () to handle powers, expressed as .
Strings in Python are immutable, meaning you cannot change a character once it is set. However, you can create new strings by joining them together, a process known as concatenation using the operator. If you need to repeat a string, you can simply multiply it by an integer.
To insert data into strings effectively, use f-strings (formatted string literals). By placing an f before the quote and wrapping variables in curly braces {}, Python evaluates the expression inside and converts it to a string automatically. This is significantly more readable and efficient than manual concatenation.
Programs often receive data as strings, especially when taking input from a user via the input() function. Because input() always returns a string, you must perform explicit type conversion if you need to perform math on that data. You use functions like int() or float() to convert a string representation into a numerical one.
Note: Always wrap your
input()calls in a conversion function if you plan to perform arithmetic. Forgetting to do so is a common cause of logic errors in beginner scripts.
int(), float()) to transform data when different types interact, especially after receiving user input.