Variables, Data Types, Operators and Functions
Objective : What I want you to learn?
Working with variables in Python, Rules for variable names, Local and Global variables, Data Types in Python, Operators and Functions in Python
Rationale : Why this is useful to you?
Working with variables, data types, operations and functions is a building block for programming, you will be using them to write programs for solving complex engineering problems
Learning Outcomes : What I want you to do after completing this topic?
Define Local and Global variables in Functions
Work with Operators and Data Types in Python
Define and Call Functions to do specific tasks
Contents
Basic Syntax and Fundamentals
Variables: Creating, printing and deleting variables, Multiple Assignment
Rules for variable names, Local and global variables
Operators in Python
Data Types in Python
Functions in Python
Basic Syntax and Fundamentals
Python Identifiers
Python identifiers are names that are given to variables, functions, classes, modules, and other objects in Python. They are used to refer to these objects in Python code.
Here are the rules for writing Python identifiers:
Identifiers can be a combination of letters, digits, and underscores (_).
Identifiers must start with a letter or an underscore.
Identifiers cannot be Python keywords.
Identifiers are case-sensitive.
Python is a case-sensitive programming language.
Python Keywords
Python keywords are reserved words that have special meaning to the Python interpreter. They cannot be used as variable names, function names, or any other identifiers in your code.
and, as, assert, async, await, break, 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
Lines and Indentation
Lines and indentation are important concepts in Python. Python uses indentation to define blocks of code. A block of code is a group of statements that are executed together.
Lines in Python are simply the lines of text that make up your code.
Indentation in Python is the amount of whitespace at the beginning of a line of code. Python uses indentation to determine which statements belong to which blocks of code.
Multiline Statements
Statements in Python typically end with a new line. Python does, however, allow the use of the line continuation character (\) to denote that the line should continue
total = item_one + \
item_two + \
item_three
Statements contained within the [], {}, or () brackets do not need to use the line continuation character.
days = ['Monday', 'Tuesday', 'Wednesday',
'Thursday', 'Friday']
Quotations in Python
Quotations in Python are used to represent strings. Strings are sequences of characters, and they can be used to represent text, numbers, or other data.
There are three types of quotations in Python:
Single quotes ('): Single quotes are used to enclose short strings. (Word)
Double quotes (''): Double quotes are used to enclose long strings or strings that contain single quotes. (Sentence)
Triple quotes (''' or ""'): Triple quotes are used to enclose multi-line strings or strings that contain both single and double quotes. (Paragraph)
Variable: Creating, Printing, and Deleting
Variables are defined with the assignment operator, “=”. Python is dynamically typed, meaning that variables can be assigned without declaring their type, and that their type can change. Values can come from constants, from computation involving values of other variables, or from the output of a function. Python variables are containers for storing data values.
They are created the moment you assign a value to them, and you can use them to store any type of data, including numbers, strings, lists, dictionaries, and objects.
To create a variable in Python, you simply need to assign a value to it.
There is no need to declare variables before using them.
Python variables can be used to store any type of data, including numbers, strings, lists, dictionaries, and objects
Example:
my_number = 10
my_string = "Hello, world!"
my_list = [1, 2, 3]
my_dictionary = {"name": "Alice", "age": 25} my_object = MyClass()
To create a variable in Python, simply assign a value to it. For example, the following code creates a variable called name and assigns it the value "Kiran":
Once a variable has been created, you can access its value using its name. For example, the following code prints the value of the name variable to the console:
To delete a variable in Python, you can use the del keyword. For example, the following code deletes the name variable:
name = "Kiran"
age = 33
print(name)
print(age)
del name
del age
Rules for Variable Names
Tips for using variable names in Python:
Give variables meaningful names. This will make your code more readable and easier to understand.
Use consistent naming conventions. This will make your code more consistent and easier to maintain.
Avoid using global variables whenever possible. Global variables can make your code more difficult to debug and maintain.
Use local variables whenever possible. Local variables are only accessible within the scope in which they are defined. This makes it easier to track down errors and to prevent unexpected behaviour.
Avoid using names that are too long or too short.
Python Program for calculating Area of Rectangle by getting the input form the user
Local variables are defined inside a function and can only be accessed from within that function.
Local variables in Python are those which are initialized inside a function and belong only to that particular function. It cannot be accessed anywhere outside the function.
Global variables are defined outside of any function and can be accessed from anywhere in your program.
These are those which are defined outside any function and which are accessible throughout the program, i.e., inside and outside of every function.
Operators in Python
Python has a number of operators that can be used to perform operations on data types.
Arithmetic operators: +, -, *, /, //, %, **
Comparison operators: ==, !=, <, >, <=, >=
Logical operators: and, or, not
Bitwise operators: &, |, ^, ~, <<, >>
Assignment operators: =, +=, -=, *=, /=, //=, %=, **=
Arithmetic operators:
Arithmetic operators in Python are used to perform mathematical operations on numbers.
Addition (+): Adds two numbers together.
Subtraction (-): Subtracts one number from another.
Multiplication (*): Multiplies two numbers together.
Division (/): Divides one number by another.
Floor division (//): Divides one number by another and returns the quotient rounded down to the nearest integer.
Modulus (%): Returns the remainder of dividing one number by another.
Exponentiation (**): Raises one number to the power of another.
Comparison operators:
Comparison operators in Python are used to compare the values of two operands. The operands can be any type of data, such as numbers, strings, lists, or objects. Comparison operators return a Boolean value, True or False, depending on whether the condition is met.
Equal to (==): Returns True if the two operands are equal, and False otherwise.
Not equal to (!=): Returns True if the two operands are not equal, and False otherwise.
Greater than (>): Returns True if the left operand is greater than the right operand, and False otherwise.
Less than (<): Returns True if the left operand is less than the right operand, and False otherwise.
Greater than or equal to (>=): Returns True if the left operand is greater than or equal to the right operand, and False otherwise.
Less than or equal to (<=): Returns True if the left operand is less than or equal to the right operand, and False otherwise.
Logical operators:
Logical operators in Python are used to combine multiple Boolean expressions into a single Boolean expression.
The three logical operators in Python are:
And (and): Returns True if both operands are True, and False otherwise.
Or (or): Returns True if either operand is True, and False otherwise.
Not (not): Inverts the result of the operand. If the operand is True, it returns False. If the operand is False, it returns True.
Bitwise operators:
Bitwise operators in Python are used to perform operations on the individual bits of an integer.
Bitwise AND (&): Returns a 1 if both corresponding bits in the operands are 1, and 0 otherwise.
Bitwise OR (|): Returns a 1 if either of the corresponding bits in the operands is 1, and 0 otherwise.
Bitwise XOR (^): Returns a 1 if the corresponding bits in the operands are different, and 0 otherwise.
Bitwise NOT (~): Inverts all of the bits in the operand.
Bitwise left shift (<<): Shifts all of the bits in the operand to the left by the specified number of bits.
Bitwise right shift (>>): Shifts all of the bits in the operand to the right by the specified number of bits.
Assignment operators:
Assignment operators in Python are used to assign values to variables.
The most basic assignment operator is the equal sign (=).
In addition to the basic assignment operator, there are a number of other assignment operators in Python that can be used to combine arithmetic operations with assignment.
Add and assign (+=): Adds the right-hand operand to the left-hand operand and assigns the result to the left-hand operand.
Subtract and assign (-=): Subtracts the right-hand operand from the left-hand operand and assigns the result to the left-hand operand.
Multiply and assign (*=): Multiplies the two operands and assigns the result to the left-hand operand.
Divide and assign (/=): Divides the left-hand operand by the right-hand operand and assigns the result to the left-hand operand.
Floor divide and assign (//=): Divides the left-hand operand by the right-hand operand and discards the fractional part of the result. The result is then assigned to the left-hand operand.
Modulus and assign (%=): Divides the left-hand operand by the right-hand operand and assigns the remainder of the division to the left-hand operand.
Exponentiation and assign (**=): Raises the left-hand operand to the power of the right-hand operand and assigns the result to the left-hand operand.
Data Types in Python
Python has a number of built-in data types, including:
Numbers: Integers (int), floating-point numbers (float), and complex numbers (complex)
Strings: Sequences of characters (str)
Lists: Ordered collections of items (list)
Tuples: Ordered collections of items that cannot be changed (tuple)
Sets: Unordered collections of unique items (set)
Dictionaries: Key-value pairs (dict)
Numbers - Numbers can be integers, floats, or complex numbers. Integers are whole numbers, such as 1, 2, and 3. Floats are decimal numbers, such as 3.14 and 1.2e3. Complex numbers are numbers of the form a + bi, where a and b are real numbers and i is the imaginary unit.
Strings - Strings are sequences of characters. Strings can be represented in single quotes (') or double quotes (").
Lists - Lists are ordered collections of objects. Lists can be created using square brackets ([]). Lists can also contain other objects, such as strings, lists, and dictionaries.
Tuples - Tuples are immutable ordered collections of objects. Tuples are created using parentheses (). Tuples are similar to lists, but they cannot be changed once they are created.
Sets - Sets are unordered collections of unique objects. Sets are created using curly braces ({ }). Sets can also contain other objects, such as strings, lists, and dictionaries.
Dictionaries - Dictionaries are collections of key-value pairs. Dictionaries are created using curly braces ({ }) and colons (:)
# Create an integer
my_integer = 10
# Create a float
my_float = 3.14
# Create a complex number
my_complex_number = 1+2j
# Create a string
my_string = "Hello, world!"
# Create a list
my_list = [1, 2, 3, 4, 5]
# Create a tuple
my_tuple = (1, 2, 3, 4, 5)
# Create a set
my_set = {1, 2, 3, 4, 5}
# Create a dictionary
my_dictionary = {"name": "Bard", "age": 1
Functions in Python
A function is a block of organized, reusable code that is used to perform a single, related action. Functions provide better modularity for your application and a high degree of code reuse.
Python provides the following types of functions −
Built-in functions
Python's standard library includes a number of built-in functions. Some of Python's built-in functions are print(), int(), len(), sum(), etc. These functions are always available, as they are loaded into the computer's memory as soon as you start the Python interpreter.
Functions defined in built-in modules
The standard library also bundles a number of modules. Each module defines a group of functions. These functions are not readily available. You need to import them into the memory from their respective modules.
User-defined functions
In addition to the built-in functions and functions in the built-in modules, you can also create your own functions. These functions are called user-defined functions.
To define a function in Python, you use the def keyword.
The syntax is as follows:
def function_name(parameter1, parameter2, ...):
# Code block
return value
The function_name is the name of your function.
The parameter1, parameter2, and so on are the parameters that you can pass to the function.
The code block is the code that will be executed when the function is called.
The return statement returns a value from the function.
Example of a Simple Function
def add_numbers(a, b):
return a + b
result = add_numbers(1, 2)
print(result)
Calling a Function:
To call a function in Python, you simply type the function name followed by parentheses ().
If the function takes any arguments, they are included within the parentheses.
def factorial(n):
return n * factorial(n - 1)
factorial_result = factorial(5)
Summary and Practice Assignment
Summary
Basic Syntax and Fundamentals
Variables: Creating, printing and deleting variables, Multiple Assignment
Rules for variable names, Local and global variables
Operators in Python
Data Types in Python
Functions in Python
Practice Assignments
Define a Function in Python/MATLAB to calculate the Pressure and Density at a Given Altitude under the International Standard Atmosphere and Plot the variation with the Altitude.