Python Programming Examples: Concepts - Indentation, Comments, Variables, Data Types, Operators, and Expressions

Python Basics: Indentation, Comments, Variables, Data Types, Operators, and Expressions

This section provides 20 example problems that help you understand basic concepts in Python, such as indentation, comments, variables, reserved words, data types, operators, and expressions. We'll also demonstrate Python's basic input and output, including f-strings.

Indentation and Comments

Example 1: Simple Indentation

Question: Write a Python script named simple_indentation.py that displays "Hello, Python!" only if a variable is set to True.

# This script demonstrates indentation
show_message = True

if show_message:
    print("Hello, Python!")

Sample Output:

C:\> python simple_indentation.py
Hello, Python!
C:\>

    

Description: This script checks if show_message is True and then prints a message. The correct indentation is crucial for Python to understand which code belongs to the if block.

πŸ’‘

Hint: Python uses indentation to define code blocks. Ensure that all lines within a block are indented equally.

Example 2: Indentation with Multiple Conditions

Question: Create a Python script named check_conditions.py that checks if two variables are both True and prints a message if they are.

# Checking multiple conditions with proper indentation
condition1 = True
condition2 = True

if condition1:
    if condition2:
        print("Both conditions are True.")

Sample Output:

C:\> python check_conditions.py
Both conditions are True.
C:\>

    

Description: This script demonstrates how to use indentation to nest if statements. The inner block is executed only if both conditions are True.

πŸ’‘

Trivia: In Python, incorrect indentation will raise an IndentationError, preventing the script from running.

Example 3: Adding Comments

Question: Write a Python script named use_comments.py that calculates the sum of two numbers and includes comments explaining the steps.

# This script calculates the sum of two numbers

# Assign values to the variables
num1 = 10
num2 = 20

# Calculate the sum
sum = num1 + num2

# Display the result
print(f"The sum of {num1} and {num2} is {sum}.")

Sample Output:

C:\> python use_comments.py
The sum of 10 and 20 is 30.
C:\>

    

Description: This script uses comments to explain each step of the process. Comments are crucial for making your code understandable to others (and to yourself in the future).

πŸ’‘

Tip: Use comments to explain why you’re doing something, not just what you’re doing. This makes your code more maintainable.

Variables and Reserved Words

Example 4: Using Variables

Question: Create a Python script named use_variables.py that assigns your name and age to variables and then prints them.

# Assigning values to variables
name = "Alice"
age = 30

# Displaying the values
print(f"Name: {name}")
print(f"Age: {age}")

Sample Output:

C:\> python use_variables.py
Name: Alice
Age: 30
C:\>

    

Description: Variables are used to store data that can be referenced and manipulated later in the script. This example demonstrates how to create and use variables.

Example 5: Reserved Words

Question: Write a Python script named reserved_words.py that demonstrates reserved words by using a valid variable name and an invalid one.

# This will work
variable = 10

# This will raise an error because 'class' is a reserved word
# class = 20

Sample Output:

C:\> python reserved_words.py
Traceback (most recent call last):
  File "reserved_words.py", line 7, in 
    class = 20
          ^
SyntaxError: invalid syntax
C:\>

    

Description: Reserved words are words that have a special meaning in Python and cannot be used as variable names. This script shows the difference between a valid variable name and an invalid one.

πŸ’‘

Hint: Reserved words in Python include if, else, while, for, class, def, and many more. Always avoid using these as variable names.

Example 6: Variable Naming Conventions

Question: Write a Python script named variable_naming.py that demonstrates good and bad variable naming practices.

# Good variable names
first_name = "Alice"
age = 30

# Bad variable names
# 2nd_name = "Bob"  # Starts with a number
# my-variable = 25  # Contains a hyphen

Sample Output:

C:\> python variable_naming.py
C:\>

    

Description: This script shows examples of good and bad variable naming practices. Good variable names are descriptive, start with a letter or underscore, and do not contain spaces or special characters.

πŸ’‘

Tip: Use descriptive variable names that make it easy to understand what the variable represents. This improves the readability of your code.

Data Types and Operators

Example 7: Basic Data Types

Question: Create a Python script named basic_data_types.py that demonstrates the use of integers, floats, and strings.

# Integer
num1 = 10

# Float
num2 = 20.5

# String
text = "Hello, Python!"

# Displaying the values
print(f"Integer: {num1}")
print(f"Float: {num2}")
print(f"String: {text}")

Sample Output:

C:\> python basic_data_types.py
Integer: 10
Float: 20.5
String: Hello, Python!
C:\>

    

Description: Python has various data types, including integers, floating-point numbers, and strings. This example demonstrates how to use and display these basic data types.

πŸ’‘

Trivia: Python’s dynamic typing allows variables to hold different types of data at different times. This flexibility can make Python easier to use, but it also requires careful attention to the types of data your program is handling.

Example 8: String Concatenation

Question: Write a Python script named string_concatenation.py that concatenates two strings and prints the result.

# Storing strings
greeting = "Hello"
name = "Alice"

# Concatenating strings
message = greeting + ", " + name + "!"

# Displaying the concatenated string
print(message)

Sample Output:

C:\> python string_concatenation.py
Hello, Alice!
C:\>

    

Description: This script demonstrates string concatenation, which is the process of joining two or more strings together. The `+` operator is used for this purpose.

Example 9: Basic Arithmetic Operations

Question: Create a Python script named arithmetic_operations.py that performs addition, subtraction, multiplication, and division.

# Performing arithmetic operations
a = 15
b = 4

addition = a + b
subtraction = a - b
multiplication = a * b
division = a / b

# Displaying the results
print(f"Addition: {addition}")
print(f"Subtraction: {subtraction}")
print(f"Multiplication: {multiplication}")
print(f"Division: {division}")

Sample Output:

C:\> python arithmetic_operations.py
Addition: 19
Subtraction: 11
Multiplication: 60
Division: 3.75
C:\>

    

Description: This example demonstrates basic arithmetic operations using integers. Python supports `+`, `-`, `*`, and `/` for addition, subtraction, multiplication, and division, respectively.

Example 10: Operator Precedence

Question: Write a Python script named operator_precedence.py that evaluates an expression with multiple operators and displays the result.

# Evaluating an expression
result = 10 + 5 * 2

# Displaying the result
print(f"The result of 10 + 5 * 2 is {result}.")

Sample Output:

C:\> python operator_precedence.py
The result of 10 + 5 * 2 is 20.
C:\>

    

Description: Python follows the standard mathematical order of operations (PEMDAS: Parentheses, Exponents, Multiplication and Division, Addition and Subtraction) when evaluating expressions.

πŸ’‘

Hint: To change the order of operations, use parentheses. For example, (10 + 5) * 2 will yield a different result.

Expressions and Basic Input/Output

Example 11: Simple Expression

Question: Create a Python script named simple_expression.py that evaluates a simple expression and prints the result.

# Evaluating a simple expression
expression = 3 * (2 + 4)

# Displaying the result
print(f"The result of the expression is {expression}.")

Sample Output:

C:\> python simple_expression.py
The result of the expression is 18.
C:\>

    

Description: This script evaluates a simple mathematical expression and displays the result. The expression is enclosed in parentheses to ensure the correct order of operations.

Example 12: Combining Strings and Numbers

Question: Write a Python script named combine_string_number.py that combines a string and a number in a single print statement.

# Combining a string and a number
age = 25
message = "You are " + str(age) + " years old."

# Displaying the message
print(message)

Sample Output:

C:\> python combine_string_number.py
You are 25 years old.
C:\>

    

Description: This script demonstrates how to combine a string and a number by converting the number to a string using the str() function.

πŸ’‘

Tip: When combining strings and numbers in a print statement, you must convert the number to a string using str() or use an f-string.

Example 13: User Input and Simple Calculation

Question: Create a Python script named user_input_calculation.py that asks for two numbers and prints their sum.

# Asking for user input
num1 = input("Enter the first number: ")
num2 = input("Enter the second number: ")

# Calculating the sum
sum = int(num1) + int(num2)

# Displaying the result
print(f"The sum of {num1} and {num2} is {sum}.")

Sample Output:

C:\> python user_input_calculation.py
Enter the first number: 10
Enter the second number: 20
The sum of 10 and 20 is 30.
C:\>

    

Description: This script asks the user for two numbers, converts them to integers, calculates the sum, and then displays the result.

πŸ’‘

Hint: The input() function returns a string, so you need to convert the input to an integer using int() before performing arithmetic operations.

Example 14: Checking for Equality

Question: Write a Python script named check_equality.py that checks if two numbers are equal and prints a message.

# Assigning values to variables
a = 5
b = 10

# Checking for equality
are_equal = a == b

# Displaying the result
print(f"Are the numbers {a} and {b} equal? {are_equal}")

Sample Output:

C:\> python check_equality.py
Are the numbers 5 and 10 equal? False
C:\>

    

Description: This script checks if two numbers are equal using the equality operator == and prints the result.

Example 15: Comparing Two Numbers

Question: Create a Python script named compare_numbers.py that compares two numbers and prints whether the first is greater than, less than, or equal to the second.

# Assigning values to variables
a = 15
b = 10

# Comparing the numbers
is_greater = a > b
is_less = a < b
is_equal = a == b

# Displaying the results
print(f"Is {a} greater than {b}? {is_greater}")
print(f"Is {a} less than {b}? {is_less}")
print(f"Are {a} and {b} equal? {is_equal}")

Sample Output:

C:\> python compare_numbers.py
Is 15 greater than 10? True
Is 15 less than 10? False
Are 15 and 10 equal? False
C:\>

    

Description: This script demonstrates how to use comparison operators to compare two numbers and display the results.

πŸ’‘

Hint: Python provides several comparison operators: == (equality), != (inequality), > (greater than), >= (greater than or equal to), < (less than), and <= (less than or equal to).

Example 16: Calculating the Area of a Rectangle

Question: Write a Python script named area_rectangle.py that calculates the area of a rectangle given its length and width.

# Assigning values to length and width
length = 5
width = 10

# Calculating the area
area = length * width

# Displaying the area
print(f"The area of the rectangle is {area}.")

Sample Output:

C:\> python area_rectangle.py
The area of the rectangle is 50.
C:\>

    

Description: This script calculates the area of a rectangle by multiplying its length and width and then prints the result.

Example 17: Temperature Conversion

Question: Create a Python script named convert_temperature.py that converts a temperature from Celsius to Fahrenheit.

# Asking for temperature in Celsius
celsius = input("Enter temperature in Celsius: ")

# Converting to Fahrenheit
fahrenheit = (float(celsius) * 9/5) + 32

# Displaying the result
print(f"{celsius}°C is equal to {fahrenheit}°F")

Sample Output:

C:\> python convert_temperature.py
Enter temperature in Celsius: 25
25°C is equal to 77°F
C:\>

    

Description: This script converts a temperature from Celsius to Fahrenheit using the formula (C * 9/5) + 32 and then prints the result.

πŸ’‘

Hint: Use float() to convert the string input to a floating-point number before performing arithmetic operations.

Example 18: Calculating the Perimeter of a Rectangle

Question: Write a Python script named perimeter_rectangle.py that calculates the perimeter of a rectangle given its length and width.

# Assigning values to length and width
length = 7
width = 3

# Calculating the perimeter
perimeter = 2 * (length + width)

# Displaying the perimeter
print(f"The perimeter of the rectangle is {perimeter}.")

Sample Output:

C:\> python perimeter_rectangle.py
The perimeter of the rectangle is 20.
C:\>

    

Description: This script calculates the perimeter of a rectangle by adding the length and width and then multiplying by 2.

Example 19: Calculating Simple Interest

Question: Create a Python script named simple_interest.py that calculates the simple interest given the principal, rate of interest, and time.

# Assigning values to principal, rate, and time
principal = 1000
rate = 5
time = 2

# Calculating simple interest
interest = (principal * rate * time) / 100

# Displaying the interest
print(f"The simple interest is {interest}.")

Sample Output:

C:\> python simple_interest.py
The simple interest is 100.0.
C:\>

    

Description: This script calculates the simple interest using the formula (P * R * T) / 100 and then prints the result.

Example 20: Calculating the Average of Three Numbers

Question: Write a Python script named average_numbers.py that calculates the average of three numbers.

# Assigning values to three numbers
num1 = 10
num2 = 20
num3 = 30

# Calculating the average
average = (num1 + num2 + num3) / 3

# Displaying the average
print(f"The average of {num1}, {num2}, and {num3} is {average}.")

Sample Output:

C:\> python average_numbers.py
The average of 10, 20, and 30 is 20.0.
C:\>

    

Description: This script calculates the average of three numbers by summing them and dividing by 3, then prints the result.

πŸ’‘

Tip: When working with averages, remember that dividing by the number of items will give you the mean. Be careful with integer division, which can truncate decimals if not using floats.