Sample Programs

  1. Write a program to take two numbers as input and print their sum.
    x = int(input("Enter first number: "))
    y = int(input("Enter second number: "))
    print("Sum of", x, "and", y, "is", x + y)

    Output

    Enter first number: 3
    Enter second number: 2
    Sum of 3 and 2 is 5
  2. Write a program to check if a number is positive, negative, or zero.
    num = int(input("Enter a number: "))
    if num > 0:
    print("The number is positive.")
    elif num == 0:
    print("The number is zero.")
    else:
    print("The number is negative.")

    Output

    Enter a number: -4
    The number is negative.
  3. Write a program to ask for user age and determine if they are an adult or not.
    age = int(input("How old are you? "))
    if age >= 18:
    print("You are an adult!")
    else:
    print("You are a teenager or a kid.")

    Output

    How old are you? 20
    You are an adult!
  4. Write a Python program to create a new file and write a message into it.
    file = open("message.txt", "w")
    file.write("Hello, welcome to file handling in Python!")
    file.close()
    print("File created and message written successfully.")

    Output

    File created and message written successfully.
In the last one, "w" means write mode. It makes message.txt if it is missing and wipes it if it already exists, so always close() the file when you are done.

A Few More Worth Trying

  1. Write a program using a function to find the area of a rectangle.
    def area(length, width):
    return length * width

    print("Area:", area(5, 8))

    Output

    Area: 40
  2. Write a program using the math library to find the square root of a number entered by the user.
    import math
    n = float(input("Enter a number: "))
    print("Square root is", math.sqrt(n))

    Output

    Enter a number: 256
    Square root is 16.0
  3. Write a program that guesses a random number between 1 and 10.
    import random
    secret = random.randint(1, 10)
    guess = int(input("Guess a number between 1 and 10: "))
    if guess == secret:
    print("You got it!")
    else:
    print("Wrong, it was", secret)

    Output

    Guess a number between 1 and 10: 4
    Wrong, it was 9
  4. Write a program that safely divides two numbers entered by the user.
    try:
    a = int(input("Numerator: "))
    b = int(input("Denominator: "))
    print("Result:", a / b)
    except ZeroDivisionError:
    print("You can't divide by zero!")
    except ValueError:
    print("Enter a valid number!")
    finally:
    print("Execution complete.")

    Output

    Numerator: 10
    Denominator: 0
    You can't divide by zero!
    Execution complete.