SlideShare a Scribd company logo
1 of 49
Python
Adarsh Jayanna
Contents
Contents
● Variables in Python
● Numbers in python
● Strings in Python
● Logic and Conditional Flow
● Datastructure in Python
● Loops in Python
● Functions
● Questions
● Variables in python
What is variable?
● Variables are containers for storing data values.
● Unlike other programming languages, Python has no command for
declaring a variable.
● A variable is created the moment you first assign a value to it.
● Python is dynamically type language.
● We can use type(variable name) to know the datatype of the variable.
● We can change the variable type in python.
● Example: number = 5
● 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 alphanumeric characters and underscores
(A-z, 0-9, and _ ).
Numbers in python
Basic arithmetic, floats and modulo
Operators:
● Operators are used to perform operations on variables and values.
● Basic arithmetic operator:
○ + Addition x + y
○ - Subtraction x - y
○ * Multiplication x * y
○ / Division x / y
○ % Modulus x % y
● Float, or "floating point number" is a number, positive or negative,
containing one or more decimals.
● Ex: 10.4
● Ordering Operations:
○ Python follow BODMAS rule
○ This was implemented in python 3
○ Ex: 2 * 5 - 1 = 9
● Python random module:
○ Ex:
Import random
health = 50
health_portion = random.randint(10,20)
Health = health + health_portion
Python Math module
● This module in python is used for mathematical tasks.
● Import math - this will import the math module
● math.floor(2.4) = 2 - this will round the number to the lower value.
● math.ceil(2.4) = 3 - this will round the number to the highest value.
● math.hypot(3,4) = 25 - this will calculate the hypotenuse.
● math.pow(2,3) = 8 - this is similar to 2 ^ 3.
● math.cos(0) = 1 - trigonometry calculations
Strings in python
String literals
● String literals in python are surrounded by either single quotation marks, or
double quotation marks.
● Example:
○ ‘Hello’
○ “Hello”
● Multi line strings - We can use three double or single quotes.
● Example:
○ a = '''Lorem ipsum dolor sit amet,
consectetur adipiscing elit,
sed do eiusmod tempor incididunt
ut labore et dolore magna aliqua.'''
● We use input() to collect data.
● Example:
○ name = input(“Enter name: ”)
○ Look same in idle.
String methods
● Count() - it is used to count the number of times the character or substring
appears in a string.
○ Example: “hello”.count(“h”)
○ Output: 1
● lower() - It is used to convert all the uppercase characters to lowercase in a
string.
○ Example: “Hello”.lower()
○ Output: hello
● upper() - It is used to convert all the lowercase characters to uppercase in a
string.
○ Example: “hello”.upper()
○ Output: HELLO
String methods
● capitalize() - it is used to capitalize the first character in a string.
○ Example: “hello world”.capitalize()
○ Output: Hello world
● title() - It is used to capitalize the first letter of each word in a string.
○ Example: “hello world”.title()
○ Output: Hello World
● isupper() - This returns true if all the characters in the string are in upper
case
○ Example: “hello”.isupper()
○ Output: False
String methods
● istitle() - Returns True if the string follows the rules of a title.
● isalpha() - Returns True if all characters in the string are in the alphabet
● isdigits() - Returns True if all characters in the string are digits
● isalnum() - Returns True if all characters in the string are alphanumeric
● index() - Searches the string for a specified value and returns the position of
where it was found.
○ Ex: x.index(“day”)
○ It throws value error if the string passed is not found.
● find() - Searches the string for a specified value and returns the position of
where it was found.
○ Ex: x.find(“day”)
○ It returns -1 if the string passed is not found.
String methods
● strip() - The strip() method removes any whitespace from the beginning or
the end.
○ a = " Hello, World! "
○ print(a.strip()) # returns "Hello, World!"
○ We can pass parameter to strip the given character.
String 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.
● Syntax:
○ Word[start : end : step]
● Example:
○ b = "Hello, World!"
○ print(b[2:5]) #llo
● We can use b[: :-1] to revere the string.
● We can use -ve indexing to start from the end o the string.
Email Slicer - Program
#get user email
email = input("Enter email address: ").strip()
#Slice out user name
user_name = email[:email.find('@')]
#slice out domain name
domain_name = email[(email.find('@')+1):]
#format message
output = "your username is {} and your domain name is {}".format(user_name,domain_name)
#print output
print(output)
Logic and Conditional Flow
Booleans and Comparison Operators
● Booleans
○ Booleans represent one of two values: True or False.
○ When you compare two values, the expression is evaluated and Python
returns the Boolean answer.
○ Example:
■ print(10 > 9) # True
■ print(10 == 9) # False
■ print(10 < 9) # False
● Operators
○ Comparison operators are used to compare two values
Booleans and Comparison Operators
Operator Name
== Equal
!= Not equal
> Greater than
< Less than
>= Greater than or equal to
<= Less than or equal to
If Statements
● If statements allow us to execute a certain piece of code only if a condition is
true.
● Syntax:
○ If condition :
Statements
● Example:
○ if 3>2:
print("it worked")
If Statements - Else
● Else : The else keyword catches anything which isn't caught by the
preceding conditions.
● Example:
a = 200
b = 33
if b > a:
print("b is greater than a")
else:
print("a is greater than b")
If Statements - Elif
● Elif : The elif keyword is pythons way of saying "if the previous conditions
were not true, then try this condition".
● Example:
a = 200
b = 33
if b > a:
print("b is greater than a")
else:
print("a is greater than b")
Logical Operators
● Logical operators are used to combine conditional statements
Operator Description
and Returns True if both statements are true
or Returns True if one of the statements is true
not Reverse the result, returns False if the result is true
Datastructure in python
List
● A list is a collection which is ordered and changeable. In Python lists are
written with square brackets.
● Example:
thislist = ["apple", "banana", "cherry"]
print(thislist)
● We can store heterogeneous data inside list
● We can use both +ve and -ve index to access elements in the list.
● Slicing can be used on list
○ Example: thislist[0:2]
● We can have a list inside a list
○ Example: l=[1,2,3,4,[5,6,7],8]
print(l[4][1]) # 6
List - program
known_users = ["adarsh","don","pinky","ponky","moon"]
print(len(known_users))
while True:
print("Hi !, Welcome")
name = input("Whats your name: ").strip().lower()
if (name in known_users):
print("Hello {}!".format(name))
remove = input("Would you like to be removed from the system (y/n)")
if(remove.upper()=="Y"):
print(known_users)
known_users.remove(name)
print(known_users)
else:
print("Hmm ! I dont have met you yet")
add_me = input("Would you like to be added to the system (y/n)").lower()
if(add_me=="y"):
known_users.append(name)
elif(add_me=="n"):
print("No problem ! See you around")
Adding item to lists
● Only list can be added to list
● Example:
A = [1,2,3,4]
A = A + 1 // this will give error
A = A + [5] //[1,2,3,4,5]
A = A + “ABC” // this will give error
A = A + [“BCD”] //[1,2,3,4,”BCD”]
A = A + list(“ABC”) //[1,2,3,4,’A’,’B’,’C’]
● We can use append() to add elements at the last of list
● We can use insert() to add the elements at the desired index.
○ Example : A.insert(2,100) // [1,2,100,3,4]
Tuples
● A tuple is a collection which is ordered and unchangeable. In Python tuples
are written with round brackets.
● Example : thistuple = ("apple", "banana", "cherry")
● We can use slice as in list Ex: thituple[0:2] //("apple", "banana")
● Tuples are immutable, so they cannot be changed.
○ Ex: thistuple[1] = “orange” // This will throw error
● We can join tuples using + operator.
○ Ex: tuple1 = ("a", "b" , "c")
tuple2 = (1, 2, 3)
tuple3 = tuple1 + tuple2 // ("a", "b" , "c",1, 2, 3)
Dictionaries
● A dictionary is a collection which is unordered, changeable and indexed. In
Python dictionaries are written with curly brackets, and they have keys and
values.
● Example : thisdict = {"brand": "Ford","model": "Mustang","year": 1964}
● We can access the elements in the dictionary by referring to the key name.
○ Example: thisdict["model"] // Mustang
● You can change the value of a specific item by referring to its key name
○ Example : thisdict["year"] = 2018
● keys() gives all the keys in the dictionary
○ Example: thisdict.keys() //dict.keys([“brand”,”model”,”year”])
● values() gives all the values in the dictionary
○ Example: thisdict.values() //dict.keys([“Ford”,”Mustang”,1964])
Dictionaries
● We can store dictionary inside a dictionary
○ Example: students{
“don” : {“id”: 11,”Age”:20, “grade”:”B”},
“monu” : {“id”: 22,”Age”:19, “grade”:”A”},
“sonu” : {“id”: 33,”Age”:18, “grade”:”C”}
}
print(students[“don”][“Age”]) //20
Cinema Simulator
films = {"don 1": [18,5],
"sheru": [3,2],
"tarzan": [15,5],
"bourne":[18,5]
}
while True:
print(list(films.keys()))
choice = input("What film would you like to watch ?").strip().lower()
if choice in films:
age = int(input("How old are you ?:").strip())
if age>=films[choice][0]:
if films[choice][1]>0:
films[choice][1] = films[choice][1] -1
print("Enjoy the film !")
else:
print("Sorry, We are sold out!")
else:
print("you are too young to see the film!")
else:
print("We do not have that film...")
Loops in python
While loop
● With the while loop we can execute a set of statements as long as a
condition is true.
● Example:
i = 1
while i < 6:
print(i)
i += 1
● This will print numbers from 1 to 5.
For loop
● A for loop is used for iterating over a sequence (that is either a list, a tuple, a
dictionary, a set, or a string).
● With the for loop we can execute a set of statements, once for each item in
a list, tuple, set etc.
● Example:
vowels = 0
consonants = 0
for letter in "adarsh" :
if letter.lower() in "aeiou":
vowels = vowels +1
elif letter ==" ":
pass
else:
consonants = consonants + 1
print("There are {} vowels".format(vowels))
print("There are {} consonants".format(consonants))
List Comprehensions
● List Comprehensions provide an elegant way to create new lists. The
following is the basic structure of a list comprehension:
● output_list = [output_exp for var in input_list if (var satisfies this condition)]
● Printing even numbers:
Even_number = [x for x in range(1,101) if x%2==0]
Functions in python
Function
● A function is a block of code which only runs when it is called.
● You can pass data, known as parameters, into a function.
● A function can return data as a result.
● In Python a function is defined using the def keyword.
● Example: def my_function():
print("Hello from a function")
● Function can accept parameter, these parameters are specified after the
function name, inside the parentheses, we can add as many arguments as
we want , just separate them with comma.
Calling function
● To call a function, use the function name followed by parenthesis
● Example: my_function()
Function
● To let function return a value, we use return statement.
● Example:
def my_function(x):
return 5 * x
Variable scope
● Local scope - A variable created inside a function belongs to the local scope
of that function, and can only be used inside that function.
● Example : def myfunc():
x = 300
print(x)
● As explained in the example above, the variable x is not available outside
the function, but it is available for any function inside the function.
● A variable created in the main body of the Python code is a global variable
and belongs to the global scope.
● Example : x = 300
def myfunc():
print(x)
myfunc()
print(x)
Variable scope
● If you need to create a global variable, but are stuck in the local scope, you
can use the global keyword.
● The global keyword makes the variable global.
● use the global keyword if you want to make a change to a global variable
inside a function.
● Example : x = 300
def myfunc():
global x
x = 200
myfunc()
print(x) //200
Arbitrary arguments and keywords
● 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 : def my_function(*kids):
print("The youngest child is " + kids[2])
my_function("Emil", "Tobias", "Linus") //The youngest child is Linus
● If you do not know how many keyword arguments that will be passed into
your function, add two asterisk: ** before the parameter name in the
function definition.
Arbitrary arguments and keywords
● This way the function will receive a dictionary of arguments, and can access
the items accordingly
● Example : def my_function(**kid):
print("His last name is " + kid["lname"])
my_function(fname = "Tobias", lname = "Refsnes")
OOP in python
Python classes and objects
● Class - A Class is like an object constructor, or a "blueprint" for creating
objects.
● To create a class, use the keyword class.
● Example : class MyClass:
x = 5
● Now we can use the class named MyClass to create objects
● Objects have both states and behaviours.
● Example : p1 = MyClass()
print(p1.x)
Python classes and objects
● __init__() - is always executed when the class is being initiated.
● __init__() function can be used to assign values to object properties, or other
operations that are necessary to do when the object is being created.
● Example: class Person:
def __init__(self, name, age):
self.name = name
self.age = age
p1 = Person("John", 36)
print(p1.name)
print(p1.age)
Python classes and objects
● The self parameter is a reference to the current instance of the class, and is
used to access variables that belongs to the class.
● We can call it whatever you like, but it has to be the first parameter of any
function in the class.
● Del - You can delete objects by using the del keyword.
○ Example: del p1
Thank You
Questions ?

More Related Content

What's hot (20)

Array assignment
Array assignmentArray assignment
Array assignment
 
02. haskell motivation
02. haskell motivation02. haskell motivation
02. haskell motivation
 
List,tuple,dictionary
List,tuple,dictionaryList,tuple,dictionary
List,tuple,dictionary
 
1 D Arrays in C++
1 D Arrays in C++1 D Arrays in C++
1 D Arrays in C++
 
09 logic programming
09 logic programming09 logic programming
09 logic programming
 
Python : Regular expressions
Python : Regular expressionsPython : Regular expressions
Python : Regular expressions
 
Array
ArrayArray
Array
 
1-D array
1-D array1-D array
1-D array
 
Python programming : Strings
Python programming : StringsPython programming : Strings
Python programming : Strings
 
Arrays in C++
Arrays in C++Arrays in C++
Arrays in C++
 
Functional Programming by Examples using Haskell
Functional Programming by Examples using HaskellFunctional Programming by Examples using Haskell
Functional Programming by Examples using Haskell
 
Unit 6. Arrays
Unit 6. ArraysUnit 6. Arrays
Unit 6. Arrays
 
Python Programming - XI. String Manipulation and Regular Expressions
Python Programming - XI. String Manipulation and Regular ExpressionsPython Programming - XI. String Manipulation and Regular Expressions
Python Programming - XI. String Manipulation and Regular Expressions
 
Session 4
Session 4Session 4
Session 4
 
Data Structures - Lecture 3 [Arrays]
Data Structures - Lecture 3 [Arrays]Data Structures - Lecture 3 [Arrays]
Data Structures - Lecture 3 [Arrays]
 
Introduction to haskell
Introduction to haskellIntroduction to haskell
Introduction to haskell
 
Head First Java Chapter 3
Head First Java Chapter 3Head First Java Chapter 3
Head First Java Chapter 3
 
Functional programming in f sharp
Functional programming in f sharpFunctional programming in f sharp
Functional programming in f sharp
 
Python data handling notes
Python data handling notesPython data handling notes
Python data handling notes
 
binary search tree
binary search treebinary search tree
binary search tree
 

Similar to Python bible

uom-2552-what-is-python-presentation.pptx
uom-2552-what-is-python-presentation.pptxuom-2552-what-is-python-presentation.pptx
uom-2552-what-is-python-presentation.pptxChetanChauhan203001
 
uom-2552-what-is-python-presentation (1).pptx
uom-2552-what-is-python-presentation (1).pptxuom-2552-what-is-python-presentation (1).pptx
uom-2552-what-is-python-presentation (1).pptxPrabha Karan
 
python-presentation.pptx
python-presentation.pptxpython-presentation.pptx
python-presentation.pptxVijay Krishna
 
what-is-python-presentation.pptx
what-is-python-presentation.pptxwhat-is-python-presentation.pptx
what-is-python-presentation.pptxVijay Krishna
 
What is Paython.pptx
What is Paython.pptxWhat is Paython.pptx
What is Paython.pptxParag Soni
 
Introduction of python Introduction of python Introduction of python
Introduction of python Introduction of python Introduction of pythonIntroduction of python Introduction of python Introduction of python
Introduction of python Introduction of python Introduction of pythonGandaraEyao
 
python programming for beginners and advanced
python programming for beginners and advancedpython programming for beginners and advanced
python programming for beginners and advancedgranjith6
 
23UCACC11 Python Programming (MTNC) (BCA)
23UCACC11 Python Programming (MTNC) (BCA)23UCACC11 Python Programming (MTNC) (BCA)
23UCACC11 Python Programming (MTNC) (BCA)ssuser7f90ae
 
Basics of Python Programming
Basics of Python ProgrammingBasics of Python Programming
Basics of Python ProgrammingManishJha237
 
Basic concept of Python.pptx includes design tool, identifier, variables.
Basic concept of Python.pptx includes design tool, identifier, variables.Basic concept of Python.pptx includes design tool, identifier, variables.
Basic concept of Python.pptx includes design tool, identifier, variables.supriyasarkar38
 
Input processing and output in Python
Input processing and output in PythonInput processing and output in Python
Input processing and output in PythonMSB Academy
 
Input processing and output in Python
Input processing and output in PythonInput processing and output in Python
Input processing and output in PythonRaajendra M
 
Strings in Python
Strings in PythonStrings in Python
Strings in Pythonnitamhaske
 
Introduction to Python - Part Two
Introduction to Python - Part TwoIntroduction to Python - Part Two
Introduction to Python - Part Twoamiable_indian
 
parts_of_python_programming_language.pptx
parts_of_python_programming_language.pptxparts_of_python_programming_language.pptx
parts_of_python_programming_language.pptxKoteswari Kasireddy
 
Meetup C++ A brief overview of c++17
Meetup C++  A brief overview of c++17Meetup C++  A brief overview of c++17
Meetup C++ A brief overview of c++17Daniel Eriksson
 

Similar to Python bible (20)

Python
PythonPython
Python
 
uom-2552-what-is-python-presentation.pptx
uom-2552-what-is-python-presentation.pptxuom-2552-what-is-python-presentation.pptx
uom-2552-what-is-python-presentation.pptx
 
uom-2552-what-is-python-presentation (1).pptx
uom-2552-what-is-python-presentation (1).pptxuom-2552-what-is-python-presentation (1).pptx
uom-2552-what-is-python-presentation (1).pptx
 
python-presentation.pptx
python-presentation.pptxpython-presentation.pptx
python-presentation.pptx
 
what-is-python-presentation.pptx
what-is-python-presentation.pptxwhat-is-python-presentation.pptx
what-is-python-presentation.pptx
 
What is Paython.pptx
What is Paython.pptxWhat is Paython.pptx
What is Paython.pptx
 
Introduction of python Introduction of python Introduction of python
Introduction of python Introduction of python Introduction of pythonIntroduction of python Introduction of python Introduction of python
Introduction of python Introduction of python Introduction of python
 
python programming for beginners and advanced
python programming for beginners and advancedpython programming for beginners and advanced
python programming for beginners and advanced
 
Python 101
Python 101Python 101
Python 101
 
23UCACC11 Python Programming (MTNC) (BCA)
23UCACC11 Python Programming (MTNC) (BCA)23UCACC11 Python Programming (MTNC) (BCA)
23UCACC11 Python Programming (MTNC) (BCA)
 
Basics of Python Programming
Basics of Python ProgrammingBasics of Python Programming
Basics of Python Programming
 
Basic concept of Python.pptx includes design tool, identifier, variables.
Basic concept of Python.pptx includes design tool, identifier, variables.Basic concept of Python.pptx includes design tool, identifier, variables.
Basic concept of Python.pptx includes design tool, identifier, variables.
 
Input processing and output in Python
Input processing and output in PythonInput processing and output in Python
Input processing and output in Python
 
Input processing and output in Python
Input processing and output in PythonInput processing and output in Python
Input processing and output in Python
 
Strings in Python
Strings in PythonStrings in Python
Strings in Python
 
Dart workshop
Dart workshopDart workshop
Dart workshop
 
Introduction to Python - Part Two
Introduction to Python - Part TwoIntroduction to Python - Part Two
Introduction to Python - Part Two
 
parts_of_python_programming_language.pptx
parts_of_python_programming_language.pptxparts_of_python_programming_language.pptx
parts_of_python_programming_language.pptx
 
Python ppt
Python pptPython ppt
Python ppt
 
Meetup C++ A brief overview of c++17
Meetup C++  A brief overview of c++17Meetup C++  A brief overview of c++17
Meetup C++ A brief overview of c++17
 

Recently uploaded

Try MyIntelliAccount Cloud Accounting Software As A Service Solution Risk Fre...
Try MyIntelliAccount Cloud Accounting Software As A Service Solution Risk Fre...Try MyIntelliAccount Cloud Accounting Software As A Service Solution Risk Fre...
Try MyIntelliAccount Cloud Accounting Software As A Service Solution Risk Fre...MyIntelliSource, Inc.
 
Russian Call Girls in Karol Bagh Aasnvi ➡️ 8264348440 💋📞 Independent Escort S...
Russian Call Girls in Karol Bagh Aasnvi ➡️ 8264348440 💋📞 Independent Escort S...Russian Call Girls in Karol Bagh Aasnvi ➡️ 8264348440 💋📞 Independent Escort S...
Russian Call Girls in Karol Bagh Aasnvi ➡️ 8264348440 💋📞 Independent Escort S...soniya singh
 
The Evolution of Karaoke From Analog to App.pdf
The Evolution of Karaoke From Analog to App.pdfThe Evolution of Karaoke From Analog to App.pdf
The Evolution of Karaoke From Analog to App.pdfPower Karaoke
 
What are the features of Vehicle Tracking System?
What are the features of Vehicle Tracking System?What are the features of Vehicle Tracking System?
What are the features of Vehicle Tracking System?Watsoo Telematics
 
XpertSolvers: Your Partner in Building Innovative Software Solutions
XpertSolvers: Your Partner in Building Innovative Software SolutionsXpertSolvers: Your Partner in Building Innovative Software Solutions
XpertSolvers: Your Partner in Building Innovative Software SolutionsMehedi Hasan Shohan
 
The Essentials of Digital Experience Monitoring_ A Comprehensive Guide.pdf
The Essentials of Digital Experience Monitoring_ A Comprehensive Guide.pdfThe Essentials of Digital Experience Monitoring_ A Comprehensive Guide.pdf
The Essentials of Digital Experience Monitoring_ A Comprehensive Guide.pdfkalichargn70th171
 
Building Real-Time Data Pipelines: Stream & Batch Processing workshop Slide
Building Real-Time Data Pipelines: Stream & Batch Processing workshop SlideBuilding Real-Time Data Pipelines: Stream & Batch Processing workshop Slide
Building Real-Time Data Pipelines: Stream & Batch Processing workshop SlideChristina Lin
 
办理学位证(UQ文凭证书)昆士兰大学毕业证成绩单原版一模一样
办理学位证(UQ文凭证书)昆士兰大学毕业证成绩单原版一模一样办理学位证(UQ文凭证书)昆士兰大学毕业证成绩单原版一模一样
办理学位证(UQ文凭证书)昆士兰大学毕业证成绩单原版一模一样umasea
 
What is Fashion PLM and Why Do You Need It
What is Fashion PLM and Why Do You Need ItWhat is Fashion PLM and Why Do You Need It
What is Fashion PLM and Why Do You Need ItWave PLM
 
EY_Graph Database Powered Sustainability
EY_Graph Database Powered SustainabilityEY_Graph Database Powered Sustainability
EY_Graph Database Powered SustainabilityNeo4j
 
buds n tech IT solutions
buds n  tech IT                solutionsbuds n  tech IT                solutions
buds n tech IT solutionsmonugehlot87
 
Intelligent Home Wi-Fi Solutions | ThinkPalm
Intelligent Home Wi-Fi Solutions | ThinkPalmIntelligent Home Wi-Fi Solutions | ThinkPalm
Intelligent Home Wi-Fi Solutions | ThinkPalmSujith Sukumaran
 
Steps To Getting Up And Running Quickly With MyTimeClock Employee Scheduling ...
Steps To Getting Up And Running Quickly With MyTimeClock Employee Scheduling ...Steps To Getting Up And Running Quickly With MyTimeClock Employee Scheduling ...
Steps To Getting Up And Running Quickly With MyTimeClock Employee Scheduling ...MyIntelliSource, Inc.
 
Implementing Zero Trust strategy with Azure
Implementing Zero Trust strategy with AzureImplementing Zero Trust strategy with Azure
Implementing Zero Trust strategy with AzureDinusha Kumarasiri
 
why an Opensea Clone Script might be your perfect match.pdf
why an Opensea Clone Script might be your perfect match.pdfwhy an Opensea Clone Script might be your perfect match.pdf
why an Opensea Clone Script might be your perfect match.pdfjoe51371421
 
Adobe Marketo Engage Deep Dives: Using Webhooks to Transfer Data
Adobe Marketo Engage Deep Dives: Using Webhooks to Transfer DataAdobe Marketo Engage Deep Dives: Using Webhooks to Transfer Data
Adobe Marketo Engage Deep Dives: Using Webhooks to Transfer DataBradBedford3
 
Engage Usergroup 2024 - The Good The Bad_The Ugly
Engage Usergroup 2024 - The Good The Bad_The UglyEngage Usergroup 2024 - The Good The Bad_The Ugly
Engage Usergroup 2024 - The Good The Bad_The UglyFrank van der Linden
 
ODSC - Batch to Stream workshop - integration of Apache Spark, Cassandra, Pos...
ODSC - Batch to Stream workshop - integration of Apache Spark, Cassandra, Pos...ODSC - Batch to Stream workshop - integration of Apache Spark, Cassandra, Pos...
ODSC - Batch to Stream workshop - integration of Apache Spark, Cassandra, Pos...Christina Lin
 
Cloud Management Software Platforms: OpenStack
Cloud Management Software Platforms: OpenStackCloud Management Software Platforms: OpenStack
Cloud Management Software Platforms: OpenStackVICTOR MAESTRE RAMIREZ
 

Recently uploaded (20)

Try MyIntelliAccount Cloud Accounting Software As A Service Solution Risk Fre...
Try MyIntelliAccount Cloud Accounting Software As A Service Solution Risk Fre...Try MyIntelliAccount Cloud Accounting Software As A Service Solution Risk Fre...
Try MyIntelliAccount Cloud Accounting Software As A Service Solution Risk Fre...
 
Russian Call Girls in Karol Bagh Aasnvi ➡️ 8264348440 💋📞 Independent Escort S...
Russian Call Girls in Karol Bagh Aasnvi ➡️ 8264348440 💋📞 Independent Escort S...Russian Call Girls in Karol Bagh Aasnvi ➡️ 8264348440 💋📞 Independent Escort S...
Russian Call Girls in Karol Bagh Aasnvi ➡️ 8264348440 💋📞 Independent Escort S...
 
The Evolution of Karaoke From Analog to App.pdf
The Evolution of Karaoke From Analog to App.pdfThe Evolution of Karaoke From Analog to App.pdf
The Evolution of Karaoke From Analog to App.pdf
 
What are the features of Vehicle Tracking System?
What are the features of Vehicle Tracking System?What are the features of Vehicle Tracking System?
What are the features of Vehicle Tracking System?
 
XpertSolvers: Your Partner in Building Innovative Software Solutions
XpertSolvers: Your Partner in Building Innovative Software SolutionsXpertSolvers: Your Partner in Building Innovative Software Solutions
XpertSolvers: Your Partner in Building Innovative Software Solutions
 
The Essentials of Digital Experience Monitoring_ A Comprehensive Guide.pdf
The Essentials of Digital Experience Monitoring_ A Comprehensive Guide.pdfThe Essentials of Digital Experience Monitoring_ A Comprehensive Guide.pdf
The Essentials of Digital Experience Monitoring_ A Comprehensive Guide.pdf
 
Building Real-Time Data Pipelines: Stream & Batch Processing workshop Slide
Building Real-Time Data Pipelines: Stream & Batch Processing workshop SlideBuilding Real-Time Data Pipelines: Stream & Batch Processing workshop Slide
Building Real-Time Data Pipelines: Stream & Batch Processing workshop Slide
 
Call Girls In Mukherjee Nagar 📱 9999965857 🤩 Delhi 🫦 HOT AND SEXY VVIP 🍎 SE...
Call Girls In Mukherjee Nagar 📱  9999965857  🤩 Delhi 🫦 HOT AND SEXY VVIP 🍎 SE...Call Girls In Mukherjee Nagar 📱  9999965857  🤩 Delhi 🫦 HOT AND SEXY VVIP 🍎 SE...
Call Girls In Mukherjee Nagar 📱 9999965857 🤩 Delhi 🫦 HOT AND SEXY VVIP 🍎 SE...
 
办理学位证(UQ文凭证书)昆士兰大学毕业证成绩单原版一模一样
办理学位证(UQ文凭证书)昆士兰大学毕业证成绩单原版一模一样办理学位证(UQ文凭证书)昆士兰大学毕业证成绩单原版一模一样
办理学位证(UQ文凭证书)昆士兰大学毕业证成绩单原版一模一样
 
What is Fashion PLM and Why Do You Need It
What is Fashion PLM and Why Do You Need ItWhat is Fashion PLM and Why Do You Need It
What is Fashion PLM and Why Do You Need It
 
EY_Graph Database Powered Sustainability
EY_Graph Database Powered SustainabilityEY_Graph Database Powered Sustainability
EY_Graph Database Powered Sustainability
 
buds n tech IT solutions
buds n  tech IT                solutionsbuds n  tech IT                solutions
buds n tech IT solutions
 
Intelligent Home Wi-Fi Solutions | ThinkPalm
Intelligent Home Wi-Fi Solutions | ThinkPalmIntelligent Home Wi-Fi Solutions | ThinkPalm
Intelligent Home Wi-Fi Solutions | ThinkPalm
 
Steps To Getting Up And Running Quickly With MyTimeClock Employee Scheduling ...
Steps To Getting Up And Running Quickly With MyTimeClock Employee Scheduling ...Steps To Getting Up And Running Quickly With MyTimeClock Employee Scheduling ...
Steps To Getting Up And Running Quickly With MyTimeClock Employee Scheduling ...
 
Implementing Zero Trust strategy with Azure
Implementing Zero Trust strategy with AzureImplementing Zero Trust strategy with Azure
Implementing Zero Trust strategy with Azure
 
why an Opensea Clone Script might be your perfect match.pdf
why an Opensea Clone Script might be your perfect match.pdfwhy an Opensea Clone Script might be your perfect match.pdf
why an Opensea Clone Script might be your perfect match.pdf
 
Adobe Marketo Engage Deep Dives: Using Webhooks to Transfer Data
Adobe Marketo Engage Deep Dives: Using Webhooks to Transfer DataAdobe Marketo Engage Deep Dives: Using Webhooks to Transfer Data
Adobe Marketo Engage Deep Dives: Using Webhooks to Transfer Data
 
Engage Usergroup 2024 - The Good The Bad_The Ugly
Engage Usergroup 2024 - The Good The Bad_The UglyEngage Usergroup 2024 - The Good The Bad_The Ugly
Engage Usergroup 2024 - The Good The Bad_The Ugly
 
ODSC - Batch to Stream workshop - integration of Apache Spark, Cassandra, Pos...
ODSC - Batch to Stream workshop - integration of Apache Spark, Cassandra, Pos...ODSC - Batch to Stream workshop - integration of Apache Spark, Cassandra, Pos...
ODSC - Batch to Stream workshop - integration of Apache Spark, Cassandra, Pos...
 
Cloud Management Software Platforms: OpenStack
Cloud Management Software Platforms: OpenStackCloud Management Software Platforms: OpenStack
Cloud Management Software Platforms: OpenStack
 

Python bible

  • 3. Contents ● Variables in Python ● Numbers in python ● Strings in Python ● Logic and Conditional Flow ● Datastructure in Python ● Loops in Python ● Functions ● Questions
  • 5. What is variable? ● Variables are containers for storing data values. ● Unlike other programming languages, Python has no command for declaring a variable. ● A variable is created the moment you first assign a value to it. ● Python is dynamically type language. ● We can use type(variable name) to know the datatype of the variable. ● We can change the variable type in python. ● Example: number = 5 ● 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 alphanumeric characters and underscores (A-z, 0-9, and _ ).
  • 7. Basic arithmetic, floats and modulo Operators: ● Operators are used to perform operations on variables and values. ● Basic arithmetic operator: ○ + Addition x + y ○ - Subtraction x - y ○ * Multiplication x * y ○ / Division x / y ○ % Modulus x % y ● Float, or "floating point number" is a number, positive or negative, containing one or more decimals. ● Ex: 10.4
  • 8. ● Ordering Operations: ○ Python follow BODMAS rule ○ This was implemented in python 3 ○ Ex: 2 * 5 - 1 = 9 ● Python random module: ○ Ex: Import random health = 50 health_portion = random.randint(10,20) Health = health + health_portion
  • 9. Python Math module ● This module in python is used for mathematical tasks. ● Import math - this will import the math module ● math.floor(2.4) = 2 - this will round the number to the lower value. ● math.ceil(2.4) = 3 - this will round the number to the highest value. ● math.hypot(3,4) = 25 - this will calculate the hypotenuse. ● math.pow(2,3) = 8 - this is similar to 2 ^ 3. ● math.cos(0) = 1 - trigonometry calculations
  • 11. String literals ● String literals in python are surrounded by either single quotation marks, or double quotation marks. ● Example: ○ ‘Hello’ ○ “Hello” ● Multi line strings - We can use three double or single quotes. ● Example: ○ a = '''Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua.'''
  • 12. ● We use input() to collect data. ● Example: ○ name = input(“Enter name: ”) ○ Look same in idle.
  • 13. String methods ● Count() - it is used to count the number of times the character or substring appears in a string. ○ Example: “hello”.count(“h”) ○ Output: 1 ● lower() - It is used to convert all the uppercase characters to lowercase in a string. ○ Example: “Hello”.lower() ○ Output: hello ● upper() - It is used to convert all the lowercase characters to uppercase in a string. ○ Example: “hello”.upper() ○ Output: HELLO
  • 14. String methods ● capitalize() - it is used to capitalize the first character in a string. ○ Example: “hello world”.capitalize() ○ Output: Hello world ● title() - It is used to capitalize the first letter of each word in a string. ○ Example: “hello world”.title() ○ Output: Hello World ● isupper() - This returns true if all the characters in the string are in upper case ○ Example: “hello”.isupper() ○ Output: False
  • 15. String methods ● istitle() - Returns True if the string follows the rules of a title. ● isalpha() - Returns True if all characters in the string are in the alphabet ● isdigits() - Returns True if all characters in the string are digits ● isalnum() - Returns True if all characters in the string are alphanumeric ● index() - Searches the string for a specified value and returns the position of where it was found. ○ Ex: x.index(“day”) ○ It throws value error if the string passed is not found. ● find() - Searches the string for a specified value and returns the position of where it was found. ○ Ex: x.find(“day”) ○ It returns -1 if the string passed is not found.
  • 16. String methods ● strip() - The strip() method removes any whitespace from the beginning or the end. ○ a = " Hello, World! " ○ print(a.strip()) # returns "Hello, World!" ○ We can pass parameter to strip the given character.
  • 17. String 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. ● Syntax: ○ Word[start : end : step] ● Example: ○ b = "Hello, World!" ○ print(b[2:5]) #llo ● We can use b[: :-1] to revere the string. ● We can use -ve indexing to start from the end o the string.
  • 18. Email Slicer - Program #get user email email = input("Enter email address: ").strip() #Slice out user name user_name = email[:email.find('@')] #slice out domain name domain_name = email[(email.find('@')+1):] #format message output = "your username is {} and your domain name is {}".format(user_name,domain_name) #print output print(output)
  • 20. Booleans and Comparison Operators ● Booleans ○ Booleans represent one of two values: True or False. ○ When you compare two values, the expression is evaluated and Python returns the Boolean answer. ○ Example: ■ print(10 > 9) # True ■ print(10 == 9) # False ■ print(10 < 9) # False ● Operators ○ Comparison operators are used to compare two values
  • 21. Booleans and Comparison Operators Operator Name == Equal != Not equal > Greater than < Less than >= Greater than or equal to <= Less than or equal to
  • 22. If Statements ● If statements allow us to execute a certain piece of code only if a condition is true. ● Syntax: ○ If condition : Statements ● Example: ○ if 3>2: print("it worked")
  • 23. If Statements - Else ● Else : The else keyword catches anything which isn't caught by the preceding conditions. ● Example: a = 200 b = 33 if b > a: print("b is greater than a") else: print("a is greater than b")
  • 24. If Statements - Elif ● Elif : The elif keyword is pythons way of saying "if the previous conditions were not true, then try this condition". ● Example: a = 200 b = 33 if b > a: print("b is greater than a") else: print("a is greater than b")
  • 25. Logical Operators ● Logical operators are used to combine conditional statements Operator Description and Returns True if both statements are true or Returns True if one of the statements is true not Reverse the result, returns False if the result is true
  • 27. List ● A list is a collection which is ordered and changeable. In Python lists are written with square brackets. ● Example: thislist = ["apple", "banana", "cherry"] print(thislist) ● We can store heterogeneous data inside list ● We can use both +ve and -ve index to access elements in the list. ● Slicing can be used on list ○ Example: thislist[0:2] ● We can have a list inside a list ○ Example: l=[1,2,3,4,[5,6,7],8] print(l[4][1]) # 6
  • 28. List - program known_users = ["adarsh","don","pinky","ponky","moon"] print(len(known_users)) while True: print("Hi !, Welcome") name = input("Whats your name: ").strip().lower() if (name in known_users): print("Hello {}!".format(name)) remove = input("Would you like to be removed from the system (y/n)") if(remove.upper()=="Y"): print(known_users) known_users.remove(name) print(known_users) else: print("Hmm ! I dont have met you yet") add_me = input("Would you like to be added to the system (y/n)").lower() if(add_me=="y"): known_users.append(name) elif(add_me=="n"): print("No problem ! See you around")
  • 29. Adding item to lists ● Only list can be added to list ● Example: A = [1,2,3,4] A = A + 1 // this will give error A = A + [5] //[1,2,3,4,5] A = A + “ABC” // this will give error A = A + [“BCD”] //[1,2,3,4,”BCD”] A = A + list(“ABC”) //[1,2,3,4,’A’,’B’,’C’] ● We can use append() to add elements at the last of list ● We can use insert() to add the elements at the desired index. ○ Example : A.insert(2,100) // [1,2,100,3,4]
  • 30. Tuples ● A tuple is a collection which is ordered and unchangeable. In Python tuples are written with round brackets. ● Example : thistuple = ("apple", "banana", "cherry") ● We can use slice as in list Ex: thituple[0:2] //("apple", "banana") ● Tuples are immutable, so they cannot be changed. ○ Ex: thistuple[1] = “orange” // This will throw error ● We can join tuples using + operator. ○ Ex: tuple1 = ("a", "b" , "c") tuple2 = (1, 2, 3) tuple3 = tuple1 + tuple2 // ("a", "b" , "c",1, 2, 3)
  • 31. Dictionaries ● A dictionary is a collection which is unordered, changeable and indexed. In Python dictionaries are written with curly brackets, and they have keys and values. ● Example : thisdict = {"brand": "Ford","model": "Mustang","year": 1964} ● We can access the elements in the dictionary by referring to the key name. ○ Example: thisdict["model"] // Mustang ● You can change the value of a specific item by referring to its key name ○ Example : thisdict["year"] = 2018 ● keys() gives all the keys in the dictionary ○ Example: thisdict.keys() //dict.keys([“brand”,”model”,”year”]) ● values() gives all the values in the dictionary ○ Example: thisdict.values() //dict.keys([“Ford”,”Mustang”,1964])
  • 32. Dictionaries ● We can store dictionary inside a dictionary ○ Example: students{ “don” : {“id”: 11,”Age”:20, “grade”:”B”}, “monu” : {“id”: 22,”Age”:19, “grade”:”A”}, “sonu” : {“id”: 33,”Age”:18, “grade”:”C”} } print(students[“don”][“Age”]) //20
  • 33. Cinema Simulator films = {"don 1": [18,5], "sheru": [3,2], "tarzan": [15,5], "bourne":[18,5] } while True: print(list(films.keys())) choice = input("What film would you like to watch ?").strip().lower() if choice in films: age = int(input("How old are you ?:").strip()) if age>=films[choice][0]: if films[choice][1]>0: films[choice][1] = films[choice][1] -1 print("Enjoy the film !") else: print("Sorry, We are sold out!") else: print("you are too young to see the film!") else: print("We do not have that film...")
  • 35. While loop ● With the while loop we can execute a set of statements as long as a condition is true. ● Example: i = 1 while i < 6: print(i) i += 1 ● This will print numbers from 1 to 5.
  • 36. For loop ● A for loop is used for iterating over a sequence (that is either a list, a tuple, a dictionary, a set, or a string). ● With the for loop we can execute a set of statements, once for each item in a list, tuple, set etc. ● Example: vowels = 0 consonants = 0 for letter in "adarsh" : if letter.lower() in "aeiou": vowels = vowels +1 elif letter ==" ": pass else: consonants = consonants + 1 print("There are {} vowels".format(vowels)) print("There are {} consonants".format(consonants))
  • 37. List Comprehensions ● List Comprehensions provide an elegant way to create new lists. The following is the basic structure of a list comprehension: ● output_list = [output_exp for var in input_list if (var satisfies this condition)] ● Printing even numbers: Even_number = [x for x in range(1,101) if x%2==0]
  • 39. Function ● A function is a block of code which only runs when it is called. ● You can pass data, known as parameters, into a function. ● A function can return data as a result. ● In Python a function is defined using the def keyword. ● Example: def my_function(): print("Hello from a function") ● Function can accept parameter, these parameters are specified after the function name, inside the parentheses, we can add as many arguments as we want , just separate them with comma. Calling function ● To call a function, use the function name followed by parenthesis ● Example: my_function()
  • 40. Function ● To let function return a value, we use return statement. ● Example: def my_function(x): return 5 * x
  • 41. Variable scope ● Local scope - A variable created inside a function belongs to the local scope of that function, and can only be used inside that function. ● Example : def myfunc(): x = 300 print(x) ● As explained in the example above, the variable x is not available outside the function, but it is available for any function inside the function. ● A variable created in the main body of the Python code is a global variable and belongs to the global scope. ● Example : x = 300 def myfunc(): print(x) myfunc() print(x)
  • 42. Variable scope ● If you need to create a global variable, but are stuck in the local scope, you can use the global keyword. ● The global keyword makes the variable global. ● use the global keyword if you want to make a change to a global variable inside a function. ● Example : x = 300 def myfunc(): global x x = 200 myfunc() print(x) //200
  • 43. Arbitrary arguments and keywords ● 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 : def my_function(*kids): print("The youngest child is " + kids[2]) my_function("Emil", "Tobias", "Linus") //The youngest child is Linus ● If you do not know how many keyword arguments that will be passed into your function, add two asterisk: ** before the parameter name in the function definition.
  • 44. Arbitrary arguments and keywords ● This way the function will receive a dictionary of arguments, and can access the items accordingly ● Example : def my_function(**kid): print("His last name is " + kid["lname"]) my_function(fname = "Tobias", lname = "Refsnes")
  • 46. Python classes and objects ● Class - A Class is like an object constructor, or a "blueprint" for creating objects. ● To create a class, use the keyword class. ● Example : class MyClass: x = 5 ● Now we can use the class named MyClass to create objects ● Objects have both states and behaviours. ● Example : p1 = MyClass() print(p1.x)
  • 47. Python classes and objects ● __init__() - is always executed when the class is being initiated. ● __init__() function can be used to assign values to object properties, or other operations that are necessary to do when the object is being created. ● Example: class Person: def __init__(self, name, age): self.name = name self.age = age p1 = Person("John", 36) print(p1.name) print(p1.age)
  • 48. Python classes and objects ● The self parameter is a reference to the current instance of the class, and is used to access variables that belongs to the class. ● We can call it whatever you like, but it has to be the first parameter of any function in the class. ● Del - You can delete objects by using the del keyword. ○ Example: del p1