Fundamentals of Programming Concepts

Aug 3, 2024

Lecture Notes

Introduction

  • Overview of programming concepts and syntax.
  • Importance of code organization and logic flow.

Data Types

Variables

  • Integer, String, Float, Boolean.
  • Example assignments:
    • a = 10
    • b = 20

Operations

  • Basic arithmetic operators: + (addition), - (subtraction), * (multiplication), / (division).
  • Integer division and remainder (modulus) examples:
    • x % y returns remainder of x divided by y.

Input and Output

Getting User Input

  • Use input() function to receive user input and assign to variables:
    • name = input("Enter your name:")
    • age = int(input("Enter your age:"))

Printing Output

  • Use print() function to display output:
    • print(f"My name is {name}, my age is {age}.")

Control Structures

Conditional Statements

  • If-Else statements to control logic flow based on conditions:
    • Example:
      if age > 18:
          print("Eligible to vote")
      else:
          print("Not eligible to vote")
      

Loops

  • For Loop example to iterate through a list:
    • for i in range(1, 11):
      • print(i)
  • While Loop example for repeating code until a condition is met:
    • while count < 5:
      • count += 1

Functions

  • Define functions using the def keyword:
    • Example Function:
      def add(a, b):
          return a + b
      
  • Call functions with arguments:
    • result = add(3, 5)

Classes and Objects

Object-Oriented Programming

  • Creation of classes and instantiation of objects.
  • Example class:
    class Dog:
        def bark(self):
            print("Woof!")
    
  • Instantiating an object:
    • my_dog = Dog()
    • my_dog.bark()

Exception Handling

  • Use try-except blocks to handle exceptions:
    try:
        # Code that may cause an exception
    except ValueError:
        print("Invalid input")
    

File Operations

  • Reading and writing files:
    • Opening a file:
      with open('file.txt', 'r') as file:
          content = file.read()
      
  • Writing to a file:
    with open('output.txt', 'w') as file:
        file.write("Hello, World!")
    

Conclusion

  • Importance of practicing coding.
  • Encouragement to explore further topics in programming.