{ "nbformat": 4, "nbformat_minor": 0, "metadata": { "colab": { "provenance": [], "authorship_tag": "ABX9TyMRAVQV27b66RPG6t6JobJm", "include_colab_link": true }, "kernelspec": { "name": "python3", "display_name": "Python 3" }, "language_info": { "name": "python" } }, "cells": [ { "cell_type": "markdown", "metadata": { "id": "view-in-github", "colab_type": "text" }, "source": [ "\"Open" ] }, { "cell_type": "markdown", "source": [ "# **Variables and Types**\n", "Python is completely object oriented, and not \"statically typed\". You do not need to declare variables before using them, or declare their type. Every variable in Python is an object.\n", "\n", "This tutorial will go over a few basic types of variables.\n", "\n", "Numbers\n", "Python supports two types of numbers - integers(whole numbers) and floating point numbers(decimals). (It also supports complex numbers, which will not be explained in this tutorial)." ], "metadata": { "id": "g-A-neL2m19b" } }, { "cell_type": "code", "execution_count": 3, "metadata": { "colab": { "base_uri": "https://localhost:8080/" }, "id": "Eq7gJavKmwrE", "outputId": "08d832fe-d085-41b3-cef8-377bfd3efaeb" }, "outputs": [ { "output_type": "stream", "name": "stdout", "text": [ "7\n", "7.0\n", "7.0\n", "hello\n", "hello\n", "Don't worry about apostrophes\n", "3\n", "hello world\n", "3 4\n", "9\n", "String: hello\n", "Float: 10.000000\n", "Integer: 20\n" ] } ], "source": [ "myint = 7\n", "print(myint)\n", "myfloat = 7.0\n", "print(myfloat)\n", "myfloat = float(7)\n", "print(myfloat)\n", "mystring = 'hello'\n", "print(mystring)\n", "mystring = \"hello\"\n", "print(mystring)\n", "mystring = \"Don't worry about apostrophes\"\n", "print(mystring)\n", "one = 1\n", "two = 2\n", "three = one + two\n", "print(three)\n", "\n", "hello = \"hello\"\n", "world = \"world\"\n", "helloworld = hello + \" \" + world\n", "print(helloworld)\n", "a, b = 3, 4\n", "print(a, b)\n", "# This will not work!\n", "one = 1\n", "two = 2\n", "hello = 6\n", "\n", "print(one + two + hello)\n", "# change this code\n", "mystring = \"hello\"\n", "myfloat = 10.0\n", "myint = 20\n", "\n", "# testing code\n", "if mystring == \"hello\":\n", " print(\"String: %s\" % mystring)\n", "if isinstance(myfloat, float) and myfloat == 10.0:\n", " print(\"Float: %f\" % myfloat)\n", "if isinstance(myint, int) and myint == 20:\n", " print(\"Integer: %d\" % myint)" ] }, { "cell_type": "markdown", "source": [ "# **Getting to Know Variables in Python**\n", "Creating Variables With Assignments\n", "\n", "Setting and Changing a Variable’s Data Type\n", "\n", "Working With Variables in Python\n", "\n", "Expressions\n", "\n", "Object Counters\n", "\n", "Accumulators\n", "\n", "Temporary Variables\n", "\n", "Boolean Flags\n", "\n", "Loop Variables\n", "\n", "Data Storage Variables\n", "\n", "Naming Variables in Python\n", "\n", "Rules for Naming Variables\n", "\n", "Best Practices for Naming Variables\n", "\n", "Public and Non-Public Variable Names\n", "\n", "Restricted and Discouraged Names\n", "\n", "Exploring Core Features of Variables\n", "\n", "Variables Hold References to Objects\n", "\n", "Variables Have Dynamic Types\n", "\n", "Variables Can Use Type Hints\n", "\n", "Using Complementary Ways to Create Variables\n", "\n", "Parallel Assignment\n", "\n", "Iterable Unpacking\n", "\n", "Assignment Expressions\n", "\n", "Understanding Variable Scopes\n", "\n", "Global, Local, and Non-Local Variables\n", "\n", "Class and Instance Variables (Attributes)\n", "\n", "Deleting Variables From Their Scope" ], "metadata": { "id": "wsaGp_PQole8" } }, { "cell_type": "code", "source": [ "word = \"Python\"" ], "metadata": { "id": "MKDme9hgoloD" }, "execution_count": null, "outputs": [] }, { "cell_type": "markdown", "source": [ "In Python, variables are symbolic names that refer to objects or values stored in your computer’s memory. They allow you to assign descriptive names to data, making it easier to manipulate and reuse values throughout your code. You create a Python variable by assigning a value using the syntax variable_name = value.\n", "\n", "You’ll understand that:\n", "\n", "Variables in Python are symbolic names pointing to objects or values in memory.\n", "\n", "You define variables by assigning them a value using the assignment operator.\n", "\n", "Python variables are dynamically typed, allowing type changes through reassignment.\n", "\n", "Python variable names can include letters, digits, and underscores but can’t start with a digit. You should use snake case for multi-word names to improve readability.\n", "\n", "Variables exist in different scopes (global, local, non-local, or built-in), which affects how you can access them.\n", "You can have an unlimited number of variables in Python, limited only by computer memory." ], "metadata": { "id": "2W1KMkh5olyL" } }, { "cell_type": "code", "source": [ "fruits = [\"apple\", \"mango\", \"grape\"]" ], "metadata": { "id": "uAfHaRPjol9L" }, "execution_count": null, "outputs": [] }, { "cell_type": "markdown", "source": [ "# **Setting and Changing a Variable’s Data Type**\n", "Apart from a variable’s value, it’s also important to consider the data type of the value. When you think about a variable’s type, you’re considering whether the variable refers to a string, integer, floating-point number, list, tuple, dictionary, custom object, or another data type.\n", "\n", "Python is a dynamically typed language, which means that variable types are determined and checked at runtime rather than during compilation. Because of this, you don’t need to specify a variable’s type when you’re creating the variable. Python will infer a variable’s type from the assigned object." ], "metadata": { "id": "GJdElHlromIz" } }, { "cell_type": "code", "source": [ "name = \"Jane Doe\"\n", "age = 19\n", "subjects = [\"Math\", \"English\", \"Physics\", \"Chemistry\"]\n", "\n", "type(name)\n", "type(age)\n", "type(subjects)\n" ], "metadata": { "id": "cUU-TF2FomQL" }, "execution_count": null, "outputs": [] }, { "cell_type": "markdown", "source": [ "# ***Working With Variables in Python***\n", "Variables are an essential concept in Python programming. They work as the building blocks for your programs. So far, you’ve learned the basics of creating variables. In this section, you’ll explore different ways to use variables in Python.\n", "\n", "You’ll start by using variables in expressions. Then, you’ll dive into counters and accumulators, which are essential for keeping track of values during iteration. You’ll also learn about other common use cases for variables, such as temporary variables, Boolean flags, loop variables, and data storage variables." ], "metadata": { "id": "NEIYjQSVomWy" } }, { "cell_type": "code", "source": [ "2 * 3.1416 * 10" ], "metadata": { "id": "kyrTQ4CMomdb" }, "execution_count": null, "outputs": [] }, { "cell_type": "markdown", "source": [ "# **Object Counters**\n", "A counter is an integer variable that allows you to count objects. Counters typically have an initial value of zero, which increments to reflect the number of times a given object appears. To illustrate, say that you need to count the objects that are strings in a given list of objects. In this situation, you can do something like the following:" ], "metadata": { "id": "RZU47w9KpbIF" } }, { "cell_type": "code", "source": [ "str_counter = 0\n", "\n", "for item in (\"Alice\", 30, \"Programmer\", None, True, \"Department C\"):\n", " if isinstance(item, str):\n", " str_counter += 1\n", "\n", "str_counter" ], "metadata": { "id": "DpZOtlbYpbRN" }, "execution_count": null, "outputs": [] }, { "cell_type": "markdown", "source": [ "# **Accumulators**\n", "Accumulators are another common type of variable used in programming. An accumulator is a variable that you use to add consecutive values to form a total that you can use as an intermediate step in different calculations." ], "metadata": { "id": "c4lit_24pbXn" } }, { "cell_type": "code", "source": [ "numbers = [1, 2, 3, 4]\n", "total = 0\n", "\n", "for number in numbers:\n", " total += number\n", "\n", "\n", "total" ], "metadata": { "id": "fCOmHYPWpbfV" }, "execution_count": null, "outputs": [] }, { "cell_type": "markdown", "source": [ "# **Temporary Variables**\n", "Temporary variables hold intermediate results that you need for a more elaborate computation. A classic use case for a temporary variable is when you need to swap values between variables:" ], "metadata": { "id": "j0kB_Nc2pbmV" } }, { "cell_type": "code", "source": [ "a = 5\n", "b = 10\n", "\n", "temp = a\n", "a = b\n", "b = temp\n", "\n", "a\n", "\n", "b" ], "metadata": { "colab": { "base_uri": "https://localhost:8080/" }, "id": "Q_JhGU_1pbse", "outputId": "4110a3c2-1024-4ee2-dce9-c56681f8bfa2" }, "execution_count": 4, "outputs": [ { "output_type": "execute_result", "data": { "text/plain": [ "5" ] }, "metadata": {}, "execution_count": 4 } ] }, { "cell_type": "markdown", "source": [ "# **Boolean Flags**\n", "Boolean flags help you manage control flow and decision-making in your programs. As their name suggests, these variables can be either True or False. You can use them in conditionals, while loops, and Boolean expressions." ], "metadata": { "id": "3vlrxyH2pbzO" } }, { "cell_type": "code", "source": [ "toggle = True\n", "\n", "for _ in range(4):\n", " if toggle:\n", " print(f\"✅ toggle is {toggle}\")\n", " print(\"Do something...\")\n", " else:\n", " print(f\"❌ toggle is {toggle}\")\n", " print(\"Do something else...\")\n", " toggle = not toggle\n" ], "metadata": { "id": "UOQzgHa3pb5u" }, "execution_count": null, "outputs": [] }, { "cell_type": "markdown", "source": [ "# **Loop Variables**\n", "Loop variables help you process data during iteration in for loops and sometimes in while loops. In a for loop, the variable takes the value of the current element in the input iterable each time you go through the loop:" ], "metadata": { "id": "354uEu0spcAO" } }, { "cell_type": "code", "source": [ "colors = [\n", " \"red\",\n", " \"orange\",\n", " \"yellow\",\n", " \"green\",\n", " \"blue\",\n", " \"indigo\",\n", " \"violet\"\n", "]\n", "\n", "for color in colors:\n", " print(color)" ], "metadata": { "id": "pZhQJmEipcGl" }, "execution_count": null, "outputs": [] }, { "cell_type": "markdown", "source": [ "# **Data Storage Variables**\n", "Data storage variables allow you to work with containers of values, such as lists, tuples, dictionaries, or sets. For example, say that you’re writing a contact book application that uses a list of tuples to store the information of your contacts:" ], "metadata": { "id": "xEYpGzPCpcMP" } }, { "cell_type": "markdown", "source": [], "metadata": { "id": "AqGPvdztq5eh" } }, { "cell_type": "code", "source": [ "contacts = [\n", " (\"Linda\", \"111-2222-3333\", \"linda@example.com\"),\n", " (\"Joe\", \"111-2222-3333\", \"joe@example.com\"),\n", " (\"Lara\", \"111-2222-3333\", \"lara@example.com\"),\n", " (\"David\", \"111-2222-3333\", \"david@example.com\"),\n", " (\"Jane\", \"111-2222-3333\", \"jane@example.com\"),\n", " ]\n", "for contact in contacts:\n", " print(contact)\n", "\n", "\n", "for name, phone, email in contacts:\n", " print(phone, name)" ], "metadata": { "colab": { "base_uri": "https://localhost:8080/" }, "id": "-BtziPIfq5lQ", "outputId": "aedb1186-8a7a-4a8f-83eb-51b62a1c6433" }, "execution_count": 5, "outputs": [ { "output_type": "stream", "name": "stdout", "text": [ "('Linda', '111-2222-3333', 'linda@example.com')\n", "('Joe', '111-2222-3333', 'joe@example.com')\n", "('Lara', '111-2222-3333', 'lara@example.com')\n", "('David', '111-2222-3333', 'david@example.com')\n", "('Jane', '111-2222-3333', 'jane@example.com')\n", "111-2222-3333 Linda\n", "111-2222-3333 Joe\n", "111-2222-3333 Lara\n", "111-2222-3333 David\n", "111-2222-3333 Jane\n" ] } ] }, { "cell_type": "markdown", "source": [ "# **Naming Variables in Python**\n", "The examples you’ve seen so far use short variable names. In practice, variable names should be descriptive to improve the code’s readability, so they can also be longer and include multiple words.\n", "\n", "In the following sections, you’ll learn about the rules to follow when creating valid variable names in Python. You’ll also learn best practices for naming variables and other naming-related practices.\n", "\n", "# *Rules for Naming Variables*\n", "Variable names in Python can be any length and can consist of uppercase letters (A-Z) and lowercase letters (a-z), digits (0-9), and the underscore character (_). The only restriction is that even though a variable name can contain digits, the first character of a variable name can’t be a digit.\n", "\n" ], "metadata": { "id": "ZnRiFrw-q5r5" } }, { "cell_type": "code", "source": [ "name = \"Bob\"\n", "year_of_birth = 1970\n", "is_adult = True" ], "metadata": { "id": "b2-sI3_Xq5xx" }, "execution_count": null, "outputs": [] }, { "cell_type": "markdown", "source": [ "# **The most common practices for multi-word variable names are the following:**\n", "\n", "Snake case: Lowercase words are separated by underscores. For example: number_of_graduates.\n", "Camel case: The second and subsequent words are capitalized to make word boundaries easier to see. For example: numberOfGraduates.\n", "Pascal case: Similar to camel case, except the first word is also capitalized. For example: NumberOfGraduates." ], "metadata": { "id": "8CLmh82-q53w" } }, { "cell_type": "code", "source": [ "initial_temperature = 25\n", "current_file = \"marketing_personel.csv\"\n", "next_point = (2, 4)" ], "metadata": { "id": "0jmRJQNnq59i" }, "execution_count": null, "outputs": [] }, { "cell_type": "markdown", "source": [ "# **Public and Non-Public Variable Names**\n", "A widely used naming convention for variables in Python is to use a leading underscore when you need to communicate that a given variable is what Python defines as non-public. A non-public variable is a variable that shouldn’t be used outside its defining module. These variables are for internal use only:\n", "\n", "\n" ], "metadata": { "id": "qiw6VoelrxVj" } }, { "cell_type": "code", "source": [ "_timeout = 30\n", "\n", "def get_timeout():\n", " return _timeout\n", "\n", "def set_timeout(seconds):\n", " global _timeout\n", " _timeout = seconds" ], "metadata": { "id": "bk7X1y48rxhN" }, "execution_count": null, "outputs": [] }, { "cell_type": "markdown", "source": [ "# **Restricted and Discouraged Names**\n", "Python reserves a small set of words known as keywords that are part of the language’s syntax. To get the list of Python’s keywords, go ahead and run the following code:\n" ], "metadata": { "id": "qWUSZjwxr3nN" } }, { "cell_type": "code", "source": [ "import keyword\n", "keyword.kwlist\n", "[\n", " 'False',\n", " 'None',\n", " 'True',\n", " 'and',\n", " 'as',\n", " 'assert',\n", " 'async',\n", " ...,\n", " 'yield'\n", "]" ], "metadata": { "id": "qI8YzZwEr3uN" }, "execution_count": null, "outputs": [] }, { "cell_type": "markdown", "source": [ "# **Exploring Core Features of Variables**\n", "When you start digging deeper into how Python variables work internally, you discover several interesting features worth studying. In the following sections, you’ll explore some of the core features of variables so that you can better understand them.\n", "\n", "**Variables Hold References to Objects**\n", "What happens when you create a variable with an assignment? This is an important question in Python because the answer differs from what you’d find in many other programming languages.\n", "\n", "Python is an object-oriented programming language. Every piece of data in a Python program is an object of a specific type or class. Consider this code:" ], "metadata": { "id": "-rwPFvbIsFMe" } }, { "cell_type": "code", "source": [ "300" ], "metadata": { "id": "O-hDsxeWsFTm" }, "execution_count": null, "outputs": [] }, { "cell_type": "markdown", "source": [ "When presented with the statement 300, Python does the following operations:\n", "\n", "Creates an integer object\n", "Gives it a value of 300\n", "Displays it on the screen\n", "You can see that an integer object is created using the built-in type() function:" ], "metadata": { "id": "qpG1qLaJsKC2" } }, { "cell_type": "code", "source": [ "type(300)" ], "metadata": { "id": "jzwJWkJxsKJf" }, "execution_count": null, "outputs": [] }, { "cell_type": "markdown", "source": [ "# **Variables Have Dynamic Types**\n", "In many programming languages, variables are statically typed, which means they’re initially declared to have a specific data type during their lifetime. Any value assigned to that variable during its lifetime must be of the specified data type.\n", "\n", "Python variables aren’t typed this way. In Python, you can assign values of different data types to a variable at different moments:" ], "metadata": { "id": "p5Q8c1zLsR_-" } }, { "cell_type": "code", "source": [ "value = \"A string value\"\n", "value\n", "\n", "\n", "# Later\n", "value = 23.5\n", "value" ], "metadata": { "colab": { "base_uri": "https://localhost:8080/" }, "id": "bq6AEXUssSIu", "outputId": "fd4fa7f5-ef1f-4dd4-9b05-e0a5d427d30b" }, "execution_count": 6, "outputs": [ { "output_type": "execute_result", "data": { "text/plain": [ "23.5" ] }, "metadata": {}, "execution_count": 6 } ] }, { "cell_type": "markdown", "source": [ "# **Variables Can Use Type Hints**\n", "You can use type hints to add explicit type information to your variables. To do this, you can use the following Python syntax:\n", "\n", "variable: data_type [= value]" ], "metadata": { "id": "PEj7g9MssSSX" } }, { "cell_type": "code", "source": [ "number: int" ], "metadata": { "id": "T_4rAfJEsSZu" }, "execution_count": null, "outputs": [] }, { "cell_type": "markdown", "source": [ "# **Using Complementary Ways to Create Variables**\n", "In Python, you’ll find a few alternative ways to create new variables. Sometimes, defining several variables simultaneously with the same initial value is convenient or needed. To do this, you can use a parallel assignment.\n", "\n", "In other situations, you may need to initialize several variables with values from a sequence data type, like a list or tuple. In this case, you can use a technique called iterable unpacking.\n", "\n", "You’ll also find situations where you need to retain the value that results from a given expression. In this case, you can use an assignment expression.\n", "\n", "In the following sections, you’ll learn about all these alternative or complementary ways to create Python variables.\n", "\n", "**Parallel Assignment**\n", "Python also allows you to run multiple assignments in a single line of code. This feature makes it possible to assign the same value to several variables simultaneously:" ], "metadata": { "id": "DQ35F5rqsie-" } }, { "cell_type": "code", "source": [ "is_authenticated = is_active = is_admin = False" ], "metadata": { "id": "bVDYjs9xsilu" }, "execution_count": null, "outputs": [] }, { "cell_type": "markdown", "source": [ "# **Iterable Unpacking**\n", "Iterable unpacking is a cool Python feature also known as tuple unpacking. It consists of distributing the values in an iterable into a series of variables. In most cases, the number of variables will match the number of items in the iterable. However, you can also use the *variable syntax to grab several items in a list.\n", "\n", "You can use iterable unpacking to create multiple variables at a time using an iterable of values. For example, say that you have some data about a person and want to create dedicated variables for each piece of data:" ], "metadata": { "id": "D1zUo1GLsrCv" } }, { "cell_type": "code", "source": [ "person = (\"Jane\", 25, \"Python Dev\")" ], "metadata": { "id": "VjvHBogrsrI_" }, "execution_count": null, "outputs": [] }, { "cell_type": "markdown", "source": [ "# **Assignment Expressions**\n", "Assignment expressions allow you to assign the result of an expression used in a conditional or a while loop to a name in one step. For example, consider the following loop that takes input from the keyboard until you type the word \"stop\":" ], "metadata": { "id": "zQkI6mo9srP_" } }, { "cell_type": "code", "source": [ "line = input(\"Type some text: \")\n", "\n", "while line != \"stop\":\n", " print(line)\n", " line = input(\"Type some text: \")\n" ], "metadata": { "id": "cjb5SxcLsrYI" }, "execution_count": null, "outputs": [] }, { "cell_type": "markdown", "source": [ "# **Understanding Variable Scopes**\n", "The concept of scope defines how variables and names are looked up in your code. It determines the visibility of a variable within your code. The scope of a variable depends on the place in your code where you create the variable.\n", "\n", "In Python, you may find up to four different scopes, which can be presented using the LEGB acronym. The letters in this acronym stand for local, enclosing, global, and built-in scopes\n", "\n", "**Global, Local, and Non-Local Variables**\n", "\n", "Global variables are those that you create at the module level. These variables are visible within the containing module and in other modules that import them. So, for example, if you’re using the Python REPL, then the current global scope is defined in a module called __main__.\n", "\n", "This module defines your current global scope. All the variables defined in this module are global, so you can use them at anytime during an interactive session run:" ], "metadata": { "id": "C7jcL7WXs4sP" } }, { "cell_type": "code", "source": [ "value = 42\n", "dir()\n" ], "metadata": { "id": "Gj76_oeJs43v" }, "execution_count": null, "outputs": [] }, { "cell_type": "markdown", "source": [ "**Local variables** are those that you define inside a function. These variables can help you store the results of intermediate computations under a descriptive name. They can make your code more readable and explicit.\n", "\n", "**non-local variables** are those that you create in a function that define inner functions. The variables local to the outer function are non-local to the inner functions. Non-local variables are useful when you’re creating closure functions and decorators." ], "metadata": { "id": "buRrSTBgtMaB" } }, { "cell_type": "code", "source": [ "# Global scope\n", "global_variable = \"global\"\n", "\n", "def outer_func():\n", " # Nonlocal scope\n", " nonlocal_variable = \"nonlocal\"\n", " def inner_func():\n", " # Local scope\n", " local_variable = \"local\"\n", " print(f\"Hi from the '{local_variable}' scope!\")\n", " print(f\"Hi from the '{nonlocal_variable}' scope!\")\n", " print(f\"Hi from the '{global_variable}' scope!\")\n", " inner_func()" ], "metadata": { "id": "ijAJJa_1tMih" }, "execution_count": null, "outputs": [] }, { "cell_type": "markdown", "source": [ "# *Class and Instance Variables (Attributes)*\n", "You can create variables inside custom Python classes when using object-oriented programming tools. These variables are called attributes. In practice, you can have class and instance attributes.\n", "\n", "**Class attributes** are variables that you create at the class level, while instance attributes are variables that you attach to instances of a given class. These attributes are visible only from within the class or its instances. So, classes define a namespace, which is similar to the scope." ], "metadata": { "id": "ghRiNeAhtZW5" } }, { "cell_type": "code", "source": [ "class Employee:\n", " count = 0\n", "\n", " def __init__(self, name, position, salary):\n", " self.name = name\n", " self.position = position\n", " self.salary = salary\n", " Employee.count += 1\n", "\n", " def display_profile(self):\n", " print(f\"Name: {self.name}\")\n", " print(f\"Position: {self.position}\")\n", " print(f\"Salary: ${self.salary}\")" ], "metadata": { "id": "CCVhJmV2tZdx" }, "execution_count": null, "outputs": [] }, { "cell_type": "markdown", "source": [ "# **Deleting Variables From Their Scope**\n", "In Python, you can explicitly remove variables or, more generically, names from a given scope using the del statement:" ], "metadata": { "id": "xRWR1ECkti2a" } }, { "cell_type": "code", "source": [ "city = \"New York\"\n", "city\n", "\n", "\n", "del city\n", "city" ], "metadata": { "id": "GRKVmnT9ti_J" }, "execution_count": null, "outputs": [] }, { "cell_type": "markdown", "source": [ "Created variables and assigned values to them\n", "\n", "Changed a variable’s data type dynamically\n", "\n", "Used variables in expressions, counters, accumulators, and Boolean flags\n", "\n", "Followed best practices for naming variables\n", "\n", "Created, accessed, and used variables in their specific scopes" ], "metadata": { "id": "uURB71hMtyyZ" } } ] }