Expressions, Statements, and Input/Output in Python

In Python, understanding expressions, statements, and input/output (I/O) is essential for writing interactive and functional programs.


1. Expressions in Python

An expression is a combination of values, variables, operators, and function calls that evaluate to a single value.

Examples:

x = 10 + 5  # Expression: 10 + 5
area = 3.14 * (5 ** 2)  # Expression with multiplication and exponentiation
result = (10 > 5) and (5 < 8)  # Expression with logical operators

Expressions can be used inside print statements, assignments, and conditions.

print(2 * 3 + 5)  # Output: 11

Types of Expressions:

  1. Arithmetic Expressions: x + y * z
  2. Relational Expressions: a > b
  3. Logical Expressions: x and y
  4. String Expressions: 'Hello' + ' World'
  5. Function Call Expressions: len('Python')

2. Statements in Python

A statement is an instruction that Python can execute. Unlike expressions, statements do not return a value.

Types of Statements:

  1. Assignment Statement:
x = 10  # Assigns 10 to x
  1. Conditional Statement:
if x > 5:
    print("x is greater than 5")
  1. Loop Statement:
for i in range(5):
    print(i)
  1. Function Definition Statement:
def greet():
    print("Hello, Python!")
  1. Import Statement:
import math
print(math.sqrt(16))  # Output: 4.0

Statements are executed sequentially unless control flow mechanisms like loops or conditionals change the execution order.


3. Input in Python

The input() function allows users to enter data into a program.

Example:

name = input("Enter your name: ")
print("Hello, " + name + "!")

By default, input() returns a string. To accept numerical input, type conversion is needed:

age = int(input("Enter your age: "))
print("Next year, you will be", age + 1)

4. Output in Python

The print() function is used to display output on the screen.

Basic Example:

print("Hello, World!")

Using Variables in print():

name = "Alice"
age = 25
print("Name:", name, "Age:", age)

Formatted Output with f-strings:

name = "Bob"
age = 30
print(f"My name is {name} and I am {age} years old.")

Printing with sep and end Parameters:

print("Hello", "Python", sep="-", end="!")
# Output: Hello-Python!

5. Summary

Expressions evaluate to a value and can be used in operations.
Statements are executed sequentially and include assignments, loops, and conditionals.
Input in Python is handled using input().
Output is displayed using print(), with advanced formatting options.

Leave a Reply

Your email address will not be published. Required fields are marked *

Scroll to Top