Introduction to PYTHON

Slides:



Advertisements
Similar presentations
Course A201: Introduction to Programming 10/28/2010.
Advertisements

Container Types in Python
CHAPTER 4 AND 5 Section06: Sequences. General Description "Normal" variables x = 19  The name "x" is associated with a single value Sequence variables:
String and Lists Dr. Benito Mendoza. 2 Outline What is a string String operations Traversing strings String slices What is a list Traversing a list List.
I210 review Fall 2011, IUB. Python is High-level programming –High-level versus machine language Interpreted Language –Interpreted versus compiled 2.
Introduction to Python
Python. What is Python? A programming language we can use to communicate with the computer and solve problems We give the computer instructions that it.
4. Python - Basic Operators
Data Structures in Python By: Christopher Todd. Lists in Python A list is a group of comma-separated values between square brackets. A list is a group.
Python for Informatics: Exploring Information
Strings CSE 1310 – Introduction to Computers and Programming Vassilis Athitsos University of Texas at Arlington 1.
Collecting Things Together - Lists 1. We’ve seen that Python can store things in memory and retrieve, using names. Sometime we want to store a bunch of.
Lists CSE 1310 – Introduction to Computers and Programming Vassilis Athitsos University of Texas at Arlington 1.
Built-in Data Structures in Python An Introduction.
Copyright © 2015 Pearson Education, Inc. Publishing as Pearson Addison-Wesley C H A P T E R 9 Dictionaries and Sets.
1 CSC 221: Introduction to Programming Fall 2011 Lists  lists as sequences  list operations +, *, len, indexing, slicing, for-in, in  example: dice.
CS105 STRING LIST TUPLE DICTIONARY. Characteristics of Sequence What is sequence data type? It stores several objects Each object has an order Each object.
1 CSC 221: Introduction to Programming Fall 2012 Lists  lists as sequences  list operations +, *, len, indexing, slicing, for-in, in  example: dice.
Midterm Review Important control structures Functions Loops Conditionals Important things to review Binary Boolean operators (and, or, not) Libraries (import.
More Sequences. Review: String Sequences  Strings are sequences of characters so we can: Use an index to refer to an individual character: Use slices.
Guide to Programming with Python Chapter Five Lists and dictionaries (data structure); The Hangman Game.
LISTS and TUPLES. Topics Sequences Introduction to Lists List Slicing Finding Items in Lists with the in Operator List Methods and Useful Built-in Functions.
Python Data Structures By Greg Felber. Lists An ordered group of items Does not need to be the same type – Could put numbers, strings or donkeys in the.
Introduction to Programming Oliver Hawkins. BACKGROUND TO PROGRAMMING LANGUAGES Introduction to Programming.
String and Lists Dr. José M. Reyes Álamo. 2 Outline What is a string String operations Traversing strings String slices What is a list Traversing a list.
Lists/Dictionaries. What we are covering Data structure basics Lists Dictionaries Json.
7 - Programming 7J, K, L, M, N, O – Handling Data.
String and Lists Dr. José M. Reyes Álamo.
G. Pullaiah College of Engineering and Technology
Python unit_4 review Tue/Wed, Dec 1-2
Topics Designing a Program Input, Processing, and Output
Input and Output Upsorn Praphamontripong CS 1110
Topics Dictionaries Sets Serializing Objects. Topics Dictionaries Sets Serializing Objects.
Python - Lists.
Containers and Lists CIS 40 – Introduction to Programming in Python
CS 100: Roadmap to Computing
CS-104 Final Exam Review Victor Norman.
Programming for Mobile Technologies
Chapter 10 Lists.
Principles of Computing – UFCFA3-30-1
Basic Python Collective variables (sequences) Lists (arrays)
Arithmetic operations, decisions and looping
Introduction to Python
CHAPTER THREE Sequences.
Guide to Programming with Python
Chapter 10 Lists.
Python - Strings.
4. sequence data type Rocky K. C. Chang 16 September 2018
String and Lists Dr. José M. Reyes Álamo.
Presented by Mirza Elahi 10/29/2018
Topics Sequences Introduction to Lists List Slicing
Topics Dictionaries Sets Serializing Objects. Topics Dictionaries Sets Serializing Objects.
Dictionaries Dictionary: object that stores a collection of data
Python Primer 1: Types and Operators
Basic String Operations
Topics Designing a Program Input, Processing, and Output
Topics Sequences Lists Copying Lists Processing Lists
CISC101 Reminders Assignment 2 due today.
Topics Designing a Program Input, Processing, and Output
Introduction to Computer Science
Topics Sequences Introduction to Lists List Slicing
Sequences Sequences are collections of data values that are ordered by position A string is a sequence of characters A list is a sequence of any Python.
Topic: Loops Loops Idea While Loop Introduction to ranges For Loop
CSE 231 Lab 9.
More Basics of Python Common types of data we will work with
Python List.
COMPUTING.
Introduction to Computer Science
Selamat Datang di “Programming Essentials in Python”
Data Types String holds alphanumeric data as text.
Presentation transcript:

Introduction to PYTHON Rashid Ahmad Department of Physics, KUST 19-08-2019

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

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’)

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])

String Methods s = ‘ hello, world! ’, q = ‘I am {}’, age = 25 1. strip() print(s.strip()) returns ‘hello, world!’ 2. len() print(len(s)) returns 15 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 8 center() print(s.center(10)) returns hello, world!

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

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

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)

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

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”)

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

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) 2. The Break Statement Example i = 1 while i < 6: print(i) if i == 3: break i += 1

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) 3. 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) 2. The Range Function Example for i in range(2, 30, 3):   print(f“Welcome {i}’’)

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)

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

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) 2. The del keyword Example fruits = ("apple", "banana", "cherry”) del fruits print(fruits)

Dictionaries and Its Methods A dictionary is a collection which is ordered, changeable and indexed 1. 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 2. Accessing Items Example student = {“name“: “Rashid”, “GPA", 3.4}  print(student.get(“name”))

Arrays and Its Methods An array is a special variable, which can hold more than one value at a time. 1. 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 2. Accessing Items Example student = {“name“: “Rashid”, “GPA", 3.4}  print(student.get(“name”))

Functions A function is a set of statements that take inputs, do some specific computation and produces output. 1. 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 0 1 1 2 3 5 8 13 21 34 55 . . . 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))

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)

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()

I Thank You All!