SlideShare ist ein Scribd-Unternehmen logo
1 von 129
Interpreter v/s Compiler
Interpreter Compiler
Translates program one statement at a
time.
Scans the entire program and
translates it as a whole into machine
code.
Interpreters usually take less amount
of time to analyze the source code.
However, the overall execution time is
comparatively slower than compilers.
Compilers usually take a large amount
of time to analyze the source code.
However, the overall execution time is
comparatively faster than interpreters.
No Object Code is generated, hence
are memory efficient.
Generates Object Code which further
requires linking, hence requires more
memory.
Programming languages like JavaScript,
Python, Ruby use interpreters.
Programming languages like C, C++,
Java use compilers.
Python
What Is Python
Python is an open-sourced, interpreted, object-oriented, high-level
programming language with dynamic syntax. It is highly attractive for Rapid
Application Development and scripting.
Most importantly, it is readable, simple, easy to learn & use which indeed
increases productivity and reduces the cost of maintenance.
It was initially formulated by Guido van Rossum in the late 1980s at Centrum
Wiskunde & Informatica(CWI) in Netherland as a successor to the ABC
language. The name Python was named after a BBC’s TV Show called ‘Monty
Python’s Flying Circus‘ which he was a fan of.
The name was perfect at that time since he wanted a short, unique, and
slightly mysterious name for his invention.
It may be interesting to know how the different Python versions evolved and
what features they introduced. In the table below, we can see Python’s first
two major versions(1.0, 2.0), when they were released and what features
they introduced before version 3 was designed to rectify the fundamental
flaw of the language.
Python
Table on Python versions 1.0 and 2.0 features and released date.
Python Version Features Released Date
1.0 Exception Handling,
lambda, filter, reduce,
map
January 1994
2.0 List comprehensions,
garbage collection
systems
October 16, 2020
Python
Python versions 2.x and 3.x are the most used Python versions. The latest
stable version of Python is 3.10.6, released on August 2, 2022.
Since the first release in 1994, Python has had regular updates with new
features and supports.
Python
Why Python ?
The question should be: “Why not Python?“. Python is one of the fastest-
growing programming languages in the world and it is used by top companies
like Google, Facebook, YouTube, Spotify, Instagram, Netflix, etc.
In this section, we shall look at where Python is being used, some
benefits/drawbacks, and lastly how it is compared to other popular
programming languages.
What Is Python Used For?
As of now, Python has many libraries and frameworks ranging
from Numpy, SQLALchemy, Pytorch, Pandas, Keras, Tensorflow, Django,
Flask, etc. and it is still growing rapidly. These have made Python a top choice
for many developers and companies.
Python is popularly used for Development, Scripting, and software testing
which indeed has made it suitable for various domains.
Where Python is used:-
1. Desktop and Web Applications
2. Data Science
3. Machine Learning
4. Robotics
5. Artificial Intelligence
6. Internet of Things (IoT)
7. Gaming
8. Mobile Applications
9. Natural Language processing
Benefits And Drawbacks Of Python
• The various attractive features of Python make it popular and preferred in many
fields.
• Some of the top features of Python include:
• Free and Open-Sourced
• Dynamically typed
• Portable
• Numerous libraries and applications
• Large supportive community
• Flexibility
• Easy to use and learn
• Extensible
• Embeddable
• Shorter line of code than most languages
Though Python is popular, it is not effective in some domains. Knowing these
drawbacks will help us to limit Python to where it is effective, thereby building robust
applications.
Some Drawbacks of Python are:
• Slow speed
• Memory inefficient
• Ineffective in mobile computing.
• Undeveloped database layers.
• Run time error prompt due to its dynamism.
How to execute Python Programs / Scripts ?
Different ways to run Python Script
Here are the ways with which we can run a Python script.
1. Interactive Mode
2. Command Line
3. Text Editor (VS Code)
4. IDE (PyCharm, jupyter etc)
1. The Python Interactive Mode
• This is the most frequently used way to run a Python
code. Here basically we do the following:
• Open command prompt / terminal in your system
• Enter the command - python or python3 (based on
python version installed in your system)
• If we see these : >>> then, we are into our python
prompt.
• The interactive shell is also called REPL which stands
for read, evaluate, print, loop. It'll read each
command, evaluate and execute it, print the output
for that command if any, and continue this same
process repeatedly until you quit the shell.
• There are different ways to quit the shell:
• you can hit Ctrl+Z on Windows or Ctrl+D on Unix
systems to quit
• use the exit() command
• use the quit() command
• Pros:
• Best for testing every single line of code written.
• In this approach, each line of code is evaluated and executed immediately
as soon as we hit ↵ Enter.
• Great deveopment tool for experimentation of Python code on the way.
• Cons:
• The code is gone as soon as we close the terminal(or the interactive
session)
• Not user friendly way to write long code.
• To close the interactive session we can:
• Type quit() or exit()
• Press ctrl + z and hit ↵ Enter for windows. For linux, we can press ctrl+d.
2. Using the Python Command Line
• Follow the below steps to run a Python Code through
command line -
• Write your Python code into any text editor.
• Save it with the extension .py into a suitable
directory
• Open the terminal or command prompt.
• Type python/python3 (based on installation)
followed by the file name.py –
• Eg:- python sample.py
3. Run Python on Text Editor
• If you want to run your Python code into a
text editor -- suppose VS Code, then follow
the below steps:
• From extensions section, find and install
'Python' extension
3. Run Python on Text Editor
• If you want to run your Python code into a
text editor -- suppose VS Code, then follow
the below steps:
• From extensions section, find and install
'Python' extension
• Restart your VS code to make sure the extension is
installed properly
• Create a new file, type your Python code and save it
• Run it using the VS code's terminal by typing the
command "py hello.py"
Or, Right Click -> Run Python file in terminal
• 4. Run Python on IDLE
• Python installation comes with an Integrated Development
and Learning Environment, which is popularly known as IDLE.
Though Python IDLE are by-default included with Python
installations on Windows and Mac, if you’re a Linux user, then
you can easily download Python IDLE using your package
manager.
• Steps to run a python program on IDLE:
• Open the Python IDLE(navigate to the path where Python is
installed, open IDLE(python version))
• The shell is the default mode of operation for Python IDLE. So,
the first thing you will see is the Python Shell --
• You can write any code here and press enter
to execute
• To run a Python script you can go to File ->
New File
Now, write your code and save the file --
Once saved, you can run your code from Run ->
Run Module Or simply by pressing F5 --
Python Indentation
• Indentation refers to the spaces at the beginning of a code line.
• Where in other programming languages the indentation in code is for
readability only, the indentation in Python is very important.
• Python uses indentation to indicate a block of code.
Python will give you an error if you skip the indentation:
Example
Syntax Error:
if 5 > 2:
print("Five is greater than two!")
The number of spaces is up to you as a programmer, the most common use is
four, but it has to be at least one.
Example
• if 5 > 2:
print("Five is greater than two!")
if 5 > 2:
print("Five is greater than two!")
You have to use the same number of spaces in the same block of code,
otherwise Python will give you an error:
Python Variables
In Python, variables are created when you assign a value to it:
Example
Variables in Python:
x = 5
y = "Hello, World!"
Python has no command for declaring a variable.
Variables do not need to be declared with any particular type, and can even change
type after they have been set.
Example
x = 4 # x is of type int
x = "Sally" # x is now of type str
print(x)
Python Variables
Casting
If you want to specify the data type of a variable, this can be done with casting.
Example
x = str(3) # x will be '3'
y = int(3) # y will be 3
z = float(3) # z will be 3.0
Get the Type
You can get the data type of a variable with the type() function.
Example
x = 5
y = "John"
print(type(x))
print(type(y))
Python Variables
• Single or Double Quotes?
• String variables can be declared either by using single or double quotes:
• Example
• x = "John"
# is the same as
x = 'John‘
Case-Sensitive
• Variable names are case-sensitive.
• Example
• This will create two variables:
• a = 4
A = "Sally"
#A will not overwrite a
•
Variable Names
• A variable can have a short name (like x and y) or a more descriptive name (age,
carname, total_volume). Rules for Python variables:A variable name must start
with a letter or the underscore character
• A variable name cannot start with a number
• A variable name can only contain alpha-numeric characters and underscores (A-z,
0-9, and _ )
• Variable names are case-sensitive (age, Age and AGE are three different variables)
Example
• Legal variable names:
• myvar = "John"
my_var = "John"
_my_var = "John"
myVar = "John"
MYVAR = "John"
myvar2 = "John"
Variable Names
• A variable can have a short name (like x and y) or a more descriptive name (age,
carname, total_volume). Rules for Python variables:A variable name must start
with a letter or the underscore character
• A variable name cannot start with a number
• A variable name can only contain alpha-numeric characters and underscores (A-z,
0-9, and _ )
• Variable names are case-sensitive (age, Age and AGE are three different variables)
Example
• Legal variable names:
• myvar = "John"
my_var = "John"
_my_var = "John"
myVar = "John"
MYVAR = "John"
myvar2 = "John"
Variable Names
• Example
Illegal variable names:
2myvar = "John"
my-var = "John"
my var = "John"
• Multi Words Variable Names
• Variable names with more than one word can be difficult to read.
• There are several techniques you can use to make them more readable:
Camel Case
• Each word, except the first, starts with a capital letter:
• myVariableName = "John"
Pascal Case
• Each word starts with a capital letter:
• MyVariableName = "John"
Snake Case
• Each word is separated by an underscore character:
• my_variable_name = "John"
Assign Multiple Variables
Python allows you to assign values to multiple variables in one line:
• Example
• x, y, z = "Orange", "Banana", "Cherry"
print(x)
print(y)
print(z)
One Value to Multiple Variables
• And you can assign the same value to multiple variables in one line:
• Example
• x = y = z = "Orange"
print(x)
print(y)
print(z)
Assign Multiple Variables
Unpack a Collection
• If you have a collection of values in a list, tuple etc. Python allows you to extract
the values into variables. This is called unpacking.
• Example
• Unpack a list:
• fruits = ["apple", "banana", "cherry"]
x, y, z = fruits
print(x)
print(y)
print(z)
Python - Output Variables
Output Variables
• The Python print() function is often used to output variables.
• Example
• x = "Python is awesome"
print(x)
In the print() function, you output multiple variables, separated by a comma:
• Example
• x = "Python"
y = "is"
z = "awesome"
print(x, y, z)
You can also use the + operator to output multiple variables:
• Example
• x = "Python "
y = "is "
z = "awesome"
print(x + y + z)
Python - Output Variables
For numbers, the + character works as a mathematical operator:
• Example
• x = 5
y = 10
print(x + y)
• In the print() function, when you try to combine a string and a number with
the + operator, Python will give you an error:
• Example
• x = 5
y = "John"
print(x + y)
• The best way to output multiple variables in the print() function is to separate
them with commas, which even support different data types:
• Example
• x = 5
y = "John"
print(x, y)
Python - Global Variables
• Variables that are created outside of a function are known as global variables.
• Global variables can be used by everyone, both inside of functions and outside.
Create a variable outside of a function, and use it inside the function
x = "awesome"
def myfunc():
print("Python is " + x)
myfunc()
If you create a variable with the same name inside a function, this variable will be
local, and can only be used inside the function. The global variable with the same
name will remain as it was, global and with the original value.
Python - Global Variables
The global Keyword
• Normally, when you create a variable inside a function, that variable is local, and
can only be used inside that function.
• To create a global variable inside a function, you can use the global keyword.
Example
• If you use the global keyword, the variable belongs to the global scope:
• def myfunc():
global x
x = "fantastic"
myfunc()
print("Python is " + x)
Python - Global Variables
Also, use the global keyword if you want to change a global variable inside a function.
Example
To change the value of a global variable inside a function, refer to the variable by using
the global keyword:
x = "awesome"
def myfunc():
global x
x = "fantastic"
myfunc()
print("Python is " + x)
Python - DATA Types
Built-in Data Types
• In programming, data type is an important concept.
• Variables can store data of different types, and different types can do different
things.
• Python has the following data types built-in by default, in these categories:
Text Type: str
Numeric Types: int, float, complex
Sequence Types: list, tuple, range
Mapping Type: dict
Set Types: set, frozenset
Boolean Type: bool
Binary Types: bytes, bytearray, memoryview
None Type: NoneType
Python - Global Variables
Getting the Data Type
• You can get the data type of any object by using the type() function:
• Example
• Print the data type of the variable x:
• x = 5
print(type(x))
Setting the Data Type
• In Python, the data type is set when you assign a value to a variable:
Example Data Type
x = "Hello World" str
x = 20 int
x = 20.5 float
x = 1j complex
x = ["apple", "banana", "cherry"] list
x = ("apple", "banana", "cherry") tuple
x = range(6) range
x = {"name" : "John", "age" : 36} dict
x = {"apple", "banana", "cherry"} set
x = frozenset({"apple", "banana", "cherry"}) frozenset
x = True bool
x = b"Hello" bytes
x = bytearray(5) bytearray
x = memoryview(bytes(5)) memoryview
x = None NoneType
Python - Numbers
• There are three numeric types in Python:
• int
• float
• complex
• Variables of numeric types are created when you assign a value to them:
• Example
• x = 1 # int
y = 2.8 # float
z = 1j # complex
• To verify the type of any object in Python, use the type() function:
Example
• print(type(x))
print(type(y))
print(type(z))
Python - Numbers
Int
Int, or integer, is a whole number, positive or negative, without decimals, of unlimited
length.
Example
Integers:
x = 1
y = 35656222554887711
z = -3255522
print(type(x))
print(type(y))
print(type(z))
Python - Numbers
Float
Float, or "floating point number" is a number, positive or negative, containing one or
more decimals.
Float can also be scientific numbers with an "e" to indicate the power of 10.
Example
Floats:
x = 35e3
y = 12E4
z = -87.7e100
x = 1.10
y = 1.0
z = -35.59
print(type(x))
print(type(y))
print(type(z))
Python - Numbers
Complex
• Complex numbers are written with a "j" as the imaginary part:
x = 3+5j
y = 5j
z = -5j
print(type(x))
print(type(y))
print(type(z))
Random Number
• Python does not have a random() function to make a random number, but Python
has a built-in module called random that can be used to make random numbers:
Example
• Import the random module, and display a random number between 1 and 9:
• import random
print(random.randrange(1, 10))
Python - Numbers
Type Conversion
• You can convert from one type to another with the int(), float(),
and complex() methods:
• Example
• Convert from one type to another:
• x = 1 # int
y = 2.8 # float
z = 1j # complex
#convert from int to float:
a = float(x)
#convert from float to int:
b = int(y)
#convert from int to complex:
c = complex(x)
print(a) print(b) print(c)
print(type(a)) print(type(b)) print(type(c))
Python - Numbers
Type Conversion
• You can convert from one type to another with the int(), float(),
and complex() methods:
• Example
• Convert from one type to another:
• x = 1 # int
y = 2.8 # float
z = 1j # complex
#convert from int to float:
a = float(x)
#convert from float to int:
b = int(y)
#convert from int to complex:
c = complex(x)
print(a) print(b) print(c)
print(type(a)) print(type(b)) print(type(c))
Python - Casting
Specify a Variable Type
• There may be times when you want to specify a type on to a variable. This can be
done with casting. Python is an object-orientated language, and as such it uses
classes to define data types, including its primitive types.
• Casting in python is therefore done using constructor functions:
• int() - constructs an integer number from an integer literal, a float literal (by
removing all decimals), or a string literal (providing the string represents a whole
number)
• float() - constructs a float number from an integer literal, a float literal or a string
literal (providing the string represents a float or an integer)
• str() - constructs a string from a wide variety of data types, including strings,
integer literals and float literals
Example
Integers:
x = int(1) # x will be 1
y = int(2.8) # y will be 2
z = int("3") # z will be 3
Python - Strings
Strings
• Strings in python are surrounded by either single quotation marks, or double
quotation marks.
• 'hello' is the same as "hello".
• You can display a string literal with the print() function:
Example
• print("Hello")
print('Hello')
• Multiline Strings
• You can assign a multiline string to a variable by using three quotes:
• Example
• You can use three double quotes:
• a = """Lorem ipsum dolor sit amet,
consectetur adipiscing elit,
ut labore et dolore magna aliqua."""
print(a)
Python - Strings
Strings are Arrays
• Like many other popular programming languages, strings in Python are arrays of
bytes representing unicode characters.
• However, Python does not have a character data type, a single character is simply
a string with a length of 1.
• Square brackets can be used to access elements of the string.
Example
Get the character at position 1 (remember that the first character has the position 0):
a = "Hello, World!"
print(a[1])
Python - Strings
Looping Through a String
Since strings are arrays, we can loop through the characters in a
string, with a for loop.
Example
Loop through the letters in the word "banana":
for x in "banana":
print(x)
Slicing - Strings
Slicing
• You can return a range of characters by using the slice syntax.
• Specify the start index and the end index, separated by a colon, to return a part of
the string.
Example
• Get the characters from position 2 to position 5 (not included):
• b = "Hello, World!"
print(b[2:5])
Slice From the Start
• By leaving out the start index, the range will start at the first character:
• Example
• Get the characters from the start to position 5 (not included):
• b = "Hello, World!"
print(b[:5])
Slicing - Strings
Slice To the End
• By leaving out the end index, the range will go to the end:
• Example
• Get the characters from position 2, and all the way to the end:
• b = "Hello, World!"
print(b[2:])
Negative Indexing
Use negative indexes to start the slice from the end of the string:
Example
• Get the characters:
• From: "o" in "World!" (position -5)
• To, but not included: "d" in "World!" (position -2):
• b = "Hello, World!"
print(b[-5:-2])
Modify - Strings
• Python has a set of built-in methods that you can use on strings.
Upper Case
Example
• The upper() method returns the string in upper case:
a = "Hello, World!"
print(a.upper())
Lower Case
Example
The lower() method returns the string in lower case:
a = "Hello, World!"
print(a.lower())
Modify - Strings
Remove Whitespace
• Whitespace is the space before and/or after the actual text, and very often you
want to remove this space.
Example
• The strip() method removes any whitespace from the beginning or the end:
• a = " Hello, World! "
print(a.strip()) # returns "Hello, World!“
Replace String
Example
• The replace() method replaces a string with another string:
• a = "Hello, World!"
print(a.replace("H", "J"))
Modify - Strings
Split String
• The split() method returns a list where the text between the specified separator
becomes the list items.
Example
• The split() method splits the string into substrings if it finds instances of the
separator:
• a = "Hello, World!"
print(a.split(",")) # returns ['Hello', ' World!']
Modify - Strings
Split String
• The split() method returns a list where the text between the specified separator
becomes the list items.
Example
• The split() method splits the string into substrings if it finds instances of the
separator:
• a = "Hello, World!"
print(a.split(",")) # returns ['Hello', ' World!']
Concatenate - Strings
String Concatenation
• To concatenate, or combine, two strings you can use the + operator.
Example
• Merge variable a with variable b into variable c:
• a = "Hello"
b = "World"
c = a + b
print(c)
To add a space between them, add a " ":
• a = "Hello"
b = "World"
c = a + " " + b
print(c)
Format - Strings
we can combine strings and numbers by using the format() method!
• The format() method takes the passed arguments, formats them, and places them
in the string where the placeholders {} are:
Example
• Use the format() method to insert numbers into strings:
age = 36
txt = "My name is John, and I am {}"
print(txt.format(age))
• The format() method takes unlimited number of arguments, and are placed into
the respective placeholders:
• Example
• quantity = 3
itemno = 567
price = 49.95
myorder = "I want {} pieces of item {} for {} dollars."
print(myorder.format(quantity, itemno, price))
Format - Strings
• You can use index numbers {0} to be sure the arguments are placed in the
correct placeholders:
Example
• quantity = 3
itemno = 567
price = 49.95
myorder = "I want to pay {2} dollars for {0} pieces of item {1}."
print(myorder.format(quantity, itemno, price))
Escape Character
To insert characters that are illegal in a string, use an escape character.
An escape character is a backslash  followed by the character you want to insert.
An example of an illegal character is a double quote inside a string that is surrounded
by double quotes:
Example
• You will get an error if you use double quotes inside a string that is surrounded by
double quotes:
• txt = "We are the so-called "Vikings" from the north."
To fix this problem, use the escape character ":
Example
• The escape character allows you to use double quotes when you normally would
not be allowed:
• txt = "We are the so-called "Vikings" from the north."
Python Booleans
Booleans represent one of two values: True or False.
• Boolean Values
• In programming you often need to know if an expression is True or False.
• You can evaluate any expression in Python, and get one of two
answers, True or False.
• When you compare two values, the expression is evaluated and Python returns
the Boolean answer:
Example
print(10 > 9)
print(10 == 9)
print(10 < 9)
Python Booleans
• When you run a condition in an if statement, Python returns True or False:
Example
Print a message based on whether the condition is True or False:
a = 200
b = 33
if b > a:
print("b is greater than a")
else:
print("b is not greater than a")
Python Booleans
Evaluate Values and Variables
The bool() function allows you to evaluate any value, and give you True or False in
return,
Example
• Evaluate a string and a number:
• print(bool("Hello"))
print(bool(15))
Example
• Evaluate two variables:
• x = "Hello"
y = 15
print(bool(x))
print(bool(y))
Python Booleans
• Most Values are True
• Almost any value is evaluated to True if it has some sort of content.
• Any string is True, except empty strings.
• Any number is True, except 0.
• Any list, tuple, set, and dictionary are True, except empty ones.
• Example
• The following will return True:
• bool("abc")
bool(123)
bool(["apple", "cherry", "banana"])
Python Booleans
• You can execute code based on the Boolean answer of a function:
Example
• Print "YES!" if the function returns True, otherwise print "NO!":
def myFunction() :
return True
if myFunction():
print("YES!")
else:
print("NO!")
Python also has many built-in functions that return a boolean value, like
the isinstance() function, which can be used to determine if an object is of a certain
data type:
Example
• Check if an object is an integer or not:
• x = 200
print(isinstance(x, int))
Python Operators
Python Arithmetic Operators
Arithmetic operators are used with numeric values to perform common mathematical
operations:
Operator Name Example
+ Addition x + y
- Subtraction x - y
* Multiplication x * y
/ Division x / y
% Modulus x % y
** Exponentiation x ** y
// Floor division x // y
Python Assignment Operators
Assignment operators are used to assign values to variables:
Operator Example Same As
= x = 5 x = 5
+= x += 3 x = x + 3
-= x -= 3 x = x - 3
*= x *= 3 x = x * 3
/= x /= 3 x = x / 3
%= x %= 3 x = x % 3
//= x //= 3 x = x // 3
**= x **= 3 x = x ** 3
&= x &= 3 x = x & 3
|= x |= 3 x = x | 3
^= x ^= 3 x = x ^ 3
Comparison Operators
• Comparison operators are used to compare two values:
Operator Name Example
== Equal x == y
!= Not equal x != y
> Greater than x > y
< Less than x < y
>= Greater than
or equal to
x >= y
<= Less than or
equal to
x <= y
Logical Operators
• Logical operators are used to combine conditional statements:
Operator Description Example
and Returns True if both statements are true x < 5 and x < 10
or Returns True if one of the statements is true x < 5 or x < 4
not Reverse the result, returns False if the result is true not(x < 5 and x < 10)
Identity Operators
• Identity operators are used to compare the objects, not if they are equal, but if
they are actually the same object, with the same memory location:
Operator Description Example
is Returns True if both variables are the
same object
x is y
is not Returns True if both variables are not
the same object
x is not y
Python Lists
mylist = ["apple", "banana", "cherry"]
List
• Lists are used to store multiple items in a single variable.
• Lists are one of 4 built-in data types in Python used to store collections of data, the
other 3 are Tuple, Set, and Dictionary, all with different qualities and usage.
• Lists are created using square brackets:
Example
Create a List:
thislist = ["apple", "banana", "cherry"]
print(thislist)
Python Lists
List Items
• List items are ordered, changeable, and allow duplicate values.
• List items are indexed, the first item has index [0], the second item has
index [1] etc.
Ordered
• When we say that lists are ordered, it means that the items have a defined order,
and that order will not change.
• If you add new items to a list, the new items will be placed at the end of the list.
Changeable
• The list is changeable, meaning that we can change, add, and remove items in a
list after it has been created.
Allow Duplicates
• Since lists are indexed, lists can have items with the same value:
Example
• Lists allow duplicate values:
• thislist = ["apple", "banana", "cherry", "apple", "cherry"]
print(thislist)
Python Lists
List Length
• To determine how many items a list has, use the len() function:
Example
Print the number of items in the list:
thislist = ["apple", "banana", "cherry"]
print(len(thislist))
List Items - Data Types
List items can be of any data type:
Example
• String, int and boolean data types:
• list1 = ["apple", "banana", "cherry"]
list2 = [1, 5, 7, 9, 3]
list3 = [True, False, False]
Python Lists
A list can contain different data types:
Example
• A list with strings, integers and boolean values:
• list1 = ["abc", 34, True, 40, "male"]
type()
• From Python's perspective, lists are defined as objects with the data type 'list':
• <class 'list'>
Example
• What is the data type of a list?
• mylist = ["apple", "banana", "cherry"]
print(type(mylist))
Python Lists
The list() Constructor
• It is also possible to use the list() constructor when creating a new list.
Example
• Using the list() constructor to make a List:
• thislist = list(("apple", "banana", "cherry")) # note the double round-brackets
print(thislist)
Python Collections (Arrays)
• There are four collection data types in the Python programming language:
• List is a collection which is ordered and changeable. Allows duplicate members.
• Tuple is a collection which is ordered and unchangeable. Allows duplicate
members.
• Set is a collection which is unordered, unchangeable*, and unindexed. No
duplicate members.
• Dictionary is a collection which is ordered** and changeable. No duplicate
members.
Access List Items
Access Items
• List items are indexed and you can access them by referring to the index number:
Example
• Print the second item of the list:
• thislist = ["apple", "banana", "cherry"]
print(thislist[1])
Note: The first item has index 0.
• Negative Indexing
• Negative indexing means start from the end
• -1 refers to the last item, -2 refers to the second last item etc.
Example
• Print the last item of the list:
• thislist = ["apple", "banana", "cherry"]
print(thislist[-1])
Access List Items
Range of Indexes
• You can specify a range of indexes by specifying where to start and where to end
the range.
• When specifying a range, the return value will be a new list with the specified
items.
Example
• Return the third, fourth, and fifth item:
• thislist = ["apple", "banana", "cherry", "orange", "kiwi", "melon", "mango"]
print(thislist[2:5])
Note: The search will start at index 2 (included) and end at index 5 (not included).
Access List Items
• By leaving out the start value, the range will start at the first item:
Example
This example returns the items from the beginning to, but NOT including, "kiwi":
thislist = ["apple", "banana", "cherry", "orange", "kiwi", "melon", "mango"]
print(thislist[:4])
By leaving out the end value, the range will go on to the end of the list:
Example
• This example returns the items from "cherry" to the end:
• thislist = ["apple", "banana", "cherry", "orange", "kiwi", "melon", "mango"]
print(thislist[2:])
Access List Items
Range of Negative Indexes
• Specify negative indexes if you want to start the search from the end of the list:
Example
• This example returns the items from "orange" (-4) to, but NOT including "mango"
(-1):
• thislist = ["apple", "banana", "cherry", "orange", "kiwi", "melon", "mango"]
print(thislist[-4:-1])
Check if Item Exists
• To determine if a specified item is present in a list use the in keyword:
• Example
• Check if "apple" is present in the list:
• thislist = ["apple", "banana", "cherry"]
if "apple" in thislist:
print("Yes, 'apple' is in the fruits list")
Change List Items
Change Item Value
• To change the value of a specific item, refer to the index number:
Example
• Change the second item:
• thislist = ["apple", "banana", "cherry"]
thislist[1] = "blackcurrant"
print(thislist)
• Change a Range of Item Values
• To change the value of items within a specific range, define a list with the new
values, and refer to the range of index numbers where you want to insert the new
values:
Example
• Change the values "banana" and "cherry" with the values "blackcurrant" and
"watermelon":
• thislist = ["apple", "banana", "cherry", "orange", "kiwi", "mango"]
thislist[1:3] = ["blackcurrant", "watermelon"]
print(thislist)
Change List Items
• Change Item Value
• To change the value of a specific item, refer to the index number:
Example
Change the second item:
thislist = ["apple", "banana", "cherry"]
thislist[1] = "blackcurrant"
print(thislist)
Append List Items
• To add an item to the end of the list, use
the append() method:
• To insert a list item at a specified index, use
the insert() method.
Remove List Items
• The remove() method removes the specified item.
• The pop() method removes the specified index.
• If you do not specify the index, the pop() method removes the last item.
• The del keyword also removes the specified index:
• The del keyword can also delete the list completely.
• The clear() method empties the list.
• The list still remains, but it has no content.
Tuples
Tuple
• Tuples are used to store multiple items in a single variable.
• A tuple is a collection which is ordered and unchangeable.
• Tuples are written with round brackets.
Tuple Items
• Tuple items are ordered, unchangeable, and allow duplicate values.
• Tuple items are indexed, the first item has index [0], the second item has
index [1] etc.
• Ordered
• When we say that tuples are ordered, it means that the items have a defined
order, and that order will not change.
• Unchangeable
• Tuples are unchangeable, meaning that we cannot change, add or remove items
after the tuple has been created.
• Allow Duplicates
• Since tuples are indexed, they can have items with the same value:
Tuples
Access Tuple Items
• You can access tuple items by referring to the index number, inside square
brackets:
• Negative indexing means start from the end.
• -1 refers to the last item, -2 refers to the second last item etc.
Range of Indexes
• You can specify a range of indexes by specifying where to start and where to end
the range.
• When specifying a range, the return value will be a new tuple with the specified
items.
Range of Negative Indexes
• Specify negative indexes if you want to start the search from the end of the tuple:
Remove List Items
• The remove() method removes the specified item.
• The pop() method removes the specified index.
• If you do not specify the index, the pop() method removes the last item.
• The del keyword also removes the specified index:
• The del keyword can also delete the list completely.
• The clear() method empties the list.
• The list still remains, but it has no content.
Python - Set
• Sets are used to store multiple items in a single variable.
• Set is one of 4 built-in data types in Python used to store collections of data, the
other 3 are List, Tuple, and Dictionary, all with different qualities and usage.
• A set is a collection which is unordered, unchangeable*, and unindexed.
• Note: Sets are unordered, so you cannot be sure in which order the items will
appear.
• Set Items
• Set items are unordered, unchangeable, and do not allow duplicate values.
• Unordered
• Unordered means that the items in a set do not have a defined order.
• Set items can appear in a different order every time you use them, and cannot be
referred to by index or key.
• Unchangeable
• Set items are unchangeable, meaning that we cannot change the items after the
set has been created.
• Once a set is created, you cannot change its items, but you can remove items and
add new items.
Python - Set
• The set() Constructor
• It is also possible to use the set() constructor to make a set.
Example
Access Items
• You cannot access items in a set by referring to an index or a key.
• But you can loop through the set items using a for loop, or ask if a specified value
is present in a set, by using the in keyword.
Change Items
• Once a set is created, you cannot change its items, but you can add new items.
Add Items
• To add one item to a set use the add() method.
Add Sets
• To add items from another set into the current set, use the update() method.
Python - Set
Add Any Iterable
• The object in the update() method does not have to be a set,
it can be any iterable object (tuples, lists, dictionaries etc.)
Remove Item
• To remove an item in a set, use the remove(), or
the discard() method.
• The clear() method empties the set:
• The del keyword will delete the set completely:
• You can loop through the set items by using a for loop:
Python – Join Sets
Join Two Sets
• There are several ways to join two or more sets in Python.
• You can use the union() method that returns a new set containing all items from
both sets, or the update() method that inserts all the items from one set into
another:
Keep ONLY the Duplicates
• The intersection_update() method will keep only the items that are present in
both sets.
The intersection() method will return a new set, that only contains the items that are
present in both sets.
Python – Dictionary
• Dictionaries are used to store data values in key:value pairs.
• A dictionary is a collection which is ordered*, changeable and do not allow
duplicates.
• As of Python version 3.7, dictionaries are ordered. In Python 3.6 and earlier,
dictionaries are unordered.
• Dictionaries are written with curly brackets, and have keys and values:
• Dictionaries are used to store data values in key:value pairs.
• A dictionary is a collection which is ordered*, changeable and do not allow
duplicates.
• As of Python version 3.7, dictionaries are ordered. In Python 3.6 and earlier,
dictionaries are unordered.
• Dictionaries are written with curly brackets, and have keys and values:
Python – Dictionary
Dictionary Items
• Dictionary items are ordered, changeable, and does not allow duplicates.
• Dictionary items are presented in key:value pairs, and can be referred to by using
the key name.
Ordered or Unordered?
• As of Python version 3.7, dictionaries are ordered. In Python 3.6 and earlier,
dictionaries are unordered.
• When we say that dictionaries are ordered, it means that the items have a defined
order, and that order will not change.
• Unordered means that the items does not have a defined order, you cannot refer
to an item by using an index.
• Changeable
• Dictionaries are changeable, meaning that we can change, add or remove items
after the dictionary has been created.
Python – Dictionary
Accessing Items
• You can access the items of a dictionary by referring to its key name, inside square
brackets:
Get the value of the "model" key:
thisdict = {
"brand": "Ford",
"model": "Mustang",
"year": 1964
}
x = thisdict["model"]
Get Keys
• The keys() method will return a list of all the keys in the dictionary.
Get Values
• The values() method will return a list of all the values in the dictionary.
Python – Dictionary
The list of the values is a view of the dictionary, meaning that any changes done to the
dictionary will be reflected in the values list.
Get Items
• The items() method will return each item in a dictionary, as tuples in a list.
Change Values
• You can change the value of a specific item by referring to its key name:
Update Dictionary
• The update() method will update the dictionary with the items from the given
argument.
• The argument must be a dictionary, or an iterable object with key:value pairs.
Adding Items
• Adding an item to the dictionary is done by using a new index key and assigning a
value to it:
Python – Dictionary
Update Dictionary
• The update() method will update the dictionary with the items from a given
argument. If the item does not exist, the item will be added.
• The argument must be a dictionary, or an iterable object with key:value pairs.
Removing Items
• There are several methods to remove items from a dictionary:
Example
• The pop() method removes the item with the specified key name:
• The popitem() method removes the last inserted item (in versions before 3.7, a
random item is removed instead):
• The del keyword removes the item with the specified key name:
Python – Dictionary
Loop Through a Dictionary
• You can loop through a dictionary by using a for loop.
• When looping through a dictionary, the return value are
the keys of the dictionary, but there are methods to return
the values as well.
• You can also use the values() method to return values of a
dictionary:
• You can use the keys() method to return the keys of a
dictionary:
• Loop through both keys and values, by using
the items() method:
If Else statements
• Decision making is required when we want to execute a code only if a
certain condition is satisfied.
• The if…elif…else statement is used in Python for decision making.
Python if Statement Syntax
• if test expression: statement(s)
• Here, the program evaluates the test expression and will execute
statement(s) only if the test expression is True.
• If the test expression is False, the statement(s) is not executed.
• In Python, the body of the if statement is indicated by the indentation. The
body starts with an indentation and the first unindented line marks the
end.
If Else statements
• In the above example, num > 0 is the test expression.
• The body of if is executed only if this evaluates to True.
• When the variable num is equal to 3, test expression is true and
statements inside the body of if are executed.
• If the variable num is equal to -1, test expression is false and statements
inside the body of if are skipped.
• The print() statement falls outside of the if block (unindented). Hence, it is
executed regardless of the test expression.
If Else statements
Python if...else Statement
Syntax of if...else
if test expression:
Body of if
else:
Body of else
• The if..else statement evaluates test expression and will execute the body
of if only when the test condition is True.
• If the condition is False, the body of else is executed. Indentation is used
to separate the blocks.
If Else statements
Python if...elif...else Statement
Syntax of if...elif...else
if test expression:
Body of if
elif test expression:
Body of elif
else:
Body of else
If Else statements
• The elif is short for else if. It allows us to check for
multiple expressions.
• If the condition for if is False, it checks the condition
of the next elif block and so on.
• If all the conditions are False, the body of else is
executed.
• Only one block among the several if...elif...else blocks
is executed according to the condition.
• The if block can have only one else block. But it can
have multiple elif blocks.
If Else statements
• Python Nested if statements
• We can have a if...elif...else statement inside
another if...elif...else statement. This is called
nesting in computer programming.
• Any number of these statements can be
nested inside one another. Indentation is the
only way to figure out the level of nesting.
They can get confusing, so they must be
avoided unless necessary.
Python - Functions
• How to Define a Function with the def Keyword
• To define a function in Python, you type the def keyword first,
then the function name and parentheses.
• To tell Python the function is a block of code, you specify a
colon in front of the function name. What follows is what you
want the function to do.
• The basic syntax of a function looks like this:
def function_name():
# What you want the function to do
Python - Functions
• To call a function, you write out the function name followed by a paranthesis.
• The syntax for calling a function looks like this:
• function_name()
def learn_to_code():
print("You can learn to code ")
learn_to_code()
# Output: You can learn to code
Python - Functions
• To call a function, you write out the function name followed by a paranthesis.
• The syntax for calling a function looks like this:
• function_name()
def learn_to_code():
print("You can learn to code ")
learn_to_code()
# Output: You can learn to code
Python - Functions
Arguments
• Information can be passed into functions as arguments.
• Arguments are specified after the function name, inside the parentheses.
You can add as many arguments as you want, just separate them with a
comma.
Number of Arguments
• By default, a function must be called with the correct number of
arguments. Meaning that if your function expects 2 arguments, you have
to call the function with 2 arguments, not more, and not less.
Python - Functions
• Arbitrary Arguments, *args
• If you do not know how many arguments that will be passed into your
function, add a * before the parameter name in the function definition.
• This way the function will receive a tuple of arguments, and can access the
items accordingly:
• Example
• If the number of arguments is unknown, add a * before the parameter
name:
• def my_function(*kids):
print("The youngest child is " + kids[2])
my_function("Emil", "Tobias", "Linus")
Python - Functions
• Default Parameter Value
• The following example shows how to use a default parameter value.
• If we call the function without argument, it uses the default value:
def my_function(country = "Norway"):
print("I am from " + country)
my_function("Sweden")
my_function("India")
my_function()
my_function("Brazil")
Python - Functions
• Passing a List as an Argument
• You can send any data types of argument to a function (string, number, list,
dictionary etc.), and it will be treated as the same data type inside the function.
• E.g. if you send a List as an argument, it will still be a List when it reaches the
function:
• Example
• def my_function(food):
for x in food:
print(x)
fruits = ["apple", "banana", "cherry"]
my_function(fruits)
Python - Functions
Return Values
• To let a function return a value, use the return statement:
Example
def my_function(x):
return 5 * x
print(my_function(3))
print(my_function(5))
print(my_function(9))
Python - Lambda Functions
What are lambda functions in Python?
• In Python, an anonymous function is a function that is defined without a
name.
• While normal functions are defined using the def keyword in Python,
anonymous functions are defined using the lambda keyword.
• Hence, anonymous functions are also called lambda functions.
A lambda function in python has the following syntax.
Syntax of Lambda Function in python
• lambda arguments: expression
• Lambda functions can have any number of arguments but only one
expression. The expression is evaluated and returned. Lambda functions
can be used wherever function objects are required.
Python - Lambda Functions
What are lambda functions in Python?
• In Python, an anonymous function is a function that is defined without a
name.
• While normal functions are defined using the def keyword in Python,
anonymous functions are defined using the lambda keyword.
• Hence, anonymous functions are also called lambda functions.
A lambda function in python has the following syntax.
Syntax of Lambda Function in python
• lambda arguments: expression
• Lambda functions can have any number of arguments but only one
expression. The expression is evaluated and returned. Lambda functions
can be used wherever function objects are required.
Python - Lambda Functions
• Use of Lambda Function in python
• We use lambda functions when we require a
nameless function for a short period of time.
• In Python, we generally use it as an argument
to a higher-order function (a function that
takes in other functions as arguments).
Lambda functions are used along with built-in
functions like filter(), map() etc.
Python - Lambda Functions
Python Loops
• What is for loop in Python?
• The for loop in Python is used to iterate over a sequence (list, tuple, string)
or other iterable objects. Iterating over a sequence is called traversal.
Syntax of for Loop
for val in sequence:
loop body
• Here, val is the variable that takes the value of the item inside the
sequence on each iteration.
• Loop continues until we reach the last item in the sequence. The body of
for loop is separated from the rest of the code using indentation.
Python Range
• The Range function in Python
• The range() function provides a sequence of integers based
upon the function's arguments.
• range(stop)
• range(start, stop[, step])
• The start argument is the first value in the range.
• If range() is called with only one argument, then Python
assumes start = 0.
• The stop argument is the upper bound of the range. It is
important to realize that this upper value is not included in
the range.
Python Range
In the example below, we have a range starting at the
default value of 0 and including integers less than 5.
# Example with one argument
for i in range(5):
print(i, end=", ") # prints: 0, 1, 2, 3, 4,
Python For loop with else
• A for loop can have an optional else block as
well. The else part is executed if the items in
the sequence used in for loop exhausts.
• The break keyword can be used to stop a for
loop. In such cases, the else part is ignored.
• Hence, a for loop's else part runs if no break
occurs.
Python For loop with else
• A for loop can have an optional else block as
well. The else part is executed if the items in
the sequence used in for loop exhausts.
• The break keyword can be used to stop a for
loop. In such cases, the else part is ignored.
• Hence, a for loop's else part runs if no break
occurs.
Python While loop
• The while loop in Python is used to iterate over a block of code as long as the test
expression (condition) is true.
• We generally use this loop when we don't know the number of times to iterate
beforehand.
• Syntax of while Loop in Python
while test_expression:
Body of while
• In the while loop, test expression is checked first. The body of the loop is entered
only if the test_expression evaluates to True. After one iteration, the test
expression is checked again. This process continues until
the test_expression evaluates to False.
• In Python, the body of the while loop is determined through indentation.
• The body starts with indentation and the first unindented line marks the end.
• Python interprets any non-zero value as True. None and 0 are interpreted as False.
Python Datetime
Python Dates
• A date in Python is not a data type of its own, but we can import a module
named datetime to work with dates as date objects.
Import the datetime module and display the current date:
• import datetime
x = datetime.datetime.now()
print(x)
Date Output
• When we execute the code from the example above the result will be:
• 2022-09-26 11:31:03.664255The date contains year, month, day, hour, minute,
second, and microsecond.
• The datetime module has many methods to return information about the date
object.
Python Datetime
Creating Date Objects
• To create a date, we can use the datetime() class (constructor) of
the datetime module.
• The datetime() class requires three parameters to create a date: year, month, day.
The strftime() Method
• The datetime object has a method for formatting date objects into readable
strings.
• The method is called strftime(), and takes one parameter, format, to specify the
format of the returned string:
Python Datetime
Directive Description Example
%a Weekday, short version Wed
%A Weekday, full version Wednesday
%w Weekday as a number 0-6,
0 is Sunday
3
%d Day of month 01-31 31
%b Month name, short version Dec
%B Month name, full version December
%m Month as a number 01-12 12
Python Modules
• What are modules in Python?
• Modules refer to a file containing Python statements and definitions.
• A file containing Python code, for example: example.py, is called a module, and its
module name would be example.
• We use modules to break down large programs into small manageable and
organized files. Furthermore, modules provide reusability of code.
• We can define our most used functions in a module and import it, instead of
copying their definitions into different programs.
• Let us create a module. Type the following and save it as example.py.
• # Python Module example
def add(a, b):
"""This program adds two numbers and return the result""“
result = a + b
return result
Python Modules
• We can import the definitions inside a module to another module or the
interactive interpreter in Python.
• We use the import keyword to do this. To import our previously defined
module example, we type the following in the Python prompt.
• >>> import example
• This does not import the names of the functions defined in example directly in the
current symbol table. It only imports the module name example there.
• Using the module name we can access the function using the dot . operator. For
example:
• >>> example.add(4,5.5)
• 9.5
• Python has tons of standard modules. You can check out the full list of Python
standard modules and their use cases. These files are in the Lib directory inside
the location where you installed Python.
• Standard modules can be imported the same way as we import our user-defined
modules.
Python Modules
Python import statement
• We can import a module using the import statement and access the definitions
inside it using the dot operator as described above. Here is an example.
# import statement example
# to import standard module math
import math print("The value of pi is", math.pi)
Import with renaming
• We can import a module by renaming it as follows:
# import module by renaming it
import math as m
print("The value of pi is", m.pi)
• We have renamed the math module as m. This can save us typing time in some
cases.
Note that the name math is not recognized in our scope. Hence, math.pi is invalid,
and m.pi is the correct implementation.
Python Modules
• Python from...import statement
• We can import specific names from a module without importing the module as a
whole. Here is an example.
• # import only pi from math module
from math import pi
print("The value of pi is", pi)
• Here, we imported only the pi attribute from the math module.
• In such cases, we don't use the dot operator. We can also import multiple
attributes as follows:
• >>> from math import pi, e
• >>> pi 3.141592653589793
• >>> e 2.718281828459045
Python Modules
Import all names
• We can import all names(definitions) from a module using the following construct:
# import all names from the standard module math
from math import *
print("The value of pi is", pi)
Here, we have imported all the definitions from the math module. This includes all
names visible in our scope except those beginning with an underscore(private
definitions).
Importing everything with the asterisk (*) symbol is not a good programming practice.
This can lead to duplicate definitions for an identifier. It also hampers the readability
of our code.
Python Modules
Python Module Search Path
• While importing a module, Python looks at several places. Interpreter first looks
for a built-in module. Then(if built-in module not found), Python looks into a list of
directories defined in sys.path. The search is in this order.
• The current directory.
• PYTHONPATH (an environment variable with a list of directories).
• The installation-dependent default directory.
• Reloading a module
• The Python interpreter imports a module only once during a session. This makes
things more efficient. Here is an example to show how this works.
• Suppose we have the following code in a module named my_module.
# This module shows the effect of multiple imports and reload
print("This code got executed")
Python Modules
• Now we see the effect of multiple imports.
>>> import my_module
This code got executed
>>> import my_module
>>> import my_module
We can see that our code got executed only once. This goes to say that our module
was imported only once.
Now if our module changed during the course of the program, we would have to
reload it. One way to do this is to restart the interpreter. But this does not help much.
Python provides a more efficient way of doing this. We can use the reload() function
inside the imp module to reload a module. We can do it in the following ways:
• >>> import importlib
• >>> import my_module
• This code got executed
• >>> import my_module
• >>> importlib.reload(my_module)
• This code got executed <module 'my_module' from '.my_module.py'>
Python Modules
The dir() built-in function
• We can use the dir() function to find out names that are defined inside a module.
• For example, we have defined a function add() in the module example that we had
in the beginning.
• We can use dir in example module in the following way:

Weitere ähnliche Inhalte

Was ist angesagt?

python ppt | Python Course In Ghaziabad | Scode Network Institute
python ppt | Python Course In Ghaziabad | Scode Network Institutepython ppt | Python Course In Ghaziabad | Scode Network Institute
python ppt | Python Course In Ghaziabad | Scode Network InstituteScode Network Institute
 
Python intro
Python introPython intro
Python introrik0
 
Intro to Python Programming Language
Intro to Python Programming LanguageIntro to Python Programming Language
Intro to Python Programming LanguageDipankar Achinta
 
Introduction to python
Introduction to pythonIntroduction to python
Introduction to pythonManishJha237
 
Fundamentals of python
Fundamentals of pythonFundamentals of python
Fundamentals of pythonBijuAugustian
 
Phython Programming Language
Phython Programming LanguagePhython Programming Language
Phython Programming LanguageR.h. Himel
 
Python programming | Fundamentals of Python programming
Python programming | Fundamentals of Python programming Python programming | Fundamentals of Python programming
Python programming | Fundamentals of Python programming KrishnaMildain
 
Python Projects For Beginners | Python Projects Examples | Python Tutorial | ...
Python Projects For Beginners | Python Projects Examples | Python Tutorial | ...Python Projects For Beginners | Python Projects Examples | Python Tutorial | ...
Python Projects For Beginners | Python Projects Examples | Python Tutorial | ...Edureka!
 
Introduction To Python
Introduction To PythonIntroduction To Python
Introduction To PythonVanessa Rene
 
Python Course | Python Programming | Python Tutorial | Python Training | Edureka
Python Course | Python Programming | Python Tutorial | Python Training | EdurekaPython Course | Python Programming | Python Tutorial | Python Training | Edureka
Python Course | Python Programming | Python Tutorial | Python Training | EdurekaEdureka!
 
Overview of python 2019
Overview of python 2019Overview of python 2019
Overview of python 2019Samir Mohanty
 
Introduction to Python programming Language
Introduction to Python programming LanguageIntroduction to Python programming Language
Introduction to Python programming LanguageMansiSuthar3
 
Python-00 | Introduction and installing
Python-00 | Introduction and installingPython-00 | Introduction and installing
Python-00 | Introduction and installingMohd Sajjad
 
Introduction To Python | Edureka
Introduction To Python | EdurekaIntroduction To Python | Edureka
Introduction To Python | EdurekaEdureka!
 

Was ist angesagt? (20)

python ppt | Python Course In Ghaziabad | Scode Network Institute
python ppt | Python Course In Ghaziabad | Scode Network Institutepython ppt | Python Course In Ghaziabad | Scode Network Institute
python ppt | Python Course In Ghaziabad | Scode Network Institute
 
Python programming
Python  programmingPython  programming
Python programming
 
Introduction to python
Introduction to pythonIntroduction to python
Introduction to python
 
Python intro
Python introPython intro
Python intro
 
Intro to Python Programming Language
Intro to Python Programming LanguageIntro to Python Programming Language
Intro to Python Programming Language
 
Introduction to python
Introduction to pythonIntroduction to python
Introduction to python
 
Fundamentals of python
Fundamentals of pythonFundamentals of python
Fundamentals of python
 
Phython Programming Language
Phython Programming LanguagePhython Programming Language
Phython Programming Language
 
Python programming | Fundamentals of Python programming
Python programming | Fundamentals of Python programming Python programming | Fundamentals of Python programming
Python programming | Fundamentals of Python programming
 
Python Projects For Beginners | Python Projects Examples | Python Tutorial | ...
Python Projects For Beginners | Python Projects Examples | Python Tutorial | ...Python Projects For Beginners | Python Projects Examples | Python Tutorial | ...
Python Projects For Beginners | Python Projects Examples | Python Tutorial | ...
 
Introduction To Python
Introduction To PythonIntroduction To Python
Introduction To Python
 
Python Course | Python Programming | Python Tutorial | Python Training | Edureka
Python Course | Python Programming | Python Tutorial | Python Training | EdurekaPython Course | Python Programming | Python Tutorial | Python Training | Edureka
Python Course | Python Programming | Python Tutorial | Python Training | Edureka
 
Overview of python 2019
Overview of python 2019Overview of python 2019
Overview of python 2019
 
Python Tutorial Part 1
Python Tutorial Part 1Python Tutorial Part 1
Python Tutorial Part 1
 
Beginning Python Programming
Beginning Python ProgrammingBeginning Python Programming
Beginning Python Programming
 
PyCharm demo
PyCharm demoPyCharm demo
PyCharm demo
 
Introduction to Python programming Language
Introduction to Python programming LanguageIntroduction to Python programming Language
Introduction to Python programming Language
 
Intro to Python
Intro to PythonIntro to Python
Intro to Python
 
Python-00 | Introduction and installing
Python-00 | Introduction and installingPython-00 | Introduction and installing
Python-00 | Introduction and installing
 
Introduction To Python | Edureka
Introduction To Python | EdurekaIntroduction To Python | Edureka
Introduction To Python | Edureka
 

Ähnlich wie python-ppt.ppt

Introduction to Python Unit -1 Part .pdf
Introduction to Python Unit -1 Part .pdfIntroduction to Python Unit -1 Part .pdf
Introduction to Python Unit -1 Part .pdfVaibhavKumarSinghkal
 
PYTHON FEATURES.pptx
PYTHON FEATURES.pptxPYTHON FEATURES.pptx
PYTHON FEATURES.pptxMaheShiva
 
Python final presentation kirti ppt1
Python final presentation kirti ppt1Python final presentation kirti ppt1
Python final presentation kirti ppt1Kirti Verma
 
python classes in thane
python classes in thanepython classes in thane
python classes in thanefaizrashid1995
 
python presntation 2.pptx
python presntation 2.pptxpython presntation 2.pptx
python presntation 2.pptxArpittripathi45
 
Python_Introduction_Good_PPT.pptx
Python_Introduction_Good_PPT.pptxPython_Introduction_Good_PPT.pptx
Python_Introduction_Good_PPT.pptxlemonchoos
 
Session-1_Introduction to Python.pptx
Session-1_Introduction to Python.pptxSession-1_Introduction to Python.pptx
Session-1_Introduction to Python.pptxWajidAliHashmi2
 
Python Book/Notes For Python Book/Notes For S.Y.B.Sc. I.T.
Python Book/Notes For Python Book/Notes For S.Y.B.Sc. I.T.Python Book/Notes For Python Book/Notes For S.Y.B.Sc. I.T.
Python Book/Notes For Python Book/Notes For S.Y.B.Sc. I.T.Niraj Bharambe
 
Python programming language introduction unit
Python programming language introduction unitPython programming language introduction unit
Python programming language introduction unitmichaelaaron25322
 
WEB PROGRAMMING UNIT VIII BY BHAVSINGH MALOTH
WEB PROGRAMMING UNIT VIII BY BHAVSINGH MALOTHWEB PROGRAMMING UNIT VIII BY BHAVSINGH MALOTH
WEB PROGRAMMING UNIT VIII BY BHAVSINGH MALOTHBhavsingh Maloth
 
Python for students step by step guidance
Python for students step by step guidancePython for students step by step guidance
Python for students step by step guidanceMantoshKumar79
 
python intro and installation.pptx
python intro and installation.pptxpython intro and installation.pptx
python intro and installation.pptxadityakumawat625
 
Python (3).pdf
Python (3).pdfPython (3).pdf
Python (3).pdfsamiwaris2
 
a9855c3532e13484ee6a39ba30218896d7c0d863-1676987272842.pptx
a9855c3532e13484ee6a39ba30218896d7c0d863-1676987272842.pptxa9855c3532e13484ee6a39ba30218896d7c0d863-1676987272842.pptx
a9855c3532e13484ee6a39ba30218896d7c0d863-1676987272842.pptxcigogag569
 
Introduction to python
Introduction to pythonIntroduction to python
Introduction to pythonRanjith kumar
 

Ähnlich wie python-ppt.ppt (20)

Introduction to Python Unit -1 Part .pdf
Introduction to Python Unit -1 Part .pdfIntroduction to Python Unit -1 Part .pdf
Introduction to Python Unit -1 Part .pdf
 
PYTHON FEATURES.pptx
PYTHON FEATURES.pptxPYTHON FEATURES.pptx
PYTHON FEATURES.pptx
 
Python final presentation kirti ppt1
Python final presentation kirti ppt1Python final presentation kirti ppt1
Python final presentation kirti ppt1
 
python classes in thane
python classes in thanepython classes in thane
python classes in thane
 
python presntation 2.pptx
python presntation 2.pptxpython presntation 2.pptx
python presntation 2.pptx
 
Python_Introduction_Good_PPT.pptx
Python_Introduction_Good_PPT.pptxPython_Introduction_Good_PPT.pptx
Python_Introduction_Good_PPT.pptx
 
Session-1_Introduction to Python.pptx
Session-1_Introduction to Python.pptxSession-1_Introduction to Python.pptx
Session-1_Introduction to Python.pptx
 
python into.pptx
python into.pptxpython into.pptx
python into.pptx
 
Python Book/Notes For Python Book/Notes For S.Y.B.Sc. I.T.
Python Book/Notes For Python Book/Notes For S.Y.B.Sc. I.T.Python Book/Notes For Python Book/Notes For S.Y.B.Sc. I.T.
Python Book/Notes For Python Book/Notes For S.Y.B.Sc. I.T.
 
Python programming language introduction unit
Python programming language introduction unitPython programming language introduction unit
Python programming language introduction unit
 
Python fundamentals
Python fundamentalsPython fundamentals
Python fundamentals
 
WEB PROGRAMMING UNIT VIII BY BHAVSINGH MALOTH
WEB PROGRAMMING UNIT VIII BY BHAVSINGH MALOTHWEB PROGRAMMING UNIT VIII BY BHAVSINGH MALOTH
WEB PROGRAMMING UNIT VIII BY BHAVSINGH MALOTH
 
Python basics
Python basicsPython basics
Python basics
 
Python for students step by step guidance
Python for students step by step guidancePython for students step by step guidance
Python for students step by step guidance
 
Welcome_to_Python.pptx
Welcome_to_Python.pptxWelcome_to_Python.pptx
Welcome_to_Python.pptx
 
1-ppt-python.ppt
1-ppt-python.ppt1-ppt-python.ppt
1-ppt-python.ppt
 
python intro and installation.pptx
python intro and installation.pptxpython intro and installation.pptx
python intro and installation.pptx
 
Python (3).pdf
Python (3).pdfPython (3).pdf
Python (3).pdf
 
a9855c3532e13484ee6a39ba30218896d7c0d863-1676987272842.pptx
a9855c3532e13484ee6a39ba30218896d7c0d863-1676987272842.pptxa9855c3532e13484ee6a39ba30218896d7c0d863-1676987272842.pptx
a9855c3532e13484ee6a39ba30218896d7c0d863-1676987272842.pptx
 
Introduction to python
Introduction to pythonIntroduction to python
Introduction to python
 

Kürzlich hochgeladen

Scaling API-first – The story of a global engineering organization
Scaling API-first – The story of a global engineering organizationScaling API-first – The story of a global engineering organization
Scaling API-first – The story of a global engineering organizationRadu Cotescu
 
AWS Community Day CPH - Three problems of Terraform
AWS Community Day CPH - Three problems of TerraformAWS Community Day CPH - Three problems of Terraform
AWS Community Day CPH - Three problems of TerraformAndrey Devyatkin
 
Tata AIG General Insurance Company - Insurer Innovation Award 2024
Tata AIG General Insurance Company - Insurer Innovation Award 2024Tata AIG General Insurance Company - Insurer Innovation Award 2024
Tata AIG General Insurance Company - Insurer Innovation Award 2024The Digital Insurer
 
TrustArc Webinar - Stay Ahead of US State Data Privacy Law Developments
TrustArc Webinar - Stay Ahead of US State Data Privacy Law DevelopmentsTrustArc Webinar - Stay Ahead of US State Data Privacy Law Developments
TrustArc Webinar - Stay Ahead of US State Data Privacy Law DevelopmentsTrustArc
 
GenCyber Cyber Security Day Presentation
GenCyber Cyber Security Day PresentationGenCyber Cyber Security Day Presentation
GenCyber Cyber Security Day PresentationMichael W. Hawkins
 
Handwritten Text Recognition for manuscripts and early printed texts
Handwritten Text Recognition for manuscripts and early printed textsHandwritten Text Recognition for manuscripts and early printed texts
Handwritten Text Recognition for manuscripts and early printed textsMaria Levchenko
 
ProductAnonymous-April2024-WinProductDiscovery-MelissaKlemke
ProductAnonymous-April2024-WinProductDiscovery-MelissaKlemkeProductAnonymous-April2024-WinProductDiscovery-MelissaKlemke
ProductAnonymous-April2024-WinProductDiscovery-MelissaKlemkeProduct Anonymous
 
The 7 Things I Know About Cyber Security After 25 Years | April 2024
The 7 Things I Know About Cyber Security After 25 Years | April 2024The 7 Things I Know About Cyber Security After 25 Years | April 2024
The 7 Things I Know About Cyber Security After 25 Years | April 2024Rafal Los
 
Understanding Discord NSFW Servers A Guide for Responsible Users.pdf
Understanding Discord NSFW Servers A Guide for Responsible Users.pdfUnderstanding Discord NSFW Servers A Guide for Responsible Users.pdf
Understanding Discord NSFW Servers A Guide for Responsible Users.pdfUK Journal
 
Histor y of HAM Radio presentation slide
Histor y of HAM Radio presentation slideHistor y of HAM Radio presentation slide
Histor y of HAM Radio presentation slidevu2urc
 
Axa Assurance Maroc - Insurer Innovation Award 2024
Axa Assurance Maroc - Insurer Innovation Award 2024Axa Assurance Maroc - Insurer Innovation Award 2024
Axa Assurance Maroc - Insurer Innovation Award 2024The Digital Insurer
 
04-2024-HHUG-Sales-and-Marketing-Alignment.pptx
04-2024-HHUG-Sales-and-Marketing-Alignment.pptx04-2024-HHUG-Sales-and-Marketing-Alignment.pptx
04-2024-HHUG-Sales-and-Marketing-Alignment.pptxHampshireHUG
 
Developing An App To Navigate The Roads of Brazil
Developing An App To Navigate The Roads of BrazilDeveloping An App To Navigate The Roads of Brazil
Developing An App To Navigate The Roads of BrazilV3cube
 
Apidays New York 2024 - Scaling API-first by Ian Reasor and Radu Cotescu, Adobe
Apidays New York 2024 - Scaling API-first by Ian Reasor and Radu Cotescu, AdobeApidays New York 2024 - Scaling API-first by Ian Reasor and Radu Cotescu, Adobe
Apidays New York 2024 - Scaling API-first by Ian Reasor and Radu Cotescu, Adobeapidays
 
Bajaj Allianz Life Insurance Company - Insurer Innovation Award 2024
Bajaj Allianz Life Insurance Company - Insurer Innovation Award 2024Bajaj Allianz Life Insurance Company - Insurer Innovation Award 2024
Bajaj Allianz Life Insurance Company - Insurer Innovation Award 2024The Digital Insurer
 
Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...
Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...
Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...apidays
 
Finology Group – Insurtech Innovation Award 2024
Finology Group – Insurtech Innovation Award 2024Finology Group – Insurtech Innovation Award 2024
Finology Group – Insurtech Innovation Award 2024The Digital Insurer
 
HTML Injection Attacks: Impact and Mitigation Strategies
HTML Injection Attacks: Impact and Mitigation StrategiesHTML Injection Attacks: Impact and Mitigation Strategies
HTML Injection Attacks: Impact and Mitigation StrategiesBoston Institute of Analytics
 
Strategize a Smooth Tenant-to-tenant Migration and Copilot Takeoff
Strategize a Smooth Tenant-to-tenant Migration and Copilot TakeoffStrategize a Smooth Tenant-to-tenant Migration and Copilot Takeoff
Strategize a Smooth Tenant-to-tenant Migration and Copilot Takeoffsammart93
 
Powerful Google developer tools for immediate impact! (2023-24 C)
Powerful Google developer tools for immediate impact! (2023-24 C)Powerful Google developer tools for immediate impact! (2023-24 C)
Powerful Google developer tools for immediate impact! (2023-24 C)wesley chun
 

Kürzlich hochgeladen (20)

Scaling API-first – The story of a global engineering organization
Scaling API-first – The story of a global engineering organizationScaling API-first – The story of a global engineering organization
Scaling API-first – The story of a global engineering organization
 
AWS Community Day CPH - Three problems of Terraform
AWS Community Day CPH - Three problems of TerraformAWS Community Day CPH - Three problems of Terraform
AWS Community Day CPH - Three problems of Terraform
 
Tata AIG General Insurance Company - Insurer Innovation Award 2024
Tata AIG General Insurance Company - Insurer Innovation Award 2024Tata AIG General Insurance Company - Insurer Innovation Award 2024
Tata AIG General Insurance Company - Insurer Innovation Award 2024
 
TrustArc Webinar - Stay Ahead of US State Data Privacy Law Developments
TrustArc Webinar - Stay Ahead of US State Data Privacy Law DevelopmentsTrustArc Webinar - Stay Ahead of US State Data Privacy Law Developments
TrustArc Webinar - Stay Ahead of US State Data Privacy Law Developments
 
GenCyber Cyber Security Day Presentation
GenCyber Cyber Security Day PresentationGenCyber Cyber Security Day Presentation
GenCyber Cyber Security Day Presentation
 
Handwritten Text Recognition for manuscripts and early printed texts
Handwritten Text Recognition for manuscripts and early printed textsHandwritten Text Recognition for manuscripts and early printed texts
Handwritten Text Recognition for manuscripts and early printed texts
 
ProductAnonymous-April2024-WinProductDiscovery-MelissaKlemke
ProductAnonymous-April2024-WinProductDiscovery-MelissaKlemkeProductAnonymous-April2024-WinProductDiscovery-MelissaKlemke
ProductAnonymous-April2024-WinProductDiscovery-MelissaKlemke
 
The 7 Things I Know About Cyber Security After 25 Years | April 2024
The 7 Things I Know About Cyber Security After 25 Years | April 2024The 7 Things I Know About Cyber Security After 25 Years | April 2024
The 7 Things I Know About Cyber Security After 25 Years | April 2024
 
Understanding Discord NSFW Servers A Guide for Responsible Users.pdf
Understanding Discord NSFW Servers A Guide for Responsible Users.pdfUnderstanding Discord NSFW Servers A Guide for Responsible Users.pdf
Understanding Discord NSFW Servers A Guide for Responsible Users.pdf
 
Histor y of HAM Radio presentation slide
Histor y of HAM Radio presentation slideHistor y of HAM Radio presentation slide
Histor y of HAM Radio presentation slide
 
Axa Assurance Maroc - Insurer Innovation Award 2024
Axa Assurance Maroc - Insurer Innovation Award 2024Axa Assurance Maroc - Insurer Innovation Award 2024
Axa Assurance Maroc - Insurer Innovation Award 2024
 
04-2024-HHUG-Sales-and-Marketing-Alignment.pptx
04-2024-HHUG-Sales-and-Marketing-Alignment.pptx04-2024-HHUG-Sales-and-Marketing-Alignment.pptx
04-2024-HHUG-Sales-and-Marketing-Alignment.pptx
 
Developing An App To Navigate The Roads of Brazil
Developing An App To Navigate The Roads of BrazilDeveloping An App To Navigate The Roads of Brazil
Developing An App To Navigate The Roads of Brazil
 
Apidays New York 2024 - Scaling API-first by Ian Reasor and Radu Cotescu, Adobe
Apidays New York 2024 - Scaling API-first by Ian Reasor and Radu Cotescu, AdobeApidays New York 2024 - Scaling API-first by Ian Reasor and Radu Cotescu, Adobe
Apidays New York 2024 - Scaling API-first by Ian Reasor and Radu Cotescu, Adobe
 
Bajaj Allianz Life Insurance Company - Insurer Innovation Award 2024
Bajaj Allianz Life Insurance Company - Insurer Innovation Award 2024Bajaj Allianz Life Insurance Company - Insurer Innovation Award 2024
Bajaj Allianz Life Insurance Company - Insurer Innovation Award 2024
 
Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...
Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...
Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...
 
Finology Group – Insurtech Innovation Award 2024
Finology Group – Insurtech Innovation Award 2024Finology Group – Insurtech Innovation Award 2024
Finology Group – Insurtech Innovation Award 2024
 
HTML Injection Attacks: Impact and Mitigation Strategies
HTML Injection Attacks: Impact and Mitigation StrategiesHTML Injection Attacks: Impact and Mitigation Strategies
HTML Injection Attacks: Impact and Mitigation Strategies
 
Strategize a Smooth Tenant-to-tenant Migration and Copilot Takeoff
Strategize a Smooth Tenant-to-tenant Migration and Copilot TakeoffStrategize a Smooth Tenant-to-tenant Migration and Copilot Takeoff
Strategize a Smooth Tenant-to-tenant Migration and Copilot Takeoff
 
Powerful Google developer tools for immediate impact! (2023-24 C)
Powerful Google developer tools for immediate impact! (2023-24 C)Powerful Google developer tools for immediate impact! (2023-24 C)
Powerful Google developer tools for immediate impact! (2023-24 C)
 

python-ppt.ppt

  • 1. Interpreter v/s Compiler Interpreter Compiler Translates program one statement at a time. Scans the entire program and translates it as a whole into machine code. Interpreters usually take less amount of time to analyze the source code. However, the overall execution time is comparatively slower than compilers. Compilers usually take a large amount of time to analyze the source code. However, the overall execution time is comparatively faster than interpreters. No Object Code is generated, hence are memory efficient. Generates Object Code which further requires linking, hence requires more memory. Programming languages like JavaScript, Python, Ruby use interpreters. Programming languages like C, C++, Java use compilers.
  • 2. Python What Is Python Python is an open-sourced, interpreted, object-oriented, high-level programming language with dynamic syntax. It is highly attractive for Rapid Application Development and scripting. Most importantly, it is readable, simple, easy to learn & use which indeed increases productivity and reduces the cost of maintenance. It was initially formulated by Guido van Rossum in the late 1980s at Centrum Wiskunde & Informatica(CWI) in Netherland as a successor to the ABC language. The name Python was named after a BBC’s TV Show called ‘Monty Python’s Flying Circus‘ which he was a fan of. The name was perfect at that time since he wanted a short, unique, and slightly mysterious name for his invention. It may be interesting to know how the different Python versions evolved and what features they introduced. In the table below, we can see Python’s first two major versions(1.0, 2.0), when they were released and what features they introduced before version 3 was designed to rectify the fundamental flaw of the language.
  • 3. Python Table on Python versions 1.0 and 2.0 features and released date. Python Version Features Released Date 1.0 Exception Handling, lambda, filter, reduce, map January 1994 2.0 List comprehensions, garbage collection systems October 16, 2020
  • 4. Python Python versions 2.x and 3.x are the most used Python versions. The latest stable version of Python is 3.10.6, released on August 2, 2022. Since the first release in 1994, Python has had regular updates with new features and supports.
  • 5. Python Why Python ? The question should be: “Why not Python?“. Python is one of the fastest- growing programming languages in the world and it is used by top companies like Google, Facebook, YouTube, Spotify, Instagram, Netflix, etc. In this section, we shall look at where Python is being used, some benefits/drawbacks, and lastly how it is compared to other popular programming languages. What Is Python Used For? As of now, Python has many libraries and frameworks ranging from Numpy, SQLALchemy, Pytorch, Pandas, Keras, Tensorflow, Django, Flask, etc. and it is still growing rapidly. These have made Python a top choice for many developers and companies. Python is popularly used for Development, Scripting, and software testing which indeed has made it suitable for various domains.
  • 6. Where Python is used:- 1. Desktop and Web Applications 2. Data Science 3. Machine Learning 4. Robotics 5. Artificial Intelligence 6. Internet of Things (IoT) 7. Gaming 8. Mobile Applications 9. Natural Language processing
  • 7. Benefits And Drawbacks Of Python • The various attractive features of Python make it popular and preferred in many fields. • Some of the top features of Python include: • Free and Open-Sourced • Dynamically typed • Portable • Numerous libraries and applications • Large supportive community • Flexibility • Easy to use and learn • Extensible • Embeddable • Shorter line of code than most languages Though Python is popular, it is not effective in some domains. Knowing these drawbacks will help us to limit Python to where it is effective, thereby building robust applications.
  • 8. Some Drawbacks of Python are: • Slow speed • Memory inefficient • Ineffective in mobile computing. • Undeveloped database layers. • Run time error prompt due to its dynamism.
  • 9. How to execute Python Programs / Scripts ? Different ways to run Python Script Here are the ways with which we can run a Python script. 1. Interactive Mode 2. Command Line 3. Text Editor (VS Code) 4. IDE (PyCharm, jupyter etc)
  • 10. 1. The Python Interactive Mode • This is the most frequently used way to run a Python code. Here basically we do the following: • Open command prompt / terminal in your system • Enter the command - python or python3 (based on python version installed in your system) • If we see these : >>> then, we are into our python prompt.
  • 11. • The interactive shell is also called REPL which stands for read, evaluate, print, loop. It'll read each command, evaluate and execute it, print the output for that command if any, and continue this same process repeatedly until you quit the shell. • There are different ways to quit the shell: • you can hit Ctrl+Z on Windows or Ctrl+D on Unix systems to quit • use the exit() command • use the quit() command
  • 12. • Pros: • Best for testing every single line of code written. • In this approach, each line of code is evaluated and executed immediately as soon as we hit ↵ Enter. • Great deveopment tool for experimentation of Python code on the way. • Cons: • The code is gone as soon as we close the terminal(or the interactive session) • Not user friendly way to write long code. • To close the interactive session we can: • Type quit() or exit() • Press ctrl + z and hit ↵ Enter for windows. For linux, we can press ctrl+d.
  • 13. 2. Using the Python Command Line • Follow the below steps to run a Python Code through command line - • Write your Python code into any text editor. • Save it with the extension .py into a suitable directory • Open the terminal or command prompt. • Type python/python3 (based on installation) followed by the file name.py – • Eg:- python sample.py
  • 14. 3. Run Python on Text Editor • If you want to run your Python code into a text editor -- suppose VS Code, then follow the below steps: • From extensions section, find and install 'Python' extension
  • 15. 3. Run Python on Text Editor • If you want to run your Python code into a text editor -- suppose VS Code, then follow the below steps: • From extensions section, find and install 'Python' extension
  • 16. • Restart your VS code to make sure the extension is installed properly • Create a new file, type your Python code and save it • Run it using the VS code's terminal by typing the command "py hello.py" Or, Right Click -> Run Python file in terminal
  • 17. • 4. Run Python on IDLE • Python installation comes with an Integrated Development and Learning Environment, which is popularly known as IDLE. Though Python IDLE are by-default included with Python installations on Windows and Mac, if you’re a Linux user, then you can easily download Python IDLE using your package manager. • Steps to run a python program on IDLE: • Open the Python IDLE(navigate to the path where Python is installed, open IDLE(python version)) • The shell is the default mode of operation for Python IDLE. So, the first thing you will see is the Python Shell --
  • 18. • You can write any code here and press enter to execute • To run a Python script you can go to File -> New File Now, write your code and save the file -- Once saved, you can run your code from Run -> Run Module Or simply by pressing F5 --
  • 19. Python Indentation • Indentation refers to the spaces at the beginning of a code line. • Where in other programming languages the indentation in code is for readability only, the indentation in Python is very important. • Python uses indentation to indicate a block of code. Python will give you an error if you skip the indentation: Example Syntax Error: if 5 > 2: print("Five is greater than two!")
  • 20. The number of spaces is up to you as a programmer, the most common use is four, but it has to be at least one. Example • if 5 > 2: print("Five is greater than two!") if 5 > 2: print("Five is greater than two!") You have to use the same number of spaces in the same block of code, otherwise Python will give you an error:
  • 21. Python Variables In Python, variables are created when you assign a value to it: Example Variables in Python: x = 5 y = "Hello, World!" Python has no command for declaring a variable. Variables do not need to be declared with any particular type, and can even change type after they have been set. Example x = 4 # x is of type int x = "Sally" # x is now of type str print(x)
  • 22. Python Variables Casting If you want to specify the data type of a variable, this can be done with casting. Example x = str(3) # x will be '3' y = int(3) # y will be 3 z = float(3) # z will be 3.0 Get the Type You can get the data type of a variable with the type() function. Example x = 5 y = "John" print(type(x)) print(type(y))
  • 23. Python Variables • Single or Double Quotes? • String variables can be declared either by using single or double quotes: • Example • x = "John" # is the same as x = 'John‘ Case-Sensitive • Variable names are case-sensitive. • Example • This will create two variables: • a = 4 A = "Sally" #A will not overwrite a •
  • 24. Variable Names • A variable can have a short name (like x and y) or a more descriptive name (age, carname, total_volume). Rules for Python variables:A variable name must start with a letter or the underscore character • A variable name cannot start with a number • A variable name can only contain alpha-numeric characters and underscores (A-z, 0-9, and _ ) • Variable names are case-sensitive (age, Age and AGE are three different variables) Example • Legal variable names: • myvar = "John" my_var = "John" _my_var = "John" myVar = "John" MYVAR = "John" myvar2 = "John"
  • 25. Variable Names • A variable can have a short name (like x and y) or a more descriptive name (age, carname, total_volume). Rules for Python variables:A variable name must start with a letter or the underscore character • A variable name cannot start with a number • A variable name can only contain alpha-numeric characters and underscores (A-z, 0-9, and _ ) • Variable names are case-sensitive (age, Age and AGE are three different variables) Example • Legal variable names: • myvar = "John" my_var = "John" _my_var = "John" myVar = "John" MYVAR = "John" myvar2 = "John"
  • 26. Variable Names • Example Illegal variable names: 2myvar = "John" my-var = "John" my var = "John" • Multi Words Variable Names • Variable names with more than one word can be difficult to read. • There are several techniques you can use to make them more readable: Camel Case • Each word, except the first, starts with a capital letter: • myVariableName = "John" Pascal Case • Each word starts with a capital letter: • MyVariableName = "John" Snake Case • Each word is separated by an underscore character: • my_variable_name = "John"
  • 27. Assign Multiple Variables Python allows you to assign values to multiple variables in one line: • Example • x, y, z = "Orange", "Banana", "Cherry" print(x) print(y) print(z) One Value to Multiple Variables • And you can assign the same value to multiple variables in one line: • Example • x = y = z = "Orange" print(x) print(y) print(z)
  • 28. Assign Multiple Variables Unpack a Collection • If you have a collection of values in a list, tuple etc. Python allows you to extract the values into variables. This is called unpacking. • Example • Unpack a list: • fruits = ["apple", "banana", "cherry"] x, y, z = fruits print(x) print(y) print(z)
  • 29. Python - Output Variables Output Variables • The Python print() function is often used to output variables. • Example • x = "Python is awesome" print(x) In the print() function, you output multiple variables, separated by a comma: • Example • x = "Python" y = "is" z = "awesome" print(x, y, z) You can also use the + operator to output multiple variables: • Example • x = "Python " y = "is " z = "awesome" print(x + y + z)
  • 30. Python - Output Variables For numbers, the + character works as a mathematical operator: • Example • x = 5 y = 10 print(x + y) • In the print() function, when you try to combine a string and a number with the + operator, Python will give you an error: • Example • x = 5 y = "John" print(x + y) • The best way to output multiple variables in the print() function is to separate them with commas, which even support different data types: • Example • x = 5 y = "John" print(x, y)
  • 31. Python - Global Variables • Variables that are created outside of a function are known as global variables. • Global variables can be used by everyone, both inside of functions and outside. Create a variable outside of a function, and use it inside the function x = "awesome" def myfunc(): print("Python is " + x) myfunc() If you create a variable with the same name inside a function, this variable will be local, and can only be used inside the function. The global variable with the same name will remain as it was, global and with the original value.
  • 32. Python - Global Variables The global Keyword • Normally, when you create a variable inside a function, that variable is local, and can only be used inside that function. • To create a global variable inside a function, you can use the global keyword. Example • If you use the global keyword, the variable belongs to the global scope: • def myfunc(): global x x = "fantastic" myfunc() print("Python is " + x)
  • 33. Python - Global Variables Also, use the global keyword if you want to change a global variable inside a function. Example To change the value of a global variable inside a function, refer to the variable by using the global keyword: x = "awesome" def myfunc(): global x x = "fantastic" myfunc() print("Python is " + x)
  • 34. Python - DATA Types Built-in Data Types • In programming, data type is an important concept. • Variables can store data of different types, and different types can do different things. • Python has the following data types built-in by default, in these categories: Text Type: str Numeric Types: int, float, complex Sequence Types: list, tuple, range Mapping Type: dict Set Types: set, frozenset Boolean Type: bool Binary Types: bytes, bytearray, memoryview None Type: NoneType
  • 35. Python - Global Variables Getting the Data Type • You can get the data type of any object by using the type() function: • Example • Print the data type of the variable x: • x = 5 print(type(x)) Setting the Data Type • In Python, the data type is set when you assign a value to a variable:
  • 36. Example Data Type x = "Hello World" str x = 20 int x = 20.5 float x = 1j complex x = ["apple", "banana", "cherry"] list x = ("apple", "banana", "cherry") tuple x = range(6) range x = {"name" : "John", "age" : 36} dict x = {"apple", "banana", "cherry"} set x = frozenset({"apple", "banana", "cherry"}) frozenset x = True bool x = b"Hello" bytes x = bytearray(5) bytearray x = memoryview(bytes(5)) memoryview x = None NoneType
  • 37. Python - Numbers • There are three numeric types in Python: • int • float • complex • Variables of numeric types are created when you assign a value to them: • Example • x = 1 # int y = 2.8 # float z = 1j # complex • To verify the type of any object in Python, use the type() function: Example • print(type(x)) print(type(y)) print(type(z))
  • 38. Python - Numbers Int Int, or integer, is a whole number, positive or negative, without decimals, of unlimited length. Example Integers: x = 1 y = 35656222554887711 z = -3255522 print(type(x)) print(type(y)) print(type(z))
  • 39. Python - Numbers Float Float, or "floating point number" is a number, positive or negative, containing one or more decimals. Float can also be scientific numbers with an "e" to indicate the power of 10. Example Floats: x = 35e3 y = 12E4 z = -87.7e100 x = 1.10 y = 1.0 z = -35.59 print(type(x)) print(type(y)) print(type(z))
  • 40. Python - Numbers Complex • Complex numbers are written with a "j" as the imaginary part: x = 3+5j y = 5j z = -5j print(type(x)) print(type(y)) print(type(z)) Random Number • Python does not have a random() function to make a random number, but Python has a built-in module called random that can be used to make random numbers: Example • Import the random module, and display a random number between 1 and 9: • import random print(random.randrange(1, 10))
  • 41. Python - Numbers Type Conversion • You can convert from one type to another with the int(), float(), and complex() methods: • Example • Convert from one type to another: • x = 1 # int y = 2.8 # float z = 1j # complex #convert from int to float: a = float(x) #convert from float to int: b = int(y) #convert from int to complex: c = complex(x) print(a) print(b) print(c) print(type(a)) print(type(b)) print(type(c))
  • 42. Python - Numbers Type Conversion • You can convert from one type to another with the int(), float(), and complex() methods: • Example • Convert from one type to another: • x = 1 # int y = 2.8 # float z = 1j # complex #convert from int to float: a = float(x) #convert from float to int: b = int(y) #convert from int to complex: c = complex(x) print(a) print(b) print(c) print(type(a)) print(type(b)) print(type(c))
  • 43. Python - Casting Specify a Variable Type • There may be times when you want to specify a type on to a variable. This can be done with casting. Python is an object-orientated language, and as such it uses classes to define data types, including its primitive types. • Casting in python is therefore done using constructor functions: • int() - constructs an integer number from an integer literal, a float literal (by removing all decimals), or a string literal (providing the string represents a whole number) • float() - constructs a float number from an integer literal, a float literal or a string literal (providing the string represents a float or an integer) • str() - constructs a string from a wide variety of data types, including strings, integer literals and float literals Example Integers: x = int(1) # x will be 1 y = int(2.8) # y will be 2 z = int("3") # z will be 3
  • 44. Python - Strings Strings • Strings in python are surrounded by either single quotation marks, or double quotation marks. • 'hello' is the same as "hello". • You can display a string literal with the print() function: Example • print("Hello") print('Hello') • Multiline Strings • You can assign a multiline string to a variable by using three quotes: • Example • You can use three double quotes: • a = """Lorem ipsum dolor sit amet, consectetur adipiscing elit, ut labore et dolore magna aliqua.""" print(a)
  • 45. Python - Strings Strings are Arrays • Like many other popular programming languages, strings in Python are arrays of bytes representing unicode characters. • However, Python does not have a character data type, a single character is simply a string with a length of 1. • Square brackets can be used to access elements of the string. Example Get the character at position 1 (remember that the first character has the position 0): a = "Hello, World!" print(a[1])
  • 46. Python - Strings Looping Through a String Since strings are arrays, we can loop through the characters in a string, with a for loop. Example Loop through the letters in the word "banana": for x in "banana": print(x)
  • 47. Slicing - Strings Slicing • You can return a range of characters by using the slice syntax. • Specify the start index and the end index, separated by a colon, to return a part of the string. Example • Get the characters from position 2 to position 5 (not included): • b = "Hello, World!" print(b[2:5]) Slice From the Start • By leaving out the start index, the range will start at the first character: • Example • Get the characters from the start to position 5 (not included): • b = "Hello, World!" print(b[:5])
  • 48. Slicing - Strings Slice To the End • By leaving out the end index, the range will go to the end: • Example • Get the characters from position 2, and all the way to the end: • b = "Hello, World!" print(b[2:]) Negative Indexing Use negative indexes to start the slice from the end of the string: Example • Get the characters: • From: "o" in "World!" (position -5) • To, but not included: "d" in "World!" (position -2): • b = "Hello, World!" print(b[-5:-2])
  • 49. Modify - Strings • Python has a set of built-in methods that you can use on strings. Upper Case Example • The upper() method returns the string in upper case: a = "Hello, World!" print(a.upper()) Lower Case Example The lower() method returns the string in lower case: a = "Hello, World!" print(a.lower())
  • 50. Modify - Strings Remove Whitespace • Whitespace is the space before and/or after the actual text, and very often you want to remove this space. Example • The strip() method removes any whitespace from the beginning or the end: • a = " Hello, World! " print(a.strip()) # returns "Hello, World!“ Replace String Example • The replace() method replaces a string with another string: • a = "Hello, World!" print(a.replace("H", "J"))
  • 51. Modify - Strings Split String • The split() method returns a list where the text between the specified separator becomes the list items. Example • The split() method splits the string into substrings if it finds instances of the separator: • a = "Hello, World!" print(a.split(",")) # returns ['Hello', ' World!']
  • 52. Modify - Strings Split String • The split() method returns a list where the text between the specified separator becomes the list items. Example • The split() method splits the string into substrings if it finds instances of the separator: • a = "Hello, World!" print(a.split(",")) # returns ['Hello', ' World!']
  • 53. Concatenate - Strings String Concatenation • To concatenate, or combine, two strings you can use the + operator. Example • Merge variable a with variable b into variable c: • a = "Hello" b = "World" c = a + b print(c) To add a space between them, add a " ": • a = "Hello" b = "World" c = a + " " + b print(c)
  • 54. Format - Strings we can combine strings and numbers by using the format() method! • The format() method takes the passed arguments, formats them, and places them in the string where the placeholders {} are: Example • Use the format() method to insert numbers into strings: age = 36 txt = "My name is John, and I am {}" print(txt.format(age)) • The format() method takes unlimited number of arguments, and are placed into the respective placeholders: • Example • quantity = 3 itemno = 567 price = 49.95 myorder = "I want {} pieces of item {} for {} dollars." print(myorder.format(quantity, itemno, price))
  • 55. Format - Strings • You can use index numbers {0} to be sure the arguments are placed in the correct placeholders: Example • quantity = 3 itemno = 567 price = 49.95 myorder = "I want to pay {2} dollars for {0} pieces of item {1}." print(myorder.format(quantity, itemno, price))
  • 56. Escape Character To insert characters that are illegal in a string, use an escape character. An escape character is a backslash followed by the character you want to insert. An example of an illegal character is a double quote inside a string that is surrounded by double quotes: Example • You will get an error if you use double quotes inside a string that is surrounded by double quotes: • txt = "We are the so-called "Vikings" from the north." To fix this problem, use the escape character ": Example • The escape character allows you to use double quotes when you normally would not be allowed: • txt = "We are the so-called "Vikings" from the north."
  • 57. Python Booleans Booleans represent one of two values: True or False. • Boolean Values • In programming you often need to know if an expression is True or False. • You can evaluate any expression in Python, and get one of two answers, True or False. • When you compare two values, the expression is evaluated and Python returns the Boolean answer: Example print(10 > 9) print(10 == 9) print(10 < 9)
  • 58. Python Booleans • When you run a condition in an if statement, Python returns True or False: Example Print a message based on whether the condition is True or False: a = 200 b = 33 if b > a: print("b is greater than a") else: print("b is not greater than a")
  • 59. Python Booleans Evaluate Values and Variables The bool() function allows you to evaluate any value, and give you True or False in return, Example • Evaluate a string and a number: • print(bool("Hello")) print(bool(15)) Example • Evaluate two variables: • x = "Hello" y = 15 print(bool(x)) print(bool(y))
  • 60. Python Booleans • Most Values are True • Almost any value is evaluated to True if it has some sort of content. • Any string is True, except empty strings. • Any number is True, except 0. • Any list, tuple, set, and dictionary are True, except empty ones. • Example • The following will return True: • bool("abc") bool(123) bool(["apple", "cherry", "banana"])
  • 61. Python Booleans • You can execute code based on the Boolean answer of a function: Example • Print "YES!" if the function returns True, otherwise print "NO!": def myFunction() : return True if myFunction(): print("YES!") else: print("NO!") Python also has many built-in functions that return a boolean value, like the isinstance() function, which can be used to determine if an object is of a certain data type: Example • Check if an object is an integer or not: • x = 200 print(isinstance(x, int))
  • 62. Python Operators Python Arithmetic Operators Arithmetic operators are used with numeric values to perform common mathematical operations: Operator Name Example + Addition x + y - Subtraction x - y * Multiplication x * y / Division x / y % Modulus x % y ** Exponentiation x ** y // Floor division x // y
  • 63. Python Assignment Operators Assignment operators are used to assign values to variables: Operator Example Same As = x = 5 x = 5 += x += 3 x = x + 3 -= x -= 3 x = x - 3 *= x *= 3 x = x * 3 /= x /= 3 x = x / 3 %= x %= 3 x = x % 3 //= x //= 3 x = x // 3 **= x **= 3 x = x ** 3 &= x &= 3 x = x & 3 |= x |= 3 x = x | 3 ^= x ^= 3 x = x ^ 3
  • 64. Comparison Operators • Comparison operators are used to compare two values: Operator Name Example == Equal x == y != Not equal x != y > Greater than x > y < Less than x < y >= Greater than or equal to x >= y <= Less than or equal to x <= y
  • 65. Logical Operators • Logical operators are used to combine conditional statements: Operator Description Example and Returns True if both statements are true x < 5 and x < 10 or Returns True if one of the statements is true x < 5 or x < 4 not Reverse the result, returns False if the result is true not(x < 5 and x < 10)
  • 66. Identity Operators • Identity operators are used to compare the objects, not if they are equal, but if they are actually the same object, with the same memory location: Operator Description Example is Returns True if both variables are the same object x is y is not Returns True if both variables are not the same object x is not y
  • 67. Python Lists mylist = ["apple", "banana", "cherry"] List • Lists are used to store multiple items in a single variable. • Lists are one of 4 built-in data types in Python used to store collections of data, the other 3 are Tuple, Set, and Dictionary, all with different qualities and usage. • Lists are created using square brackets: Example Create a List: thislist = ["apple", "banana", "cherry"] print(thislist)
  • 68. Python Lists List Items • List items are ordered, changeable, and allow duplicate values. • List items are indexed, the first item has index [0], the second item has index [1] etc. Ordered • When we say that lists are ordered, it means that the items have a defined order, and that order will not change. • If you add new items to a list, the new items will be placed at the end of the list. Changeable • The list is changeable, meaning that we can change, add, and remove items in a list after it has been created. Allow Duplicates • Since lists are indexed, lists can have items with the same value: Example • Lists allow duplicate values: • thislist = ["apple", "banana", "cherry", "apple", "cherry"] print(thislist)
  • 69. Python Lists List Length • To determine how many items a list has, use the len() function: Example Print the number of items in the list: thislist = ["apple", "banana", "cherry"] print(len(thislist)) List Items - Data Types List items can be of any data type: Example • String, int and boolean data types: • list1 = ["apple", "banana", "cherry"] list2 = [1, 5, 7, 9, 3] list3 = [True, False, False]
  • 70. Python Lists A list can contain different data types: Example • A list with strings, integers and boolean values: • list1 = ["abc", 34, True, 40, "male"] type() • From Python's perspective, lists are defined as objects with the data type 'list': • <class 'list'> Example • What is the data type of a list? • mylist = ["apple", "banana", "cherry"] print(type(mylist))
  • 71. Python Lists The list() Constructor • It is also possible to use the list() constructor when creating a new list. Example • Using the list() constructor to make a List: • thislist = list(("apple", "banana", "cherry")) # note the double round-brackets print(thislist) Python Collections (Arrays) • There are four collection data types in the Python programming language: • List is a collection which is ordered and changeable. Allows duplicate members. • Tuple is a collection which is ordered and unchangeable. Allows duplicate members. • Set is a collection which is unordered, unchangeable*, and unindexed. No duplicate members. • Dictionary is a collection which is ordered** and changeable. No duplicate members.
  • 72. Access List Items Access Items • List items are indexed and you can access them by referring to the index number: Example • Print the second item of the list: • thislist = ["apple", "banana", "cherry"] print(thislist[1]) Note: The first item has index 0. • Negative Indexing • Negative indexing means start from the end • -1 refers to the last item, -2 refers to the second last item etc. Example • Print the last item of the list: • thislist = ["apple", "banana", "cherry"] print(thislist[-1])
  • 73. Access List Items Range of Indexes • You can specify a range of indexes by specifying where to start and where to end the range. • When specifying a range, the return value will be a new list with the specified items. Example • Return the third, fourth, and fifth item: • thislist = ["apple", "banana", "cherry", "orange", "kiwi", "melon", "mango"] print(thislist[2:5]) Note: The search will start at index 2 (included) and end at index 5 (not included).
  • 74. Access List Items • By leaving out the start value, the range will start at the first item: Example This example returns the items from the beginning to, but NOT including, "kiwi": thislist = ["apple", "banana", "cherry", "orange", "kiwi", "melon", "mango"] print(thislist[:4]) By leaving out the end value, the range will go on to the end of the list: Example • This example returns the items from "cherry" to the end: • thislist = ["apple", "banana", "cherry", "orange", "kiwi", "melon", "mango"] print(thislist[2:])
  • 75. Access List Items Range of Negative Indexes • Specify negative indexes if you want to start the search from the end of the list: Example • This example returns the items from "orange" (-4) to, but NOT including "mango" (-1): • thislist = ["apple", "banana", "cherry", "orange", "kiwi", "melon", "mango"] print(thislist[-4:-1]) Check if Item Exists • To determine if a specified item is present in a list use the in keyword: • Example • Check if "apple" is present in the list: • thislist = ["apple", "banana", "cherry"] if "apple" in thislist: print("Yes, 'apple' is in the fruits list")
  • 76. Change List Items Change Item Value • To change the value of a specific item, refer to the index number: Example • Change the second item: • thislist = ["apple", "banana", "cherry"] thislist[1] = "blackcurrant" print(thislist) • Change a Range of Item Values • To change the value of items within a specific range, define a list with the new values, and refer to the range of index numbers where you want to insert the new values: Example • Change the values "banana" and "cherry" with the values "blackcurrant" and "watermelon": • thislist = ["apple", "banana", "cherry", "orange", "kiwi", "mango"] thislist[1:3] = ["blackcurrant", "watermelon"] print(thislist)
  • 77. Change List Items • Change Item Value • To change the value of a specific item, refer to the index number: Example Change the second item: thislist = ["apple", "banana", "cherry"] thislist[1] = "blackcurrant" print(thislist)
  • 78. Append List Items • To add an item to the end of the list, use the append() method: • To insert a list item at a specified index, use the insert() method.
  • 79. Remove List Items • The remove() method removes the specified item. • The pop() method removes the specified index. • If you do not specify the index, the pop() method removes the last item. • The del keyword also removes the specified index: • The del keyword can also delete the list completely. • The clear() method empties the list. • The list still remains, but it has no content.
  • 80. Tuples Tuple • Tuples are used to store multiple items in a single variable. • A tuple is a collection which is ordered and unchangeable. • Tuples are written with round brackets. Tuple Items • Tuple items are ordered, unchangeable, and allow duplicate values. • Tuple items are indexed, the first item has index [0], the second item has index [1] etc. • Ordered • When we say that tuples are ordered, it means that the items have a defined order, and that order will not change. • Unchangeable • Tuples are unchangeable, meaning that we cannot change, add or remove items after the tuple has been created. • Allow Duplicates • Since tuples are indexed, they can have items with the same value:
  • 81. Tuples Access Tuple Items • You can access tuple items by referring to the index number, inside square brackets: • Negative indexing means start from the end. • -1 refers to the last item, -2 refers to the second last item etc. Range of Indexes • You can specify a range of indexes by specifying where to start and where to end the range. • When specifying a range, the return value will be a new tuple with the specified items. Range of Negative Indexes • Specify negative indexes if you want to start the search from the end of the tuple:
  • 82. Remove List Items • The remove() method removes the specified item. • The pop() method removes the specified index. • If you do not specify the index, the pop() method removes the last item. • The del keyword also removes the specified index: • The del keyword can also delete the list completely. • The clear() method empties the list. • The list still remains, but it has no content.
  • 83. Python - Set • Sets are used to store multiple items in a single variable. • Set is one of 4 built-in data types in Python used to store collections of data, the other 3 are List, Tuple, and Dictionary, all with different qualities and usage. • A set is a collection which is unordered, unchangeable*, and unindexed. • Note: Sets are unordered, so you cannot be sure in which order the items will appear. • Set Items • Set items are unordered, unchangeable, and do not allow duplicate values. • Unordered • Unordered means that the items in a set do not have a defined order. • Set items can appear in a different order every time you use them, and cannot be referred to by index or key. • Unchangeable • Set items are unchangeable, meaning that we cannot change the items after the set has been created. • Once a set is created, you cannot change its items, but you can remove items and add new items.
  • 84. Python - Set • The set() Constructor • It is also possible to use the set() constructor to make a set. Example Access Items • You cannot access items in a set by referring to an index or a key. • But you can loop through the set items using a for loop, or ask if a specified value is present in a set, by using the in keyword. Change Items • Once a set is created, you cannot change its items, but you can add new items. Add Items • To add one item to a set use the add() method. Add Sets • To add items from another set into the current set, use the update() method.
  • 85. Python - Set Add Any Iterable • The object in the update() method does not have to be a set, it can be any iterable object (tuples, lists, dictionaries etc.) Remove Item • To remove an item in a set, use the remove(), or the discard() method. • The clear() method empties the set: • The del keyword will delete the set completely: • You can loop through the set items by using a for loop:
  • 86. Python – Join Sets Join Two Sets • There are several ways to join two or more sets in Python. • You can use the union() method that returns a new set containing all items from both sets, or the update() method that inserts all the items from one set into another: Keep ONLY the Duplicates • The intersection_update() method will keep only the items that are present in both sets. The intersection() method will return a new set, that only contains the items that are present in both sets.
  • 87. Python – Dictionary • Dictionaries are used to store data values in key:value pairs. • A dictionary is a collection which is ordered*, changeable and do not allow duplicates. • As of Python version 3.7, dictionaries are ordered. In Python 3.6 and earlier, dictionaries are unordered. • Dictionaries are written with curly brackets, and have keys and values: • Dictionaries are used to store data values in key:value pairs. • A dictionary is a collection which is ordered*, changeable and do not allow duplicates. • As of Python version 3.7, dictionaries are ordered. In Python 3.6 and earlier, dictionaries are unordered. • Dictionaries are written with curly brackets, and have keys and values:
  • 88. Python – Dictionary Dictionary Items • Dictionary items are ordered, changeable, and does not allow duplicates. • Dictionary items are presented in key:value pairs, and can be referred to by using the key name. Ordered or Unordered? • As of Python version 3.7, dictionaries are ordered. In Python 3.6 and earlier, dictionaries are unordered. • When we say that dictionaries are ordered, it means that the items have a defined order, and that order will not change. • Unordered means that the items does not have a defined order, you cannot refer to an item by using an index. • Changeable • Dictionaries are changeable, meaning that we can change, add or remove items after the dictionary has been created.
  • 89. Python – Dictionary Accessing Items • You can access the items of a dictionary by referring to its key name, inside square brackets: Get the value of the "model" key: thisdict = { "brand": "Ford", "model": "Mustang", "year": 1964 } x = thisdict["model"] Get Keys • The keys() method will return a list of all the keys in the dictionary. Get Values • The values() method will return a list of all the values in the dictionary.
  • 90. Python – Dictionary The list of the values is a view of the dictionary, meaning that any changes done to the dictionary will be reflected in the values list. Get Items • The items() method will return each item in a dictionary, as tuples in a list. Change Values • You can change the value of a specific item by referring to its key name: Update Dictionary • The update() method will update the dictionary with the items from the given argument. • The argument must be a dictionary, or an iterable object with key:value pairs. Adding Items • Adding an item to the dictionary is done by using a new index key and assigning a value to it:
  • 91. Python – Dictionary Update Dictionary • The update() method will update the dictionary with the items from a given argument. If the item does not exist, the item will be added. • The argument must be a dictionary, or an iterable object with key:value pairs. Removing Items • There are several methods to remove items from a dictionary: Example • The pop() method removes the item with the specified key name: • The popitem() method removes the last inserted item (in versions before 3.7, a random item is removed instead): • The del keyword removes the item with the specified key name:
  • 92. Python – Dictionary Loop Through a Dictionary • You can loop through a dictionary by using a for loop. • When looping through a dictionary, the return value are the keys of the dictionary, but there are methods to return the values as well. • You can also use the values() method to return values of a dictionary: • You can use the keys() method to return the keys of a dictionary: • Loop through both keys and values, by using the items() method:
  • 93. If Else statements • Decision making is required when we want to execute a code only if a certain condition is satisfied. • The if…elif…else statement is used in Python for decision making. Python if Statement Syntax • if test expression: statement(s) • Here, the program evaluates the test expression and will execute statement(s) only if the test expression is True. • If the test expression is False, the statement(s) is not executed. • In Python, the body of the if statement is indicated by the indentation. The body starts with an indentation and the first unindented line marks the end.
  • 94.
  • 95. If Else statements • In the above example, num > 0 is the test expression. • The body of if is executed only if this evaluates to True. • When the variable num is equal to 3, test expression is true and statements inside the body of if are executed. • If the variable num is equal to -1, test expression is false and statements inside the body of if are skipped. • The print() statement falls outside of the if block (unindented). Hence, it is executed regardless of the test expression.
  • 96. If Else statements Python if...else Statement Syntax of if...else if test expression: Body of if else: Body of else • The if..else statement evaluates test expression and will execute the body of if only when the test condition is True. • If the condition is False, the body of else is executed. Indentation is used to separate the blocks.
  • 97. If Else statements Python if...elif...else Statement Syntax of if...elif...else if test expression: Body of if elif test expression: Body of elif else: Body of else
  • 98. If Else statements • The elif is short for else if. It allows us to check for multiple expressions. • If the condition for if is False, it checks the condition of the next elif block and so on. • If all the conditions are False, the body of else is executed. • Only one block among the several if...elif...else blocks is executed according to the condition. • The if block can have only one else block. But it can have multiple elif blocks.
  • 99. If Else statements • Python Nested if statements • We can have a if...elif...else statement inside another if...elif...else statement. This is called nesting in computer programming. • Any number of these statements can be nested inside one another. Indentation is the only way to figure out the level of nesting. They can get confusing, so they must be avoided unless necessary.
  • 100. Python - Functions • How to Define a Function with the def Keyword • To define a function in Python, you type the def keyword first, then the function name and parentheses. • To tell Python the function is a block of code, you specify a colon in front of the function name. What follows is what you want the function to do. • The basic syntax of a function looks like this: def function_name(): # What you want the function to do
  • 101. Python - Functions • To call a function, you write out the function name followed by a paranthesis. • The syntax for calling a function looks like this: • function_name() def learn_to_code(): print("You can learn to code ") learn_to_code() # Output: You can learn to code
  • 102. Python - Functions • To call a function, you write out the function name followed by a paranthesis. • The syntax for calling a function looks like this: • function_name() def learn_to_code(): print("You can learn to code ") learn_to_code() # Output: You can learn to code
  • 103. Python - Functions Arguments • Information can be passed into functions as arguments. • Arguments are specified after the function name, inside the parentheses. You can add as many arguments as you want, just separate them with a comma. Number of Arguments • By default, a function must be called with the correct number of arguments. Meaning that if your function expects 2 arguments, you have to call the function with 2 arguments, not more, and not less.
  • 104. Python - Functions • Arbitrary Arguments, *args • If you do not know how many arguments that will be passed into your function, add a * before the parameter name in the function definition. • This way the function will receive a tuple of arguments, and can access the items accordingly: • Example • If the number of arguments is unknown, add a * before the parameter name: • def my_function(*kids): print("The youngest child is " + kids[2]) my_function("Emil", "Tobias", "Linus")
  • 105. Python - Functions • Default Parameter Value • The following example shows how to use a default parameter value. • If we call the function without argument, it uses the default value: def my_function(country = "Norway"): print("I am from " + country) my_function("Sweden") my_function("India") my_function() my_function("Brazil")
  • 106. Python - Functions • Passing a List as an Argument • You can send any data types of argument to a function (string, number, list, dictionary etc.), and it will be treated as the same data type inside the function. • E.g. if you send a List as an argument, it will still be a List when it reaches the function: • Example • def my_function(food): for x in food: print(x) fruits = ["apple", "banana", "cherry"] my_function(fruits)
  • 107. Python - Functions Return Values • To let a function return a value, use the return statement: Example def my_function(x): return 5 * x print(my_function(3)) print(my_function(5)) print(my_function(9))
  • 108. Python - Lambda Functions What are lambda functions in Python? • In Python, an anonymous function is a function that is defined without a name. • While normal functions are defined using the def keyword in Python, anonymous functions are defined using the lambda keyword. • Hence, anonymous functions are also called lambda functions. A lambda function in python has the following syntax. Syntax of Lambda Function in python • lambda arguments: expression • Lambda functions can have any number of arguments but only one expression. The expression is evaluated and returned. Lambda functions can be used wherever function objects are required.
  • 109. Python - Lambda Functions What are lambda functions in Python? • In Python, an anonymous function is a function that is defined without a name. • While normal functions are defined using the def keyword in Python, anonymous functions are defined using the lambda keyword. • Hence, anonymous functions are also called lambda functions. A lambda function in python has the following syntax. Syntax of Lambda Function in python • lambda arguments: expression • Lambda functions can have any number of arguments but only one expression. The expression is evaluated and returned. Lambda functions can be used wherever function objects are required.
  • 110. Python - Lambda Functions • Use of Lambda Function in python • We use lambda functions when we require a nameless function for a short period of time. • In Python, we generally use it as an argument to a higher-order function (a function that takes in other functions as arguments). Lambda functions are used along with built-in functions like filter(), map() etc.
  • 111. Python - Lambda Functions
  • 112. Python Loops • What is for loop in Python? • The for loop in Python is used to iterate over a sequence (list, tuple, string) or other iterable objects. Iterating over a sequence is called traversal. Syntax of for Loop for val in sequence: loop body • Here, val is the variable that takes the value of the item inside the sequence on each iteration. • Loop continues until we reach the last item in the sequence. The body of for loop is separated from the rest of the code using indentation.
  • 113. Python Range • The Range function in Python • The range() function provides a sequence of integers based upon the function's arguments. • range(stop) • range(start, stop[, step]) • The start argument is the first value in the range. • If range() is called with only one argument, then Python assumes start = 0. • The stop argument is the upper bound of the range. It is important to realize that this upper value is not included in the range.
  • 114. Python Range In the example below, we have a range starting at the default value of 0 and including integers less than 5. # Example with one argument for i in range(5): print(i, end=", ") # prints: 0, 1, 2, 3, 4,
  • 115. Python For loop with else • A for loop can have an optional else block as well. The else part is executed if the items in the sequence used in for loop exhausts. • The break keyword can be used to stop a for loop. In such cases, the else part is ignored. • Hence, a for loop's else part runs if no break occurs.
  • 116. Python For loop with else • A for loop can have an optional else block as well. The else part is executed if the items in the sequence used in for loop exhausts. • The break keyword can be used to stop a for loop. In such cases, the else part is ignored. • Hence, a for loop's else part runs if no break occurs.
  • 117.
  • 118. Python While loop • The while loop in Python is used to iterate over a block of code as long as the test expression (condition) is true. • We generally use this loop when we don't know the number of times to iterate beforehand. • Syntax of while Loop in Python while test_expression: Body of while • In the while loop, test expression is checked first. The body of the loop is entered only if the test_expression evaluates to True. After one iteration, the test expression is checked again. This process continues until the test_expression evaluates to False. • In Python, the body of the while loop is determined through indentation. • The body starts with indentation and the first unindented line marks the end. • Python interprets any non-zero value as True. None and 0 are interpreted as False.
  • 119. Python Datetime Python Dates • A date in Python is not a data type of its own, but we can import a module named datetime to work with dates as date objects. Import the datetime module and display the current date: • import datetime x = datetime.datetime.now() print(x) Date Output • When we execute the code from the example above the result will be: • 2022-09-26 11:31:03.664255The date contains year, month, day, hour, minute, second, and microsecond. • The datetime module has many methods to return information about the date object.
  • 120. Python Datetime Creating Date Objects • To create a date, we can use the datetime() class (constructor) of the datetime module. • The datetime() class requires three parameters to create a date: year, month, day. The strftime() Method • The datetime object has a method for formatting date objects into readable strings. • The method is called strftime(), and takes one parameter, format, to specify the format of the returned string:
  • 121. Python Datetime Directive Description Example %a Weekday, short version Wed %A Weekday, full version Wednesday %w Weekday as a number 0-6, 0 is Sunday 3 %d Day of month 01-31 31 %b Month name, short version Dec %B Month name, full version December %m Month as a number 01-12 12
  • 122. Python Modules • What are modules in Python? • Modules refer to a file containing Python statements and definitions. • A file containing Python code, for example: example.py, is called a module, and its module name would be example. • We use modules to break down large programs into small manageable and organized files. Furthermore, modules provide reusability of code. • We can define our most used functions in a module and import it, instead of copying their definitions into different programs. • Let us create a module. Type the following and save it as example.py. • # Python Module example def add(a, b): """This program adds two numbers and return the result""“ result = a + b return result
  • 123. Python Modules • We can import the definitions inside a module to another module or the interactive interpreter in Python. • We use the import keyword to do this. To import our previously defined module example, we type the following in the Python prompt. • >>> import example • This does not import the names of the functions defined in example directly in the current symbol table. It only imports the module name example there. • Using the module name we can access the function using the dot . operator. For example: • >>> example.add(4,5.5) • 9.5 • Python has tons of standard modules. You can check out the full list of Python standard modules and their use cases. These files are in the Lib directory inside the location where you installed Python. • Standard modules can be imported the same way as we import our user-defined modules.
  • 124. Python Modules Python import statement • We can import a module using the import statement and access the definitions inside it using the dot operator as described above. Here is an example. # import statement example # to import standard module math import math print("The value of pi is", math.pi) Import with renaming • We can import a module by renaming it as follows: # import module by renaming it import math as m print("The value of pi is", m.pi) • We have renamed the math module as m. This can save us typing time in some cases. Note that the name math is not recognized in our scope. Hence, math.pi is invalid, and m.pi is the correct implementation.
  • 125. Python Modules • Python from...import statement • We can import specific names from a module without importing the module as a whole. Here is an example. • # import only pi from math module from math import pi print("The value of pi is", pi) • Here, we imported only the pi attribute from the math module. • In such cases, we don't use the dot operator. We can also import multiple attributes as follows: • >>> from math import pi, e • >>> pi 3.141592653589793 • >>> e 2.718281828459045
  • 126. Python Modules Import all names • We can import all names(definitions) from a module using the following construct: # import all names from the standard module math from math import * print("The value of pi is", pi) Here, we have imported all the definitions from the math module. This includes all names visible in our scope except those beginning with an underscore(private definitions). Importing everything with the asterisk (*) symbol is not a good programming practice. This can lead to duplicate definitions for an identifier. It also hampers the readability of our code.
  • 127. Python Modules Python Module Search Path • While importing a module, Python looks at several places. Interpreter first looks for a built-in module. Then(if built-in module not found), Python looks into a list of directories defined in sys.path. The search is in this order. • The current directory. • PYTHONPATH (an environment variable with a list of directories). • The installation-dependent default directory. • Reloading a module • The Python interpreter imports a module only once during a session. This makes things more efficient. Here is an example to show how this works. • Suppose we have the following code in a module named my_module. # This module shows the effect of multiple imports and reload print("This code got executed")
  • 128. Python Modules • Now we see the effect of multiple imports. >>> import my_module This code got executed >>> import my_module >>> import my_module We can see that our code got executed only once. This goes to say that our module was imported only once. Now if our module changed during the course of the program, we would have to reload it. One way to do this is to restart the interpreter. But this does not help much. Python provides a more efficient way of doing this. We can use the reload() function inside the imp module to reload a module. We can do it in the following ways: • >>> import importlib • >>> import my_module • This code got executed • >>> import my_module • >>> importlib.reload(my_module) • This code got executed <module 'my_module' from '.my_module.py'>
  • 129. Python Modules The dir() built-in function • We can use the dir() function to find out names that are defined inside a module. • For example, we have defined a function add() in the module example that we had in the beginning. • We can use dir in example module in the following way: