SlideShare ist ein Scribd-Unternehmen logo
1 von 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 ?

Weitere ähnliche Inhalte

Was ist angesagt?

09 logic programming
09 logic programming09 logic programming
09 logic programming
saru40
 
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
Ranel Padon
 

Was ist angesagt? (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
 

Ähnlich wie Python bible

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
Prabha Karan
 
what-is-python-presentation.pptx
what-is-python-presentation.pptxwhat-is-python-presentation.pptx
what-is-python-presentation.pptx
Vijay Krishna
 
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
GandaraEyao
 

Ähnlich wie 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
 

Kürzlich hochgeladen

AI Mastery 201: Elevating Your Workflow with Advanced LLM Techniques
AI Mastery 201: Elevating Your Workflow with Advanced LLM TechniquesAI Mastery 201: Elevating Your Workflow with Advanced LLM Techniques
AI Mastery 201: Elevating Your Workflow with Advanced LLM Techniques
VictorSzoltysek
 
+971565801893>>SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHAB...
+971565801893>>SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHAB...+971565801893>>SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHAB...
+971565801893>>SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHAB...
Health
 
TECUNIQUE: Success Stories: IT Service provider
TECUNIQUE: Success Stories: IT Service providerTECUNIQUE: Success Stories: IT Service provider
TECUNIQUE: Success Stories: IT Service provider
mohitmore19
 

Kürzlich hochgeladen (20)

VTU technical seminar 8Th Sem on Scikit-learn
VTU technical seminar 8Th Sem on Scikit-learnVTU technical seminar 8Th Sem on Scikit-learn
VTU technical seminar 8Th Sem on Scikit-learn
 
call girls in Vaishali (Ghaziabad) 🔝 >༒8448380779 🔝 genuine Escort Service 🔝✔️✔️
call girls in Vaishali (Ghaziabad) 🔝 >༒8448380779 🔝 genuine Escort Service 🔝✔️✔️call girls in Vaishali (Ghaziabad) 🔝 >༒8448380779 🔝 genuine Escort Service 🔝✔️✔️
call girls in Vaishali (Ghaziabad) 🔝 >༒8448380779 🔝 genuine Escort Service 🔝✔️✔️
 
Shapes for Sharing between Graph Data Spaces - and Epistemic Querying of RDF-...
Shapes for Sharing between Graph Data Spaces - and Epistemic Querying of RDF-...Shapes for Sharing between Graph Data Spaces - and Epistemic Querying of RDF-...
Shapes for Sharing between Graph Data Spaces - and Epistemic Querying of RDF-...
 
The Real-World Challenges of Medical Device Cybersecurity- Mitigating Vulnera...
The Real-World Challenges of Medical Device Cybersecurity- Mitigating Vulnera...The Real-World Challenges of Medical Device Cybersecurity- Mitigating Vulnera...
The Real-World Challenges of Medical Device Cybersecurity- Mitigating Vulnera...
 
AI Mastery 201: Elevating Your Workflow with Advanced LLM Techniques
AI Mastery 201: Elevating Your Workflow with Advanced LLM TechniquesAI Mastery 201: Elevating Your Workflow with Advanced LLM Techniques
AI Mastery 201: Elevating Your Workflow with Advanced LLM Techniques
 
AI & Machine Learning Presentation Template
AI & Machine Learning Presentation TemplateAI & Machine Learning Presentation Template
AI & Machine Learning Presentation Template
 
How To Troubleshoot Collaboration Apps for the Modern Connected Worker
How To Troubleshoot Collaboration Apps for the Modern Connected WorkerHow To Troubleshoot Collaboration Apps for the Modern Connected Worker
How To Troubleshoot Collaboration Apps for the Modern Connected Worker
 
Exploring the Best Video Editing App.pdf
Exploring the Best Video Editing App.pdfExploring the Best Video Editing App.pdf
Exploring the Best Video Editing App.pdf
 
Vip Call Girls Noida ➡️ Delhi ➡️ 9999965857 No Advance 24HRS Live
Vip Call Girls Noida ➡️ Delhi ➡️ 9999965857 No Advance 24HRS LiveVip Call Girls Noida ➡️ Delhi ➡️ 9999965857 No Advance 24HRS Live
Vip Call Girls Noida ➡️ Delhi ➡️ 9999965857 No Advance 24HRS Live
 
Azure_Native_Qumulo_High_Performance_Compute_Benchmarks.pdf
Azure_Native_Qumulo_High_Performance_Compute_Benchmarks.pdfAzure_Native_Qumulo_High_Performance_Compute_Benchmarks.pdf
Azure_Native_Qumulo_High_Performance_Compute_Benchmarks.pdf
 
Unlocking the Future of AI Agents with Large Language Models
Unlocking the Future of AI Agents with Large Language ModelsUnlocking the Future of AI Agents with Large Language Models
Unlocking the Future of AI Agents with Large Language Models
 
The Guide to Integrating Generative AI into Unified Continuous Testing Platfo...
The Guide to Integrating Generative AI into Unified Continuous Testing Platfo...The Guide to Integrating Generative AI into Unified Continuous Testing Platfo...
The Guide to Integrating Generative AI into Unified Continuous Testing Platfo...
 
The Ultimate Test Automation Guide_ Best Practices and Tips.pdf
The Ultimate Test Automation Guide_ Best Practices and Tips.pdfThe Ultimate Test Automation Guide_ Best Practices and Tips.pdf
The Ultimate Test Automation Guide_ Best Practices and Tips.pdf
 
A Secure and Reliable Document Management System is Essential.docx
A Secure and Reliable Document Management System is Essential.docxA Secure and Reliable Document Management System is Essential.docx
A Secure and Reliable Document Management System is Essential.docx
 
+971565801893>>SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHAB...
+971565801893>>SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHAB...+971565801893>>SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHAB...
+971565801893>>SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHAB...
 
Microsoft AI Transformation Partner Playbook.pdf
Microsoft AI Transformation Partner Playbook.pdfMicrosoft AI Transformation Partner Playbook.pdf
Microsoft AI Transformation Partner Playbook.pdf
 
call girls in Vaishali (Ghaziabad) 🔝 >༒8448380779 🔝 genuine Escort Service 🔝✔️✔️
call girls in Vaishali (Ghaziabad) 🔝 >༒8448380779 🔝 genuine Escort Service 🔝✔️✔️call girls in Vaishali (Ghaziabad) 🔝 >༒8448380779 🔝 genuine Escort Service 🔝✔️✔️
call girls in Vaishali (Ghaziabad) 🔝 >༒8448380779 🔝 genuine Escort Service 🔝✔️✔️
 
Diamond Application Development Crafting Solutions with Precision
Diamond Application Development Crafting Solutions with PrecisionDiamond Application Development Crafting Solutions with Precision
Diamond Application Development Crafting Solutions with Precision
 
TECUNIQUE: Success Stories: IT Service provider
TECUNIQUE: Success Stories: IT Service providerTECUNIQUE: Success Stories: IT Service provider
TECUNIQUE: Success Stories: IT Service provider
 
Optimizing AI for immediate response in Smart CCTV
Optimizing AI for immediate response in Smart CCTVOptimizing AI for immediate response in Smart CCTV
Optimizing AI for immediate response in Smart CCTV
 

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