COS 102

lecture 4

Learn about lecture 4 in COS 102. Comprehensive study materials and practice questions.

Study notes included Document available CBT practice ready

Study Document

Open full

Study Notes

COS 102

CSC120: Computer as a Problem-Solving Tool

Topic 4: Fundamentals of Programming (1)

Lecture 4 Week5: Variables and Data Types in Python

Lecturer: Dr. Ufuoma C. Ogude

Department: Computer Sciences, University of Lagos

Outlines of the Course Wk2-7

  • Concept of Problem solving
  • Introduction to programming
  • Concept & properties of Algorithm
  • Fundamentals of programming (1): variable/variable naming convention/data types in Python
  • Fundamentals of programming (2): operators and expressions
  • Fundamentals of programming (3): control structures

Fundamentals of Programming (1): Variables and Data Types in Python

Python Overview

  • Python is a Scripting programming language known for its simplicity and wide breadth of applications, making it ideal for beginners.
  • It is a powerful and flexible programming language with concise, easy-to-learn syntax, enabling faster development of complex programs.
  • Used for everything from Web Development to Scientific Computing.
  • Referred to as a "general purpose" language.
  • It is an object-oriented programming language created by Guido Rossum in 1989.
  • Designed for rapid prototyping of complex applications.
  • Has interfaces to many OS system calls and libraries, and is extensible to C or C++.
  • Many large companies use Python, including NASA, Google, YouTube, and BitTorrent.

What Python Can Do (Applications)

Python's versatility allows it to be used in:

  • Web Application Development
  • Software Development
  • Data Analysis
  • Automation
  • Data Visualization
  • AI (Artificial Intelligence)
  • Prototyping
  • Machine Learning
  • System Scripting
  • Workflows
  • Mathematics

Top Python Projects Examples

Projects that can be built using Python include:

  • Email Sender, SMS Sender
  • School Management, Online Quiz System
  • Video Editor, Ticket Reservation, Tic-tac-toe, Security Software
  • Automatic Driver, Playing with cards, Professional Calculator, Email Client
  • Data Visualization, Hospital Management, Education System, Face Recognition

Python Libraries & Frameworks (Categorized Examples)

  • Machine Learning: Numpy, TensorFlow, Keras, Scikit-Learn, Theano, Matplotlib, Pandas, Scipy, PyTorch, Seaborn
  • Web Development: Django, Flask, Bottle, CherryPy, Pyramid, Web2Py, TurboGears, CubicWeb, Dash, Falcon
  • Automation Testing: Splinter, Robot, Behave, PyUnit, PyTest
  • Image Processing: OpenCV, Mahotas, SimpleITK, Pillow, Scikit-image
  • Game Development: Panda3D, PyGame, PyGlet, PyOpenGL, Arcade
  • Web Scrapping: Requests, Beautiful Soup, Selenium, Lxml, Scrapy

Why Python

  • Robust Language: Capable of sophisticated scientific and mathematical tasks despite its simplicity.
  • Highly Portable: Supported by various operating systems (Windows, Mac, Linux).
  • Structured Language: Supports structured programming, object-oriented programming, and aspects of functional programming.
  • Rich System Library: Comes with a robust standard library of modules, functions, and tools.
  • Middle-Level Language: Preferred for Machine Learning and Artificial Intelligence models.
  • Efficient and Fast: One of the fastest-growing and most in-demand programming skills.

How to Write a Python Program (Initial Steps)

  • Write your first Python program.
  • Understand what happens when running a program with an error.
  • Learn to declare a variable and inspect its value.
  • Learn to write comments.
  • Use the interactive window to display text using print().
  • Use the interactive window to assign a string literal to a variable and print its contents.
  • Repeat the above exercises using an editor window.

Fundamentals of Python Programming (Broader Topics)

  • The Context of Software Development
  • Values and Variables
  • Expressions and Arithmetic
  • Conditional Execution
  • Iteration, Using Functions
  • Writing Functions, More on Functions
  • Objects, lists
  • Tuples, Dictionaries, and Sets
  • Handling Exceptions, Custom Types
  • Class Design: Composition and Inheritance

Python Syntax

  • Refers to the set of rules defining how human users and the system should write and interpret a Python program.
  • Familiarity with syntax is crucial for writing and running Python programs.

Keywords

  • Python keywords are reserved words that cannot be used as variable, constant, function name, or identifier in your code.
  • Examples include: and, assert, break, class, continue, def, del, elif, else, except, exec, finally, for, from, global, if, import, in, is, lambda, not, or, pass, print, raise, return, try, while, with, yield.

Python Identifiers

  • A Python Identifier is a name given to a function, class, variable, module, or other objects used in a Python program.
  • All entities must be appropriately named as they form part of the program.

Naming Conventions

  • An identifier can be a combination of uppercase letters, lowercase letters, underscores, and digits (0-9).
  • Special characters such as %, @, and $ are not allowed.
  • An identifier should not begin with a number (e.g., 2variable is invalid, but variable2 is valid).
  • Python is a case-sensitive language (e.g., Labor and labor are distinct).
  • You cannot use Python keywords as identifiers.
  • Class identifiers begin with an uppercase letter; other identifiers typically begin in lowercase.
  • Underscores can be used to separate multiple words (e.g., my_variable).
  • Always choose descriptive identifiers for better readability and future reference (e.g., count = 2 instead of c = 2).

Using Quotations

  • Python allows the use of quotation marks to indicate string literals.
  • You can use single (' '), double (" "), or triple quotes (''' ''' or """ """), but the string must start and end with the same type.
  • Triple quotes are used when a string spans across several lines.

Python Statements

  • Statements are instructions that a Python interpreter can execute.
  • An assignment statement assigns a value to a variable (e.g., my_variable = "dog", c = 3).
  • Other types of statements include if statements, while statements, and for statements.

Multi-line Statements

  • A statement can span over several lines.
  • To break a long statement, you can wrap the expression inside parentheses (), braces {}, or brackets [] (preferred style).
  • Another way is to use a backslash \ at the end of each line to indicate line continuation.

Variables

  • Variables are containers for storing data values that can be accessed or changed.
  • They point to a memory location used by a program.
  • Variables instruct the computer to save or retrieve data to and from memory locations.

Variable Names

  • Rules:
    • Can contain letters, numbers, and underscores.
    • Cannot contain spaces.
    • Cannot start with a number.
    • Case matters (e.g., temp and Temp are different).
  • It's helpful to choose descriptive names (e.g., age, carname, total_volume).
  • Examples of Legal Variable names: myvar, my_var, _my_var, myVar, MYVAR, myVar2.
  • Examples of Illegal Variable names: 2myvar (starts with number), my - var (contains special character -), my var (contains space).

Creating Variables (Python Specifics)

  • Python has no explicit command for declaring a variable.
  • A variable is created the moment you first assign a value to it.
  • Variables do not need to be declared with a particular type and can even change type after being set.

Assignment Operator

  • An operator is a symbol (like +) that performs an operation on one or more values.
  • The assignment operator = takes the value to its right and assigns it to the name on its left.
  • Example:
    x = 5
    y = "John"
    print(x) # Output: 5
    print(y) # Output: John
    
    x = 4 # x is of type int
    x = "Sally" # x is now of type str
    print(x) # Output: Sally
    
    print(type(x)) # Output: <class 'str'>
            
  • Python variables are flexible; their type can change based on the assigned value.

Output Variables

  • The print() statement is used to output variables.
  • To combine text and a variable, use the + character:
    x = "awesome"
    print("Python is " + x) # Output: Python is awesome
            
  • The + character can also add variables together:
    x = "Python is "
    y = "awesome"
    z = x + y
    print(z) # Output: Python is awesome
            
  • Important Note: The + character works as a mathematical operator for numbers (e.g., print(x + y) where x=5, y=10 outputs 15). However, you cannot combine a string and a number using +; it will result in an error.

Data Types

  • Data stored in memory can be of many types, influencing operations and storage methods.
  • Examples: a person's age is a numeric value, an address is alphanumeric characters.
  • Python handles various standard data types including: strings, numbers, Booleans, lists, date, and time.

Standard Data Types (Built-in)

  • Text Type: str
  • Numeric Types: int, float, complex
  • Sequence Types: list, tuple, range
  • Mapping Types: dictionary
  • Set Types: set, frozenset
  • Boolean Type: bool
  • Binary Types: bytes, bytearray, memoryview

Python Numbers

Python supports four different numerical types:

  • int (signed integers)
  • long (long integers, can be represented in octal and hexadecimal)
  • float (floating-point real values)
  • complex (complex numbers)
  • Python handles various representations for these types, including standard decimal, octal (prefix 0o), hexadecimal (prefix 0x), scientific notation (e.g., 3.2e+18), and complex number notation (e.g., 3.14j).

Summary of Initial Learning

  • Executed a first Python program that displays "Hello, World" using print().
  • Learned about syntax errors (occur before execution due to invalid code) and runtime errors (occur during execution).
  • Understood how to assign values to variables using the assignment operator = and inspect them.
  • Learned to write helpful comments in code for future reference.

Review Exercises

  • Write a program that IDLE won't run because it has a syntax error.
  • Write a program that crashes only while it's running because it has a runtime error.
  • Using the interactive window, display some text using print().
  • Using the interactive window, assign a string literal to a variable.
  • Then print the contents of the variable using the print() function.
  • Repeat the first two exercises using the editor window.

Arithmetic Operators

  • + Addition: Adds the value of the left and right operands.
  • - Subtraction: Subtracts the value of the right operand from the value of the left operand.
  • * Multiplication: Multiplies the value of the left and right operands.
  • / Division: Divides the value of the left operand by the right operand (result is always a float).
  • ** Exponent: Performs exponential calculation (raises left operand to the power of the right operand).
  • % Modulus: Returns the remainder after dividing the left operand by the right operand.
  • // Floor Division: Division of operands where the solution is the quotient left after removing decimal numbers (truncates the result).

Numeric Operations (Summary)

  • Addition (x + y): `x` and `y` can be floats or ints.
  • Subtraction (x - y): `x` and `y` can be floats or ints.
  • Multiplication (x * y): `x` and `y` can be floats or ints.
  • Division (x / y): `x` and `y` can be floats or ints; result is always a float.
  • Floor Division (x // y): `x` and `y` can be floats or ints; result is the first integer less than or equal to the quotient.
  • Remainder or Modulo (x % y): `x` and `y` must be ints; this is the remainder of dividing `x` by `y`.
  • Exponentiation (x ** y): `x` and `y` can be floats or ints; results in `x` raised to the `y`-th power.
  • Float Conversion (float(x)): Converts the numeric value of `x` to a float.
  • Integer Conversion (int(x)): Converts the numeric value of `x` to an int; decimal portion is truncated, not rounded.
  • Absolute Value (abs(x)): Gives the absolute value of `x`.
  • Round (round(x)): Rounds the float `x` to the nearest whole number; the result type is always an int.

Test Your Knowledge

Challenge yourself with targeted practice questions and accelerate your mastery of lecture 4.

Practice CBT Study Flashcards