Sunday, December 22, 2024

Python Variables Definition Creation Casting Getting the Type of a Variable Case Sensitivity Output Local Global Variable Inside a Function Numbers

Definition of Variables

  1. Variables are Containers
    • Used for storing data values.

Creating Variables

  1. No Declaration Command

    • Python does not require a specific command to declare variables.
    • A variable is created when you assign a value to it.
  2. Examples:

    • x = 5
      y = "John"
      print(x)
      print(y)
      
  3. Dynamic Typing

    • Variables do not need to have a fixed type and can change types after being set.
    • Example:
      x = 4       # x is of type int
      x = "Sally" # x is now of type str
      print(x)
      

Casting Variables

  1. Specifying Data Type
    • Use casting to define a variable's data type explicitly.
    • Example:
      x = str(3)    # x will be '3'
      y = int(3)    # y will be 3
      z = float(3)  # z will be 3.0
      

Getting the Type of a Variable

  1. Using type() Function
    • Check the data type of a variable.
    • Example:
      x = 5
      y = "John"
      print(type(x))  # Output: <class 'int'>
      print(type(y))  # Output: <class 'str'>
      

Strings and Quotes

  1. Single or Double Quotes
    • String variables can use either single (') or double (") quotes interchangeably.
    • Example:
      x = "John"
      y = 'John'
      

Case Sensitivity

  1. Variable Names are Case-Sensitive
    • Variables with different cases are treated as distinct variables.
    • Example:
      a = 4
      A = "Sally"
      # A will not overwrite a
      

Exercise

  • Question: What is a correct way to declare a Python variable?
    • Correct Answer: x = 5

Definition of Variable Names

  1. Short or Descriptive
    • Variable names can be short (e.g., x, y) or descriptive (e.g., age, carname, total_volume).

Rules for Python Variable Names

  1. Starting Character

    • Must start with a letter or an underscore (_).
  2. Cannot Start with a Number

    • A variable name cannot begin with a digit.
  3. Allowed Characters

    • Can only contain alphanumeric characters (A-Z, a-z, 0-9) and underscores (_).
  4. Case Sensitivity

    • Variable names are case-sensitive. Examples:
      • age, Age, and AGE are treated as different variables.
  5. Python Keywords

    • Variable names cannot be any of Python's reserved keywords.

Examples of Legal and Illegal Variable Names

Legal Variable Names:

myvar = "John"
my_var = "John"
_my_var = "John"
myVar = "John"
MYVAR = "John"
myvar2 = "John"

Illegal Variable Names:

2myvar = "John"  # Cannot start with a number
my-var = "John"  # Cannot contain special characters like "-"
my var = "John"  # Cannot contain spaces

Reminder

  • Case Sensitivity:
    • Variable names like myvar, MyVar, and MYVAR are distinct due to Python's case sensitivity.


Many Values to Multiple Variables

  1. Assigning Multiple Values in One Line

    • Python allows assigning multiple values to multiple variables in one line.
    • Example:
      x, y, z = "Orange", "Banana", "Cherry"
      print(x)  # Orange
      print(y)  # Banana
      print(z)  # Cherry
      
  2. Matching Variables and Values

    • The number of variables must match the number of values; otherwise, an error will occur.

One Value to Multiple Variables

  1. Assigning the Same Value to Multiple Variables
    • A single value can be assigned to multiple variables in one line.
    • Example:
      x = y = z = "Orange"
      print(x)  # Orange
      print(y)  # Orange
      print(z)  # Orange
      

Unpack a Collection

  1. Extracting Values from Collections

    • Python allows extracting values from a collection (like a list or tuple) into variables, called unpacking.
    • Example:
      fruits = ["apple", "banana", "cherry"]
      x, y, z = fruits
      print(x)  # apple
      print(y)  # banana
      print(z)  # cherry
      
  2. Learn More About Unpacking

    • You can learn more about unpacking in the Unpack Tuples Chapter.

Exercise

Question:
What is the correct syntax to assign the value 'Hello World' to 3 variables in one statement?

Options:

  1. x, y, z = 'Hello World'
  2. x = y = z = 'Hello World'
  3. x|y|z = 'Hello World'


Output Variables

  1. Using print() to Output Variables

    • The print() function can be used to display the value of a variable.
    • Example:
      x = "Python is awesome"
      print(x)
      
  2. Outputting Multiple Variables

    • Multiple variables can be output using commas within the print() function.
    • Example:
      x = "Python"
      y = "is"
      z = "awesome"
      print(x, y, z)  # Python is awesome
      
  3. Using the + Operator to Output Variables

    • The + operator can be used to concatenate strings.
    • Example:
      x = "Python "
      y = "is "
      z = "awesome"
      print(x + y + z)  # Python is awesome
      
    • Note: If there are no spaces within the string variables, the result will appear as a single concatenated string (e.g., "Pythonisawesome").

Working with Numbers

  1. Mathematical Operation with +

    • The + operator adds numbers when used with numeric variables.
    • Example:
      x = 5
      y = 10
      print(x + y)  # 15
      
  2. Error When Combining Strings and Numbers

    • Combining a string and a number with the + operator will result in a TypeError.
    • Example:
      x = 5
      y = "John"
      print(x + y)  # Error
      
  3. Using Commas for Different Data Types

    • Using commas in the print() function allows you to combine different data types.
    • Example:
      x = 5
      y = "John"
      print(x, y)  # 5 John
      

Exercise

Question:
Consider the following code:

print('Hello', 'World')

What will be the printed result?

Options:

  1. Hello, World
  2. Hello World
  3. HelloWorld

Global Variables


Definition of Global Variables

  1. Global Variables are created outside of a function and can be used both inside and outside of functions.

Using Global Variables Inside Functions

  1. A global variable can be accessed directly within a function.
    • Example:
      x = "awesome"
      
      def myfunc():
          print("Python is " + x)
      
      myfunc()  # Output: Python is awesome
      

Local Variables with the Same Name as Global Variables

  1. If a variable with the same name as a global variable is defined inside a function, it becomes a local variable and does not affect the global variable.
    • Example:
      x = "awesome"
      
      def myfunc():
          x = "fantastic"  # Local variable
          print("Python is " + x)
      
      myfunc()              # Output: Python is fantastic
      print("Python is " + x)  # Output: Python is awesome
      

The global Keyword

  1. Definition: The global keyword is used to define or modify a global variable inside a function.

Creating a Global Variable Inside a Function

  1. Using global within a function creates a global variable that can be accessed outside of the function.
    • Example:
      def myfunc():
          global x
          x = "fantastic"
      
      myfunc()
      print("Python is " + x)  # Output: Python is fantastic
      

Modifying a Global Variable Inside a Function

  1. To change the value of an existing global variable inside a function, use the global keyword.
    • Example:
      x = "awesome"
      
      def myfunc():
          global x
          x = "fantastic"
      
      myfunc()
      print("Python is " + x)  # Output: Python is fantastic
      

💥 YouTube https://www.youtube.com/channel/UCJojbxGV0sfU1QPWhRxx4-A
💥 Blog https://localedxcelcambridgeictcomputerclass.blogspot.com/
💥 WordPress https://computerclassinsrilanka.wordpress.com
💥 Facebook https://web.facebook.com/itclasssrilanka
💥 Wix https://itclasssl.wixsite.com/icttraining
💥 Web https://itclasssl.github.io/eTeacher/
💥 Medium https://medium.com/@itclasssl
💥 Quora https://www.quora.com/profile/BIT-UCSC-UoM-Final-Year-Student-Project-Guide
💥 mystrikingly https://bit-ucsc-uom-final-year-project-ideas-help-guide-php-class.mystrikingly.com/
💥 https://elakiri.com/threads/bit-ucsc-uom-php-mysql-project-guidance-and-individual-classes-in-colombo.1627048/
💥 https://bitbscucscuomfinalprojectclasslk.weebly.com/
💥 https://www.tiktok.com/@onlinelearningitclassso1

No comments:

Post a Comment