Presentation is loading. Please wait.

Presentation is loading. Please wait.

Introduction to PYTHON

Similar presentations


Presentation on theme: "Introduction to PYTHON"— Presentation transcript:

1 Introduction to PYTHON
Rashid Ahmad Department of Physics, KUST

2 Anaconda Open Source Distribution
Over 15 million users worldwide Develop and train machine learning and deep learning models with Scikit-learn, TensorFlow, and Theano 2. Integrated Development Environments Spyder Jupytor

3 Hello World The print() function Exercises Print the following Example
I’ m “your name” Use single(double) quotation marks inside each other Use print() as calculator Use Escape Sequence The print() function Example print(“Hello World”) print(‘Hello World’) print(‘Hello \’ nice \’ World’)

4 Variables, Numbers and Strings
Exercises Input the username and print it in the reverse order Hint: Use input function e.g. Name = Input() 2. Print only first and third letters of the name Casting int(), float(), str() Example int(2.5) str(4) float(‘4’) String Indexing name = ‘Python’ print(name[0:1:5])

5 String Methods s = ‘ hello, world! ’, q = ‘I am {}’, age = 25
1. strip() print(s.strip()) returns ‘hello, world!’ 2. len() print(len(s)) returns 3. lower() print(s.lower()) returns ‘hello, world!’ upper() print(s.upper()) returns ‘HELLO, WORLD!’ title() print(s.title()) returns ‘Hello, World!’ replace() print(s.replace(“,”, “ ”)) returns ‘Hello World!’ split() print(s.split(","))  returns ['Hello', ' World!'] format() print(q.format(age)) returns I am 36 find() print(s.find(‘w’)) returns center() print(s.center(10)) returns hello, world!

6 String Methods Exercises
Take two coma separated inputs from user (name and one character of the name) and count the occurrence of that character of the name Use the format and method to create a string

7 Arithmetic and Assignment Operators
Arithmetic operators: they are used with numeric values to perform common mathematical operations: Assignment operators: they are used to assign values to variables: Operator Name Example + Addition x + y - Subtraction x - y * Multiplication x * y / Division x / y % Modulus x % y ** Exponentiation x ** y // Float division x // y Operator Example Same As = 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 >>= x >>= 3 x = x >> 3 <<= x <<= 3 x = x << 3

8 Comparison and Logical Operators
Comparison operators: they are used to compare two values: Logical operators: they are used to combine conditional statements: 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 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)

9 Identity and Membership Operators
Identity operators: they are used to compare the objects, not if they are equal, but if they are actually the same object, with the same memory location: Membership operators: they are used to test if a sequence is presented in an object: Operator Description Example in  Returns True if a sequence with the specified value is present in the object x in y not in Returns True if a sequence with the specified value is not present in the object x not in y 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

10 Loop Statements 3. If else Statement Example
a = 10 b = 20 if b > a:    print(“b is greater than a”) elif a == b:    print("a and b are equal") else: print(“a is greater than b”) 1. If Statement Example a = 10 b = 20 if b > a: print(“b is greater than a”) 2. If else Statement a = 33 b = 200 if b > a: print(“b is greater than a”) else: print(“a is greater than b”)

11 If else elif statement Exercises
Create a game in which user guesses some random number Write a program which checks eligibility of a student for admission based on Test Score and CGPA

12 The While Loop It executes set of statements as long as given condition is true The While Statement Example i = 1 while i < 6:   print(i)   i += 1 3. The continue Statement Example i = 0 while i < 6: i += 1 if i == 3: continue print(i) The Break Statement Example i = 1 while i < 6: print(i) if i == 3: break i += 1

13 The For Loop Execute a set of statements, once for each item 1. The Simple for Loop Example fruits = ["apple", "banana", "cherry"] for x in fruits: print(x) The for else loop Example for x in range(6):   print(x) else:   print("Finally finished!") 4. Nested Loops Example adj = ["red", "big", "tasty"] fruits = ["apple", "banana", "cherry"] for x in adj: for y in fruits:     print(x, y) The Range Function Example for i in range(2, 30, 3):   print(f“Welcome {i}’’)

14 List and Its Methods Changeable ordered collection of objects 1. Creating List Example fruits = ["apple", "banana", "cherry"] print(fruits) Method Description append() Adds an element at the end of the list clear() Removes all the elements from the list copy() Returns a copy of the list count() Returns the number of elements with the specified value extend() Add the elements of a list (or any iterable), to the end of the current list index() Returns the index of the first element with the specified value insert() Adds an element at the specified position pop() Removes the element at the specified position remove() Removes the item with the specified value reverse() Reverses the order of the list sort() Sorts the list 2. The insert method Example fruits = ["apple", "banana", "cherry"] fruits.insert(1, "orange")   print(fruits)

15 Tuple and Its Methods Unchangeable ordered collection of objects 1. Creating Tuple Example fruits = ("apple", "banana", "cherry”) print(fruits) 3. Adding Items is not Possible Example fruits = ("apple", "banana", "cherry”) Fruits[3] = “orange” # error will be raised  print(fruits) 2. Check if Item Exists Example fruits = ("apple", "banana", "cherry”) if "apple" in fruits:   print("Yes, 'apple' is in the fruits tuple") Method Description count() Returns the number of times a specified value occurs in a tuple index() Searches the tuple for a specified value and returns the position of where it was found

16 Sets and Its Methods Method Description add() Adds an element to the set clear() Removes all the elements from the set copy() Returns a copy of the set difference() Returns a set containing the difference between two or more sets difference_update() Removes the items in this set that are also included in another, specified set discard() Remove the specified item intersection() Returns a set, that is the intersection of two other sets intersection_update() Removes the items in this set that are not present in other, specified set(s) isdisjoint() Returns whether two sets have a intersection or not issubset() Returns whether another set contains this set or not issuperset() Returns whether this set contains another set or not pop() Removes an element from the set remove() Removes the specified element symmetric_difference() Returns a set with the symmetric differences of two sets symmetric_difference_update() inserts the symmetric differences from this set and another union() Return a set containing the union of sets update() Update the set with the union of this set and others A set is a collection which is unordered and unindexed 1. Creating Set Example fruits = {"apple", "banana", "cherry”} print(fruits) The del keyword Example fruits = ("apple", "banana", "cherry”) del fruits print(fruits)

17 Dictionaries and Its Methods
A dictionary is a collection which is ordered, changeable and indexed Creating Dictionary Example student = {“name“: “Rashid”, “GPA", 3.4}  print(student) Method Description clear() Removes all the elements from the dictionary copy() Returns a copy of the dictionary fromkeys() Returns a dictionary with the specified keys and values get() Returns the value of the specified key items() Returns a list containing the a tuple for each key value pair keys() Returns a list containing the dictionary's keys pop() Removes the element with the specified key popitem() Removes the last inserted key-value pair setdefault() Returns the value of the specified key. If the key does not exist: insert the key, with the specified value update() Updates the dictionary with the specified key-value pairs values() Returns a list of all the values in the dictionary Accessing Items Example student = {“name“: “Rashid”, “GPA", 3.4}  print(student.get(“name”))

18 Arrays and Its Methods An array is a special variable, which can hold more than one value at a time. Creating Array Example student = [“A”, “B”, “C”, “D”, “E”]  print(student) Method Description append() Adds an element at the end of the list clear() Removes all the elements from the list copy() Returns a copy of the list count() Returns the number of elements with the specified value extend() Add the elements of a list (or any iterable), to the end of the current list index() Returns the index of the first element with the specified value insert() Adds an element at the specified position pop() Removes the element at the specified position remove() Removes the first item with the specified value reverse() Reverses the order of the list sort() Sorts the list Accessing Items Example student = {“name“: “Rashid”, “GPA", 3.4}  print(student.get(“name”))

19 Functions A function is a set of statements that take inputs, do some specific computation and produces output. Defining Function Example def add_two(a,b): return a+b print(add_two(4,5)) Exercises Define a function which takes name as input from user and print its last character Define a function which takes two numbers as input and returns the greater number Define a function which generates the Fibonacci Series 2. Concatenate Strings Example First_name = input(‘’Enter your first name:”) Second_name = input(‘’Enter your Second name:”) print(add_two(First_name , Second_name))

20 Classes and Objects The built-in __init__() function class LHC_school:
Class:  It is a structure created for defining an object. It contains a set of attributes that characterizes any object that is instantiated from this class. Creating a Class class  MyClass:   x = 5 Object:  It is an instance of a class. This is the realized version of the class, where the class is manifested in the program. Creating an object obj =  MyClass() print(obj.x) The built-in __init__() function class LHC_school: def __init__(self) print(“This is 8th LHC School”) P1= LHC_school() print(P1)

21 LHC Class class LHC_school:
def __init__(self, name, number, place, month, period, year): self.name = name self.number = number self.place = place self.month = month self.period = period self.year = year def venue(self): print(self.name + self.place) def which(self): print(self.number) def summer(self): print(self.month) def date(self): print(self.period) def season(self): print(self.year) def main(): This_year = LHC_school("LHC School ", "8th", "held in Islamabad", "August", "19-30", "2019") This_year.venue() This_year.which() This_year.summer() This_year.date() This_year.season() if __name__ == "__main__": main()

22 I Thank You All!


Download ppt "Introduction to PYTHON"

Similar presentations


Ads by Google