Basic Output in Python
The print() function is the most fundamental way to output content in Python. It displays text or values to the console.
print("Hello World")
In this example, the text inside the parentheses is enclosed in quotation marks. This tells Python to treat it as a string literal. The output will be:
Hello World
Variables
There are situations where you don't need quotation marks inside print(). This is where variables come in.
In Python, a single equals sign (=) is the assignment operator, while double equals (==) is used for comparison.
message = "Hello World"
print(message)
Here, the string "Hello World" is assigned to the variable message. Now message represents that string, and can be used directly in print(). The output remains the same.
User Input
The input() function allows users to enter data from the keyboard. Let's see how it works:
name = input("Enter your name: ")
print("You entered:", name)
This code prompts the user to enter their name, then displays what was entered.
Type Conversion
Python has several basic data types:
int- integer numbersfloat- decimal numbersstr- text strings
To convert between types, use the type name followed by parentheses containing the value to convert. Note that input() always returns a string (str).
age = int(input("Enter your age: "))
print("Your age is:", age)
Now the variable age contains an integer instead of a string.
Arithmetic Operations
Python supports standard mathematical operators:
| Operator | Operation |
|---|---|
| + | Addition |
| - | Subtraction |
| * | Multiplication |
| / | Division |
| % | Modulus (remainder) |
| ** | Exponentiation |
| // | Floor division |
These operators work with numeric types (int and float).
Practical Example: Simple Calculator
Let's combine everything we've learned to create a basic calculator:
num1 = int(input("Enter first number: "))
num2 = int(input("Enter second number: "))
print("Sum:", num1 + num2)
print("Difference:", num1 - num2)
print("Product:", num1 * num2)
print("Quotient:", num1 / num2)
This program takes two numbers as input and displays their sum, difference, product, and quotient.