The print and input functions in Python: a complete guide
The print and input functions are the main tools for user interaction in Python. They allow you to display information on the screen and receive data from the user, which makes the programs interactive and convenient.
Print function: data output to the screen
The print() function is designed to display information on the screen. It accepts any number of arguments and displays them with automatic space separation.
Basic syntax and examples:
# Simple text output
print("Hello, world!") # Hello, world!
# Output of multiple
print arguments("Name:", "Alice", "Age:", 30) # Name: Alice Age: 30
# Output of variables
name = "Bob"
age = 25
print("User:", name, "is", age, "years old")
Additional parameters of the print function:
The sep parameter allows you to change the separator between the elements.:
print("apple", "banana", "orange", sep=", ") # apple, banana, orange
print("2024", "12", "15", sep="-") # 2024-12-15
The end parameter defines the line ending character:
print("Hello, ", end="")
print("world!") # Hello, world!
print("Loading", end="...")
print("Done!") # Loading...Done!
String formatting:
F-strings are a modern way of formatting:
name = "Alice"
age = 30
salary = 50000.50
print(f"My name is {name}, I am {age} years old")
print(f"My salary: {salary:.2f} rubles")
Format() method:
print("Name: {}, Age: {}".format(name, age))
print("Name: {name}, Age: {age}".format(name=name, age=age))
input function: receiving data from the user
The input() function requests data input from the user and always returns a string (str). Explicit type conversion is required to work with numbers.
Basic usage examples:
# Simple input
name = input("Enter your name: ")
print(f"Hello, {name}!")
# Input converted to a number
age = int(input("Enter your age: "))
print(f"You are {age} years old")
# Input with float conversion
height = float(input("Enter your height in meters: "))
print(f"Your height: {height} m")
Input error handling:
try:
number = int(input("Enter a number: "))
print(f"You have entered: {number}")
except ValueError:
print("Error: enter the correct number")
Entering multiple values using split()
The split() method allows you to split a string into parts and get multiple values at the same time:
# Entering two numbers in one line
numbers = input("Enter two numbers separated by a space: ")
num1, num2 = numbers.split()
num1 = float(num1)
num2 = float(num2)
print(f"Sum: {num1 + num2}")
# Short form of writing
num1, num2 = map(float, input("Enter two numbers:").split())
print(f"Product: {num1 * num2}")
A practical example is a calculator:
# Requesting data from the user
values = input("Enter three numbers separated by a space: ")
a, b, c = map(float, values.split())
# Calculations
sum_result = a + b + c
average = sum_result / 3
# Output of results
print(f"Numbers: {a}, {b}, {c}")
print(f"Sum: {sum_result}")
print(f"Arithmetic mean: {average:.2f}")
Data types in Python
Python supports various types of data, which can be divided into simple and composite. Understanding data types is critical for proper operation of the input and print functions.
Simple data types
Integers (int):
positive_num = 42
negative_num = -17
zero = 0
print(type(positive_num)) #
print(f"Value: {positive_num}")
Real numbers (float):
pi = 3.14159
temperature = -10.5
scientific = 1.5e-4 # 0.00015
print(type(pi)) #
print(f"Number" {pi}")
Boolean type (bool):
is_student = True
is_working = False
print(type(is_student)) # <class 'bool'
print(f"Student status: {is_student}")
Strings (str):
single_quotes = 'Hello world!'
double_quotes = "Hello World!"
multiline = """This is a multi
-line string in Python"""
print(type(single_quotes)) #
print(f"String length: {len(single_quotes)}")
Data type conversion
Type casting is necessary to work with data correctly, especially when using the input function.
Main conversion functions:
# String conversion
number = 100
text = str(number)
print(f"Number as string: '{text}'")
# Convert to an integer
text_number = "42"
integer = int(text_number)
print(f"String as a number: {integer}")
# Conversion to float
decimal_text = "3.14"
decimal = float(decimal_text)
print(f"Decimal: {decimal}")
# Conversion to bool
print(bool(1)) # True
print(bool(0)) # False
print(bool("")) # False
print(bool("text")) # True
Dynamic change of variable type:
variable = 10 # int
print(f"Type: {type(variable)}, value: {variable}")
variable = str(variable) # str
print(f"Type: {type(variable)}, value: '{variable}'")
variable = float(variable) # float
print(f"Type: {type(variable)}, value: {variable}")
math library: advanced mathematical functions
The math module provides access to mathematical functions and constants defined in the C standard.
Import and basic constants:
import math
# Basic constants
print(f"π = {math.pi}") # 3.141592653589793
print(f"e = {math.e}") # 2.718281828459045
print(f"τ = {math.tau}") # 6.283185307179586 (2π)
print(f"∞ = {math.inf}") # inf
print(f"NaN = {math.nan}") # nan
Rounding functions and integer operations:
import math
x = 4.7
y = -3.2
print(f"ceil({x}) = {math.ceil(x)}") # 5 (up)
print(f"floor({x}) = {math.floor(x)}") # 4 (down)
print(f"trunk({y}) = {math.trunk(y)}") # -3 (towards zero)
# Factorial and NODE
print(f"5! = {math.factorial(5)}") # 120
print(f"NODE(48, 18) = {math.gcd(48, 18)}") # 6
Power and logarithmic functions:
import math
# Power functions
print(f"√16 = {math.sqrt(16)}") # 4.0
print(f"2³ = {math.pow(2, 3)}") # 8.0
print(f"∛27 = {math.pow(27, 1/3)}") # 3.0
# Logarithms
print(f"log₁₀(100) = {math.log10(100)}") # 2.0
print(f"ln(e) = {math.log(math.e)}") # 1.0
print(f"log₂(8) = {math.log2(8)}") # 3.0
Trigonometric functions:
import math
angle = math.pi / 4 # 45 degrees in radians
print(f"sin(45°) = {math.sin(angle):.3f}") # 0.707
print(f"cos(45°) = {math.cos(angle):.3f}") # 0.707
print(f"tan(45°) = {math.tan(angle):.3f}") # 1.000
# Converting degrees to radians and back
degrees = 90
radians = math.radians(degrees)
print(f"{degrees}° ={radians} rad")
print(f"{radians} rad = {math.degrees(radians)}°")
Practical examples of programs
Example 1: Calculating the area and perimeter of a rectangle
import math
# Data entry
length = float(input("Enter rectangle length:"))
width = float(input("Enter rectangle width:"))
# Calculations
area = length * width
perimeter = 2 * (length + width)
diagonal = math.sqrt(length**2 + width**2)
#
Print output(f"Area: {area:.2f}")
print(f"Perimeter: {perimeter:.2f}")
print(f"Diagonal: {diagonal:.2f}")
Example 2: Temperature converter
# Temperature input
celsius = float(input("Enter temperature in degrees Celsius: "))
# Transformations
fahrenheit = (celsius * 9/5) + 32
kelvin = celsius + 273.15
# Output
of print(f"{celsius}°C = {fahrenheit:.1f}°F")
print(f"{celsius}°C = {kelvin:.1f}K")
Example 3: Solving a quadratic equation
import math
print("Solving the quadratic equation ax2 + bx + c = 0")
# Entering coefficients
a = float(input("Enter coefficient a:"))
b = float(input("Enter coefficient b:"))
c = float(input("Enter coefficient c:"))
# Checking and calculating the discriminant
if a == 0:
print("This is not a quadratic equation (a = 0)")
else:
discriminant = b**2 - 4* a*c
print(f"Discriminant: {discriminant}")
if discriminant > 0:
x1 = (-b + math.sqrt(discriminant)) / (2*a)
x2 = (-b - math.sqrt(discriminant)) / (2*a)
print(f"Two roots: x₁ = {x1:.3f}, x₂ = {x2:.3f}")
elif discriminant == 0:
x = -b / (2*a)
print(f"One root: x = {x:.3f }")
else:
print("There are no roots (the discriminant is negative)")
Optimization tips and best practices
- Always check user input for correct data types
- Use f-strings for modern output formatting
- Import only the necessary functions from math to save memory:
from math import sqrt, pi - Add descriptive hints to input functions for a better UX
- Round up the results to a reasonable number of decimal places
Mastering the print and input functions, understanding data types, and using the math library create a solid foundation for creating interactive Python programs of any complexity.