Python Basics Explained


Print Statement


    print("Hello, World!")
                

Hello, World!

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



Input, Processing, and Output

Input in Python

# Example of input, processing, and output in Python

    name = input("Enter your name: ")
    greeting = "Hello, " + name
    print(greeting)
                
# or to easily format

    name = input("Enter your name: ")
    greeting = (f"Hello, {name}")
    print(greeting)
                

If the user enters "Alice", the expected result would be "Hello, Alice".

This code snippet takes the user's name as input, processes it by creating a greeting, and then outputs it using the print function. Input in Python: This part explains how to use the input() function to take user input from the console and store it in a variable. It demonstrates how to prompt the user for their name and then greet them with it.


Processing in Python


        number1 = int(input("Enter first number: "))
        number2 = int(input("Enter second number: "))
        sum = number1 + number2
        print("The sum is", sum)

The sum of the two entered numbers is calculated and displayed.

Processing user input by converting it to integers and then performing an arithmetic operation. Processing in Python: Here, the focus is on processing user input. It shows how to read two numbers from the user, convert them to integers, and then calculate and display their sum. This section highlights the processing and manipulation of input data.


Input Validation in Python


    def get_valid_number(prompt):
        while True:
            try:
                value = float(input(prompt))
                return value
            except ValueError:
                print("Invalid input. Please enter a number.")
    
    number = get_valid_number("Enter a number: ")
    print("You entered:", number)

The user is continuously prompted for a number until they enter a valid numerical value.

This section demonstrates how to validate user input to ensure it is a number. The get_valid_number function repeatedly prompts the user for input until a valid number is entered, using a try-except block to catch any ValueError that occurs when converting the input to a float. This section provides a practical example of how to handle and validate user input in Python, ensuring that the program behaves as expected even when faced with incorrect or unexpected input. Function for Validation: The get_valid_number function is defined to encapsulate the validation logic. It uses a while loop to continuously prompt the user for input. Error Handling: The try-except block within the function is used to catch any ValueError that occurs if the input cannot be converted to a float. If an error is caught, the user is informed that their input was invalid, and they are prompted to try again. Validating User Input: The function ensures that the user's input is a valid number. It only breaks out of the loop and returns the value when a valid numerical input is given.



Decision Structures and Boolean Logic


    age = int(input("Enter your age: "))
    if age >= 18:
        print("You are an adult.")
    else:
        print("You are a minor.")
                        

Depending on the input age, it will print either "You are an adult." or "You are a minor."

Decision structures allow for different actions based on conditions. Boolean logic is used to evaluate these conditions. Decision Structures: The if-elif-else statement is used to demonstrate how Python decides between different options. The example takes the user's age as input and categorizes them as an adult or a minor.


    is_sunny = input("Is it sunny outside? (yes/no): ") == "yes"
    if is_sunny:
        print("It's a sunny day!")
    else:
        print("It's not sunny today.")

Depending on the entered age, the program will categorize the user as an adult or a minor. It will also respond to the user's input about the weather condition.

The first part uses an if-elif-else structure to decide and print whether the user is an adult or a minor based on their age. The second part uses Boolean logic to determine and display whether it's a sunny day based on user input. Boolean Logic: The second part of the code introduces basic Boolean logic. It takes a simple yes/no input to decide whether it's a sunny day. This example uses a comparison operation (==) to produce a Boolean value (True or False), which is then used in an if-else statement.



Repetition Structures


            for i in range(5):
                print(f"Number {i}")
                        

This will print numbers 0 through 4, each on a new line.

Repetition structures, or loops, allow for executing a block of code multiple times.



Functions


            def greet(name):
                return f"Hello, {name}!"
        
            print(greet("Alice"))
                        

Calling the function with "Alice" will output "Hello, Alice!"

Functions are reusable blocks of code that perform a specific task.



Files and Exceptions


            try:
                with open('file.txt', 'r') as file:
                    print(file.read())
            except FileNotFoundError:
                print("The file was not found.")
                        

If 'file.txt' exists, its contents will be printed; otherwise, "The file was not found."

Handling files for input and output, and managing exceptions that may occur during file operations. Writing to a file: This section shows how to write text to a file. If the file doesn't exist, it will be created. Appending to a file: This section shows how to add text to the end of an existing file or create a new one if it doesn't exist. Reading a file line by line: This demonstrates how to read each line from a file and print it, handling the case where the file might not exist.


            try:
                with open('output.txt', 'w') as file:
                    file.write('Hello, world!')
            except IOError:
                print("File cannot be accessed for writing.")
                        

If the operation is successful, 'Hello, world!' will be written to 'output.txt'.

Writing text to a file. This will create a new file or overwrite an existing file.


            try:
                with open('file.txt', 'a') as file:
                    file.write('Adding more text.')
            except IOError:
                print("File cannot be accessed for appending.")
                        

This will add 'Adding more text.' to 'file.txt' without overwriting its existing content.

Appending text to an existing file. If the file doesn't exist, it will be created.


            try:
                with open('file.txt', 'r') as file:
                    for line in file:
                        print(line.strip())
            except FileNotFoundError:
                print("The file was not found.")
                        

This will print each line of 'file.txt' if the file exists.

Reading a file line by line and printing each line.



Lists and Tuples


            # List example
            fruits = ['apple', 'banana', 'cherry']
            print(fruits[1])
            
            # Tuple example
            coordinates = (10.0, 20.0)
            print(coordinates)
                        

This will print "banana" and the tuple coordinates.

Lists are mutable sequences, while tuples are immutable. Both can contain multiple items.



More About Strings


            message = "Hello, World!"
            print(message.lower())
                        

This will output "hello, world!" in lowercase.

Exploring string methods for manipulation and inquiry.



Dictionaries and Sets


            # Dictionary example
            person = {'name': 'Alice', 'age': 30}
            print(person['name'])
            
            # Set example
            colors = {'red', 'green', 'blue'}
            print('green' in colors)
                        

This will print "Alice" and "True" as 'green' is in the colors set.

Dictionaries store key-value pairs, while sets store unordered unique elements.



Classes and Object-Oriented Programming


            class Dog:
                def __init__(self, name):
                    self.name = name
                
                def bark(self):
                    return f"{self.name} barks!"
        
            my_dog = Dog("Rex")
            print(my_dog.bark())
                        

This will output "Rex barks!"

Classes are blueprints for objects. Object-oriented programming is a paradigm based on the concept of "objects".