Introduction To Python
Introduction To Python
Foundations of Physics
Module III - Python as Calculator
Table of Contents
6. Conditional Statements – if,
1. Introduction else and elif
2. Python 7. Loops in Python
Introduction
• What is a program?
Introduction Python Variables Input/Output Operators Conditionals Loops Derived datatypes Strings Functions
Introduction
• What is a program?
A program is a sequence of instructions that specifies how to perform a
computation. Typically consists of (i) input, (ii) output, (iii) math, (iv)
conditional executions and (v) repetition
Introduction Python Variables Input/Output Operators Conditionals Loops Derived datatypes Strings Functions
Introduction
• What is a program?
A program is a sequence of instructions that specifies how to perform a
computation. Typically consists of (i) input, (ii) output, (iii) math, (iv)
conditional executions and (v) repetition
• Types of computer languages:
◦ Low level languages: These are programming languages that can be easily
understood by the computer but not easily readable for humans. An assembler is
required to translate the instructions to binary. Such programs are hard to
debug and maintain and not portable but they are memory efficient. e.g.
Machine Language, Assembly Language
◦ High level languages: These are programming languages that are
human-readable but need to be appropriately converted for the computer to
understand. A compiler/interpreter is required for this. Easier to maintain and
debug and easily portable but less memory efficient than low-level languages.
e.g. C, C++, Python, Javascript, Ruby etc.
Introduction Python Variables Input/Output Operators Conditionals Loops Derived datatypes Strings Functions
Why Python?
1. Easy to Learn and use: Python uses very few keywords and a clear syntax
that resembles English
Introduction Python Variables Input/Output Operators Conditionals Loops Derived datatypes Strings Functions
Why Python?
1. Easy to Learn and use: Python uses very few keywords and a clear syntax
that resembles English
2. Interpreted Language: Python code is executed line by line. This makes it
easier to debug but thus has slower execution speeds and high memory
consumption compared to other languages.
Introduction Python Variables Input/Output Operators Conditionals Loops Derived datatypes Strings Functions
Why Python?
1. Easy to Learn and use: Python uses very few keywords and a clear syntax
that resembles English
2. Interpreted Language: Python code is executed line by line. This makes it
easier to debug but thus has slower execution speeds and high memory
consumption compared to other languages.
3. Versatile: Python can be used for a variety of purposes e.g. web
development, data analysis, machine learning, artifcial intelligence etc.
Introduction Python Variables Input/Output Operators Conditionals Loops Derived datatypes Strings Functions
Why Python?
1. Easy to Learn and use: Python uses very few keywords and a clear syntax
that resembles English
2. Interpreted Language: Python code is executed line by line. This makes it
easier to debug but thus has slower execution speeds and high memory
consumption compared to other languages.
3. Versatile: Python can be used for a variety of purposes e.g. web
development, data analysis, machine learning, artifcial intelligence etc.
4. Extensive Libraries: Python has a large standard library and a vast
ecosystem of third-party libraries for variety of purposes e.g. numpy,
scipy, matplotlib, pandas, PyTorch, TensorFlow, Django, Flask etc.
Introduction Python Variables Input/Output Operators Conditionals Loops Derived datatypes Strings Functions
Why Python?
1. Easy to Learn and use: Python uses very few keywords and a clear syntax
that resembles English
2. Interpreted Language: Python code is executed line by line. This makes it
easier to debug but thus has slower execution speeds and high memory
consumption compared to other languages.
3. Versatile: Python can be used for a variety of purposes e.g. web
development, data analysis, machine learning, artifcial intelligence etc.
4. Extensive Libraries: Python has a large standard library and a vast
ecosystem of third-party libraries for variety of purposes e.g. numpy,
scipy, matplotlib, pandas, PyTorch, TensorFlow, Django, Flask etc.
5. Open Source: Python source code is freely available to view, modify and
distribute.
Introduction Python Variables Input/Output Operators Conditionals Loops Derived datatypes Strings Functions
Why Python?
1. Easy to Learn and use: Python uses very few keywords and a clear syntax
that resembles English
2. Interpreted Language: Python code is executed line by line. This makes it
easier to debug but thus has slower execution speeds and high memory
consumption compared to other languages.
3. Versatile: Python can be used for a variety of purposes e.g. web
development, data analysis, machine learning, artifcial intelligence etc.
4. Extensive Libraries: Python has a large standard library and a vast
ecosystem of third-party libraries for variety of purposes e.g. numpy,
scipy, matplotlib, pandas, PyTorch, TensorFlow, Django, Flask etc.
5. Open Source: Python source code is freely available to view, modify and
distribute.
6. Object Oriented Programming: Python supports Functional
Programming (program revolves around using functions) as well as
Object Oriented Programming (program is organised using objects)
Introduction Python Variables Input/Output Operators Conditionals Loops Derived datatypes Strings Functions
Installation
Windows
1. Go to www.python.org/downloads/windows/ and download the latest
"Stable Release" of the Python installer.
2. Install Python "for all USERS" and add Python "to PATH"
3. Finish the installation with recommended settings
4. Open the command line (cmd) from the Start Menu and execute "python"
or "python3" to open the Python interpreter (REPL – Read, Evaluate, Print,
Loop)
Android
1. Install the app "PyDroid3" from the Google Play Store
2. Open the app and run the "Interpreter" from the hamburger menu on the
left.
Introduction Python Variables Input/Output Operators Conditionals Loops Derived datatypes Strings Functions
Commenting
Any section of the script that starts with the “#” symbol is not read by Python.
This allows for developers to write comments on the code which can help in
understanding and maintaining the code especially if it is to be used by other
parties. It can also be used to temporarily disable parts of the code during
testing and debugging of the script.
Introduction Python Variables Input/Output Operators Conditionals Loops Derived datatypes Strings Functions
Commenting
Any section of the script that starts with the “#” symbol is not read by Python.
This allows for developers to write comments on the code which can help in
understanding and maintaining the code especially if it is to be used by other
parties. It can also be used to temporarily disable parts of the code during
testing and debugging of the script.
Indentation
Indentation in Python defines the structure and heirarchy of the code.
Python does not use code blocks but rather indentation is used to group
statements into one block. This requires consistent indentation within
certain commands such as loops, conditionals and functions. Proper
indentation also improves code readability and reduces errors.
Introduction Python Variables Input/Output Operators Conditionals Loops Derived datatypes Strings Functions
Variables
Variables
Variables
Variables
Variables
Variables
Variables
Variables
Variables
Types of variables
Types of variables
Types of variables
Types of variables
Types of variables
Types of variables
Types of variables
Types of variables
Types of variables
Types of variables
Types of variables
• In Python, you can change or convert between different data types using
various built-in functions or methods.
Introduction Python Variables Input/Output Operators Conditionals Loops Derived datatypes Strings Functions
• In Python, you can change or convert between different data types using
various built-in functions or methods.
• Changing data types (type conversion or type casting) is a common
operation that involves converting a variable from one data type to another.
This can be achieved using built-in functions like int(), float(),
str(), and bool().
Introduction Python Variables Input/Output Operators Conditionals Loops Derived datatypes Strings Functions
• In Python, you can change or convert between different data types using
various built-in functions or methods.
• Changing data types (type conversion or type casting) is a common
operation that involves converting a variable from one data type to another.
This can be achieved using built-in functions like int(), float(),
str(), and bool().
• For instance, converting a string to an integer is done with int("123"),
and converting an integer to a string is done with str(123). Type
conversion is essential for ensuring data compatibility and correctness in
operations, such as mathematical calculations or string manipulations.
Introduction Python Variables Input/Output Operators Conditionals Loops Derived datatypes Strings Functions
Input/Output in Python
Input
Introduction Python Variables Input/Output Operators Conditionals Loops Derived datatypes Strings Functions
Input/Output in Python
Input
1. Input from the user in Python can be done using the input() command.
This function reads a line from the input (usually from the user via the
keyboard), converts it to a string, and returns it.
Introduction Python Variables Input/Output Operators Conditionals Loops Derived datatypes Strings Functions
Input/Output in Python
Input
1. Input from the user in Python can be done using the input() command.
This function reads a line from the input (usually from the user via the
keyboard), converts it to a string, and returns it.
2. Input from the user can also be read from a file.
Introduction Python Variables Input/Output Operators Conditionals Loops Derived datatypes Strings Functions
Input/Output in Python
Input
1. Input from the user in Python can be done using the input() command.
This function reads a line from the input (usually from the user via the
keyboard), converts it to a string, and returns it.
2. Input from the user can also be read from a file.
Output
Any output can be displayed either in terminal or stored in a file.
Displaying in the terminal is done using the print command which prints
the output as strings. There are several ways to format the output string:
Introduction Python Variables Input/Output Operators Conditionals Loops Derived datatypes Strings Functions
Input/Output in Python
Input
1. Input from the user in Python can be done using the input() command.
This function reads a line from the input (usually from the user via the
keyboard), converts it to a string, and returns it.
2. Input from the user can also be read from a file.
Output
Any output can be displayed either in terminal or stored in a file.
Displaying in the terminal is done using the print command which prints
the output as strings. There are several ways to format the output string:
1. Default: By default, the print command can print several arguments
separated by a space.
Introduction Python Variables Input/Output Operators Conditionals Loops Derived datatypes Strings Functions
Input/Output in Python
Input
1. Input from the user in Python can be done using the input() command.
This function reads a line from the input (usually from the user via the
keyboard), converts it to a string, and returns it.
2. Input from the user can also be read from a file.
Output
Any output can be displayed either in terminal or stored in a file.
Displaying in the terminal is done using the print command which prints
the output as strings. There are several ways to format the output string:
1. Default: By default, the print command can print several arguments
separated by a space.
2. str.format: This method allows for more advanced string formatting by
replacing placeholders ‘{}’ with variables or expressions.
Introduction Python Variables Input/Output Operators Conditionals Loops Derived datatypes Strings Functions
Input/Output in Python
Input
1. Input from the user in Python can be done using the input() command.
This function reads a line from the input (usually from the user via the
keyboard), converts it to a string, and returns it.
2. Input from the user can also be read from a file.
Output
Any output can be displayed either in terminal or stored in a file.
Displaying in the terminal is done using the print command which prints
the output as strings. There are several ways to format the output string:
1. Default: By default, the print command can print several arguments
separated by a space.
2. str.format: This method allows for more advanced string formatting by
replacing placeholders ‘{}’ with variables or expressions.
3. f-strings: These are a concise and readable way to embed expressions
inside string literals using curly braces.
Introduction Python Variables Input/Output Operators Conditionals Loops Derived datatypes Strings Functions
Input/Output in Python
Input
1. Input from the user in Python can be done using the input() command.
This function reads a line from the input (usually from the user via the
keyboard), converts it to a string, and returns it.
2. Input from the user can also be read from a file.
Output
Any output can be displayed either in terminal or stored in a file.
Displaying in the terminal is done using the print command which prints
the output as strings. There are several ways to format the output string:
1. Default: By default, the print command can print several arguments
separated by a space.
2. str.format: This method allows for more advanced string formatting by
replacing placeholders ‘{}’ with variables or expressions.
3. f-strings: These are a concise and readable way to embed expressions
inside string literals using curly braces.
You can also specify the separator and end parameters.
Introduction Python Variables Input/Output Operators Conditionals Loops Derived datatypes Strings Functions
Arithematic Operators
Introduction Python Variables Input/Output Operators Conditionals Loops Derived datatypes Strings Functions
Comparison Operators
Introduction Python Variables Input/Output Operators Conditionals Loops Derived datatypes Strings Functions
Assignment Operators
Introduction Python Variables Input/Output Operators Conditionals Loops Derived datatypes Strings Functions
if statements
An if statement allows you to execute certain blocks of code based on specific
conditions. It enables decision-making in the program by evaluating a condition and
determining whether it is True or False. The syntax is given by:
Introduction Python Variables Input/Output Operators Conditionals Loops Derived datatypes Strings Functions
if statements
An if statement allows you to execute certain blocks of code based on specific
conditions. It enables decision-making in the program by evaluating a condition and
determining whether it is True or False. The syntax is given by:
if-else statements
Following an if statement block, the else keyword can be used, followed by another
colon and an indented block of code that runs if the condition is False. This structure
enables you to handle binary decisions effectively, ensuring that one of the two code
blocks is always executed. The syntax is given by:
Introduction Python Variables Input/Output Operators Conditionals Loops Derived datatypes Strings Functions
if-elif-else statements
It begins with an if statement, where a specific condition is evaluated. If this condition is
true, the corresponding block of code executes. If the initial condition is false, the program
proceeds to check subsequent elif (else if) statements in sequence. Each elif statement
introduces another condition to evaluate, providing additional pathways for the program’s
logic based on different scenarios. Finally, if none of the preceding conditions are met, the
else block, if present, serves as a catch-all for executing code when all previous conditions
evaluate to false.
Introduction Python Variables Input/Output Operators Conditionals Loops Derived datatypes Strings Functions
Loops in Python
Loops in Python
Loops in Python
range object
range(stop)
range(start, stop[, step])
The range keyword is used in Python to produce an object containing a
sequence of integers from start(inclusive) to stop(exclusive) with step
increment (positive or negative). Default value of start is 0.
Introduction Python Variables Input/Output Operators Conditionals Loops Derived datatypes Strings Functions
Unlike for loops, which iterate over a sequence of elements, while loops
continue iterating until the condition specified at the start of the loop
evaluates to False.
Introduction Python Variables Input/Output Operators Conditionals Loops Derived datatypes Strings Functions
Fine-tuning loops
There are two useful statements that can be used within loops to fine-tune
how they are executed:
• The break statement breaks out of the loop entirely
• The continue statement skips the remainder of the current loop, and goes
to the next iteration
These can be used in both for and while loops.
Introduction Python Variables Input/Output Operators Conditionals Loops Derived datatypes Strings Functions
Complex numbers
Complex numbers
Complex numbers
Complex numbers
Complex numbers
Lists
Lists are ordered collections of items. They are mutable, meaning that their
elements can be changed after they are created. Python allows for several
operations on lists as well:
Introduction Python Variables Input/Output Operators Conditionals Loops Derived datatypes Strings Functions
Lists
Lists are ordered collections of items. They are mutable, meaning that their
elements can be changed after they are created. Python allows for several
operations on lists as well:
• append: Append an object to the end of a list.
Introduction Python Variables Input/Output Operators Conditionals Loops Derived datatypes Strings Functions
Lists
Lists are ordered collections of items. They are mutable, meaning that their
elements can be changed after they are created. Python allows for several
operations on lists as well:
• append: Append an object to the end of a list.
• extend: Extend list by appending elements from the iterable.
Introduction Python Variables Input/Output Operators Conditionals Loops Derived datatypes Strings Functions
Lists
Lists are ordered collections of items. They are mutable, meaning that their
elements can be changed after they are created. Python allows for several
operations on lists as well:
• append: Append an object to the end of a list.
• extend: Extend list by appending elements from the iterable.
• Concatenation
Introduction Python Variables Input/Output Operators Conditionals Loops Derived datatypes Strings Functions
Lists
Lists are ordered collections of items. They are mutable, meaning that their
elements can be changed after they are created. Python allows for several
operations on lists as well:
• append: Append an object to the end of a list.
• extend: Extend list by appending elements from the iterable.
• Concatenation
• insert: Insert object before index.
Introduction Python Variables Input/Output Operators Conditionals Loops Derived datatypes Strings Functions
Lists
Lists are ordered collections of items. They are mutable, meaning that their
elements can be changed after they are created. Python allows for several
operations on lists as well:
• append: Append an object to the end of a list.
• extend: Extend list by appending elements from the iterable.
• Concatenation
• insert: Insert object before index.
• remove: Remove first occurrence of value.
Introduction Python Variables Input/Output Operators Conditionals Loops Derived datatypes Strings Functions
Lists
Lists are ordered collections of items. They are mutable, meaning that their
elements can be changed after they are created. Python allows for several
operations on lists as well:
• append: Append an object to the end of a list.
• extend: Extend list by appending elements from the iterable.
• Concatenation
• insert: Insert object before index.
• remove: Remove first occurrence of value.
• pop: Remove and return item at index (default last).
Introduction Python Variables Input/Output Operators Conditionals Loops Derived datatypes Strings Functions
Lists
Lists are ordered collections of items. They are mutable, meaning that their
elements can be changed after they are created. Python allows for several
operations on lists as well:
• append: Append an object to the end of a list.
• extend: Extend list by appending elements from the iterable.
• Concatenation
• insert: Insert object before index.
• remove: Remove first occurrence of value.
• pop: Remove and return item at index (default last).
• index: Return first index of value.
Introduction Python Variables Input/Output Operators Conditionals Loops Derived datatypes Strings Functions
Lists
Lists are ordered collections of items. They are mutable, meaning that their
elements can be changed after they are created. Python allows for several
operations on lists as well:
• append: Append an object to the end of a list.
• extend: Extend list by appending elements from the iterable.
• Concatenation
• insert: Insert object before index.
• remove: Remove first occurrence of value.
• pop: Remove and return item at index (default last).
• index: Return first index of value.
• count: Return number of occurrences of value.
Introduction Python Variables Input/Output Operators Conditionals Loops Derived datatypes Strings Functions
Lists
Lists are ordered collections of items. They are mutable, meaning that their
elements can be changed after they are created. Python allows for several
operations on lists as well:
• append: Append an object to the end of a list.
• extend: Extend list by appending elements from the iterable.
• Concatenation
• insert: Insert object before index.
• remove: Remove first occurrence of value.
• pop: Remove and return item at index (default last).
• index: Return first index of value.
• count: Return number of occurrences of value.
• sort: Sort the list in ascending order and return None.
Introduction Python Variables Input/Output Operators Conditionals Loops Derived datatypes Strings Functions
Lists
• reverse: Reverse *IN PLACE*.
Introduction Python Variables Input/Output Operators Conditionals Loops Derived datatypes Strings Functions
Lists
• reverse: Reverse *IN PLACE*.
• len: Return the number of items in the list.
Introduction Python Variables Input/Output Operators Conditionals Loops Derived datatypes Strings Functions
Lists
• reverse: Reverse *IN PLACE*.
• len: Return the number of items in the list.
• max: Return the biggest item in a list.
Introduction Python Variables Input/Output Operators Conditionals Loops Derived datatypes Strings Functions
Lists
• reverse: Reverse *IN PLACE*.
• len: Return the number of items in the list.
• max: Return the biggest item in a list.
• min: Return the smallest item in a list.
Introduction Python Variables Input/Output Operators Conditionals Loops Derived datatypes Strings Functions
Lists
• reverse: Reverse *IN PLACE*.
• len: Return the number of items in the list.
• max: Return the biggest item in a list.
• min: Return the smallest item in a list.
• sorted: Return a new list containing all items from the iterable in
ascending order.
Introduction Python Variables Input/Output Operators Conditionals Loops Derived datatypes Strings Functions
Lists
• reverse: Reverse *IN PLACE*.
• len: Return the number of items in the list.
• max: Return the biggest item in a list.
• min: Return the smallest item in a list.
• sorted: Return a new list containing all items from the iterable in
ascending order.
• sum: Return the sum of a list of numbers
Introduction Python Variables Input/Output Operators Conditionals Loops Derived datatypes Strings Functions
Lists
• reverse: Reverse *IN PLACE*.
• len: Return the number of items in the list.
• max: Return the biggest item in a list.
• min: Return the smallest item in a list.
• sorted: Return a new list containing all items from the iterable in
ascending order.
• sum: Return the sum of a list of numbers
Slicing
Elements of lists can also be accessed using slicing.
Introduction Python Variables Input/Output Operators Conditionals Loops Derived datatypes Strings Functions
Lists
• reverse: Reverse *IN PLACE*.
• len: Return the number of items in the list.
• max: Return the biggest item in a list.
• min: Return the smallest item in a list.
• sorted: Return a new list containing all items from the iterable in
ascending order.
• sum: Return the sum of a list of numbers
Slicing
Elements of lists can also be accessed using slicing.
• Syntax: lst[start:stop:step]
Introduction Python Variables Input/Output Operators Conditionals Loops Derived datatypes Strings Functions
Lists
• reverse: Reverse *IN PLACE*.
• len: Return the number of items in the list.
• max: Return the biggest item in a list.
• min: Return the smallest item in a list.
• sorted: Return a new list containing all items from the iterable in
ascending order.
• sum: Return the sum of a list of numbers
Slicing
Elements of lists can also be accessed using slicing.
• Syntax: lst[start:stop:step]
• Indexes/Steps can be positive or negative
Introduction Python Variables Input/Output Operators Conditionals Loops Derived datatypes Strings Functions
Lists
• reverse: Reverse *IN PLACE*.
• len: Return the number of items in the list.
• max: Return the biggest item in a list.
• min: Return the smallest item in a list.
• sorted: Return a new list containing all items from the iterable in
ascending order.
• sum: Return the sum of a list of numbers
Slicing
Elements of lists can also be accessed using slicing.
• Syntax: lst[start:stop:step]
• Indexes/Steps can be positive or negative
• e.g. l[1:3], l[:3], l[1:], l[::2], l[::-1], l[-4:]
Introduction Python Variables Input/Output Operators Conditionals Loops Derived datatypes Strings Functions
Tuples
Tuples are ordered collections of items that are immutable, meaning that
their elements cannot be changed after they are created.
Even though the elements cannot be modified they can be accessed using
other ways:
• slicing
• length
• count
• index
Introduction Python Variables Input/Output Operators Conditionals Loops Derived datatypes Strings Functions
Dictionaries
Sets
Sets are unordered collections of unique items. They are mutable, meaning
that their elements can be changed after they are created.
There are certain inbuilt functions that can be used on Sets.
• add: add elements to the set
• remove: remove elements from the set
• union: items appearing in either
• intersection: items appearing in both
• difference: items appearing in one but not the other
• symmetric difference: items appearing in only one set
Introduction Python Variables Input/Output Operators Conditionals Loops Derived datatypes Strings Functions
Strings
Strings are ordered sequence of letters, numbers and special characters that
are immutable. Strings in Python also have certain functions and methods
that can be used.
• len
• upper
• lower
• title
• capitalize
• count
• split
• indexing/slicing
Introduction Python Variables Input/Output Operators Conditionals Loops Derived datatypes Strings Functions
Functions
Functions
Functions
Functions
Defining and Calling functions
Introduction Python Variables Input/Output Operators Conditionals Loops Derived datatypes Strings Functions
Functions
Defining and Calling functions
• Defining and calling functions in Python allows you to encapsulate
reusable blocks of code for efficient and modular programming.
Introduction Python Variables Input/Output Operators Conditionals Loops Derived datatypes Strings Functions
Functions
Defining and Calling functions
• Defining and calling functions in Python allows you to encapsulate
reusable blocks of code for efficient and modular programming.
• To define a function, use the def keyword followed by the function name
and any parameters within parentheses. The function body, indented
following a colon:, contains the code to execute when the function is called.
Introduction Python Variables Input/Output Operators Conditionals Loops Derived datatypes Strings Functions
Functions
Defining and Calling functions
• Defining and calling functions in Python allows you to encapsulate
reusable blocks of code for efficient and modular programming.
• To define a function, use the def keyword followed by the function name
and any parameters within parentheses. The function body, indented
following a colon:, contains the code to execute when the function is called.
• To call a function, simply use its name followed by parentheses, optionally
passing any required arguments.
Introduction Python Variables Input/Output Operators Conditionals Loops Derived datatypes Strings Functions
Functions
Defining and Calling functions
• Defining and calling functions in Python allows you to encapsulate
reusable blocks of code for efficient and modular programming.
• To define a function, use the def keyword followed by the function name
and any parameters within parentheses. The function body, indented
following a colon:, contains the code to execute when the function is called.
• To call a function, simply use its name followed by parentheses, optionally
passing any required arguments.
Functions
Defining and Calling functions
• Defining and calling functions in Python allows you to encapsulate
reusable blocks of code for efficient and modular programming.
• To define a function, use the def keyword followed by the function name
and any parameters within parentheses. The function body, indented
following a colon:, contains the code to execute when the function is called.
• To call a function, simply use its name followed by parentheses, optionally
passing any required arguments.
Functions
Defining and Calling functions
• Defining and calling functions in Python allows you to encapsulate
reusable blocks of code for efficient and modular programming.
• To define a function, use the def keyword followed by the function name
and any parameters within parentheses. The function body, indented
following a colon:, contains the code to execute when the function is called.
• To call a function, simply use its name followed by parentheses, optionally
passing any required arguments.
Functions
Defining and Calling functions
• Defining and calling functions in Python allows you to encapsulate
reusable blocks of code for efficient and modular programming.
• To define a function, use the def keyword followed by the function name
and any parameters within parentheses. The function body, indented
following a colon:, contains the code to execute when the function is called.
• To call a function, simply use its name followed by parentheses, optionally
passing any required arguments.
Functions
Functions
Functions
Functions