Upgrade to Pro — share decks privately, control downloads, hide ads and more …

Introduction to Programming in Python

Sponsored · SiteGround - Reliable hosting with speed, security, and support you can count on. →

Introduction to Programming in Python

Introduction to programming to absolute beginners using python. A workshop/seminar at my college

Avatar for Bibek Gautam

Bibek Gautam

March 05, 2019

Other Decks in Programming

Transcript

  1. Intro to Programming: With Python (a workshop) Bibek Gautam St.

    Xavier’s College, Maitighar March 5, 2019
  2. 1. Intro to Python Why Python? Figure: Python Figure: c

    Bibek Gautam Intro to Programming: With Python 2/38
  3. 1. Intro to Python Compiled Vs. Interpreted Figure: Compiled Vs.

    Interpreted (Ex 1) Bibek Gautam Intro to Programming: With Python 3/38
  4. 2. Setting up Environment Installing python On Linux (Ubuntu/Mint or

    similar) $ sudo apt-get update $ sudo apt-get upgrade $ sudo apt-get install spyder python3-matplotlib $ sudo apt-get install python3-scipy python3-pandas Bibek Gautam Intro to Programming: With Python 4/38
  5. 2. Setting up Environment Installing python On Windows Download and

    install Anaconda https://www.anaconda.com/distribution/ Bibek Gautam Intro to Programming: With Python 5/38
  6. 3. Thinking like a programmer. What you’ll need.. Input Get

    data from the keyboard, a file, the internet, or some other devices. Output Display information on the screen, save it in a file, send it over the network, etc. Maths Perform basic mathematical operations like addition, multipli- cation, etc. Conditional Execution Check for certain conditions and run the appropriate code. Repetition Perform some action repeatedly, usually with some variation. Bibek Gautam Intro to Programming: With Python 6/38
  7. 3. Thinking like a programmer. What you’ll need.. Input Get

    data from the keyboard, a file, the internet, or some other devices. Output Display information on the screen, save it in a file, send it over the network, etc. Maths Perform basic mathematical operations like addition, multipli- cation, etc. Conditional Execution Check for certain conditions and run the appropriate code. Repetition Perform some action repeatedly, usually with some variation. Bibek Gautam Intro to Programming: With Python 6/38
  8. 3. Thinking like a programmer. What you’ll need.. Input Get

    data from the keyboard, a file, the internet, or some other devices. Output Display information on the screen, save it in a file, send it over the network, etc. Maths Perform basic mathematical operations like addition, multipli- cation, etc. Conditional Execution Check for certain conditions and run the appropriate code. Repetition Perform some action repeatedly, usually with some variation. Bibek Gautam Intro to Programming: With Python 6/38
  9. 3. Thinking like a programmer. What you’ll need.. Input Get

    data from the keyboard, a file, the internet, or some other devices. Output Display information on the screen, save it in a file, send it over the network, etc. Maths Perform basic mathematical operations like addition, multipli- cation, etc. Conditional Execution Check for certain conditions and run the appropriate code. Repetition Perform some action repeatedly, usually with some variation. Bibek Gautam Intro to Programming: With Python 6/38
  10. 3. Thinking like a programmer. What you’ll need.. Input Get

    data from the keyboard, a file, the internet, or some other devices. Output Display information on the screen, save it in a file, send it over the network, etc. Maths Perform basic mathematical operations like addition, multipli- cation, etc. Conditional Execution Check for certain conditions and run the appropriate code. Repetition Perform some action repeatedly, usually with some variation. Bibek Gautam Intro to Programming: With Python 6/38
  11. 3. Thinking like a programmer. What you’ll need.. Input Get

    data from the keyboard, a file, the internet, or some other devices. Output Display information on the screen, save it in a file, send it over the network, etc. Maths Perform basic mathematical operations like addition, multipli- cation, etc. Conditional Execution Check for certain conditions and run the appropriate code. Repetition Perform some action repeatedly, usually with some variation. Bibek Gautam Intro to Programming: With Python 6/38
  12. 3. Thinking like a programmer. What you’ll need.. Input Get

    data from the keyboard, a file, the internet, or some other devices. Output Display information on the screen, save it in a file, send it over the network, etc. Maths Perform basic mathematical operations like addition, multipli- cation, etc. Conditional Execution Check for certain conditions and run the appropriate code. Repetition Perform some action repeatedly, usually with some variation. Bibek Gautam Intro to Programming: With Python 6/38
  13. 4. Python Basics intro Hello world and comments print("Hello World.")

    print("Hi") # this prints "Hi" ''' Everything within this is comment. This doesn't get evaluated. It's all comments! ''' print("hi") ← Hello World ← inline ← multi-line Bibek Gautam Intro to Programming: With Python 7/38
  14. 4. Python Basics intro Usual Operations + - * /

    # basic arithmetic // # integer division ++ -- # increment += -+ *= # ** # power == != <= >= < > # comparision Order of Operation matters! Bibek Gautam Intro to Programming: With Python 8/38
  15. 4. Python Basics Data types Variables & Data types age

    = 5 # integer height = 123.2 # float college = "SXC" # string isAlumni = True # boolean favNum = 2 + 3j # complex number # and a few more Bibek Gautam Intro to Programming: With Python 9/38
  16. 4. Python Basics Data types Strings name = "John Doe"

    # join strings with + sentence = "My name is " + name +"." print(sentence, end=".") multiLine = ''' This is a string with multiple lines in it ''' How would you print : He said ”I’m Lucky” ? print("He said \"I'm Lucky\"") ''' \ is a way to escape special meaning (aka escape sequence) ''' Bibek Gautam Intro to Programming: With Python 10/38
  17. 4. Python Basics Data types Strings name = "John Doe"

    # join strings with + sentence = "My name is " + name +"." print(sentence, end=".") multiLine = ''' This is a string with multiple lines in it ''' How would you print : He said ”I’m Lucky” ? print("He said \"I'm Lucky\"") ''' \ is a way to escape special meaning (aka escape sequence) ''' Bibek Gautam Intro to Programming: With Python 10/38
  18. 4. Python Basics Data types Strings name = "John Doe"

    # join strings with + sentence = "My name is " + name +"." print(sentence, end=".") multiLine = ''' This is a string with multiple lines in it ''' How would you print : He said ”I’m Lucky” ? print("He said \"I'm Lucky\"") ''' \ is a way to escape special meaning (aka escape sequence) ''' Bibek Gautam Intro to Programming: With Python 10/38
  19. 4. Python Basics Data types Strings Some useful string methods:

    .split() .replace("," , ".") .find() .count() .isalnum() .int() .isalpha() .isdigit(), .isspace(), .istitle() .startswith(), .endswith() .strip('' .center(20, "=") Bibek Gautam Intro to Programming: With Python 11/38
  20. 4. Python Basics Data types Taking inputs: As simple as

    it gets... age = input("Enter your age: ") print("You've lived for about", int(age)*365, "days!") What if i enter abc’s and not digits? Bibek Gautam Intro to Programming: With Python 12/38
  21. 4. Python Basics Data types Taking inputs: As simple as

    it gets... age = input("Enter your age: ") print("You've lived for about", int(age)*365, "days!") What if i enter abc’s and not digits? Bibek Gautam Intro to Programming: With Python 12/38
  22. 4. Python Basics Data types Practice Here is a problem

    for you to try: Get input from user and print it out by splitting it at space character. x = input(''Enter a line: '') x. split(",") x.join(",") x.replace(",", ";") Bibek Gautam Intro to Programming: With Python 13/38
  23. 4. Python Basics Data types Practice Here is a problem

    for you to try: Get input from user and print it out by splitting it at space character. x = input(''Enter a line: '') x. split(",") x.join(",") x.replace(",", ";") Bibek Gautam Intro to Programming: With Python 13/38
  24. 4. Python Basics Data types Lists • collection of items

    • could be heterogenous • mutable shopping_list = ['tomatoes', 'potatoes', 'apples', 'juice', 'guava'] print("First item:", shopping_list[0]) Bibek Gautam Intro to Programming: With Python 14/38
  25. 4. Python Basics Data types Lists List indexing and splicing

    list[1:3] # from index 1 to 3 (excluding 3) list[:3] # splicing list[2:] new_list = list[:] # makes a copy list_2 = list # giving another name Bibek Gautam Intro to Programming: With Python 15/38
  26. 4. Python Basics Data types Lists List inside of list

    matrix = [[1,2,3], [4,5,6], [7,8,9]] print(matrix[1][0]) # this prints 6 ! matrix.append([10,11,12]) # now matrix is 4*3 matrix.insert(2,[2, 2, 3]) # inserts new row at index 2 a = [1, 4, 5] matrix = matrix + a # combining to lists. Bibek Gautam Intro to Programming: With Python 16/38
  27. 4. Python Basics Data types Lists Some list useful methods:

    list.sort() list.reverse() # sorting sorted() # returns an iterable of sorted items del(list[4]) # delete item at index 4 max() and min() # first and last for non numbers) Bibek Gautam Intro to Programming: With Python 17/38
  28. 4. Python Basics Data types Lists Some more list useful

    methods: list = [3,1,4] len(list) # length of the list (returns 3) a = 3 in list # a is True now # item in list evaluates to either true or false. .find() .search() .replace() Bibek Gautam Intro to Programming: With Python 18/38
  29. 4. Python Basics Data types Lists string are almost like

    lists ! Bibek Gautam Intro to Programming: With Python 19/38
  30. 4. Python Basics Data types Tuples What are tuples? •

    list that cant be changed. • fixed length, can’t be appended or deleted. • comparable to struct in C • takes less memory and is faster • list() and tuple() function to go back and forth between lists and tuple point = (x, y) student = (name, roll, enrollYr) # they can be sliced just like lists student[0] # gives name of student point[1] # gives y co-ordinate of point Bibek Gautam Intro to Programming: With Python 20/38
  31. 4. Python Basics Data types Tuples What are tuples? •

    list that cant be changed. • fixed length, can’t be appended or deleted. • comparable to struct in C • takes less memory and is faster • list() and tuple() function to go back and forth between lists and tuple point = (x, y) student = (name, roll, enrollYr) # they can be sliced just like lists student[0] # gives name of student point[1] # gives y co-ordinate of point Bibek Gautam Intro to Programming: With Python 20/38
  32. 4. Python Basics Data types Dictionary • Dictionary stores key-value

    pair data • also known as hash table, look-up table in other languages >>> >>> capitals = {"Nepal": "Kathmandu", "India": "New Delhi", "Pakistan": "Islamabad"} >>> capital["Pakistan"] # returns Islamabad >>> capital["France"] = "Rome" >>> del(capital["France"]) # as you'd expect Bibek Gautam Intro to Programming: With Python 21/38
  33. 4. Python Basics Data types Dictionary • Dictionary stores key-value

    pair data • also known as hash table, look-up table in other languages >>> >>> capitals = {"Nepal": "Kathmandu", "India": "New Delhi", "Pakistan": "Islamabad"} >>> capital["Pakistan"] # returns Islamabad >>> capital["France"] = "Rome" >>> del(capital["France"]) # as you'd expect Bibek Gautam Intro to Programming: With Python 21/38
  34. 4. Python Basics Data types Dictionary • Dictionary stores key-value

    pair data • also known as hash table, look-up table in other languages >>> >>> capitals = {"Nepal": "Kathmandu", "India": "New Delhi", "Pakistan": "Islamabad"} >>> capital["Pakistan"] # returns Islamabad >>> capital["France"] = "Rome" >>> del(capital["France"]) # as you'd expect Bibek Gautam Intro to Programming: With Python 21/38
  35. 4. Python Basics Data types Dictionary Some dictionary methods: >>>

    len(dict) >>> dict.keys() >>> dict.values() Bibek Gautam Intro to Programming: With Python 22/38
  36. 4. Python Basics Conditionals Conditionals - if/else When your code

    requires decision making based on conditions >>> if age > 16: ... print("You're old enough to drive") ... elif age > 25: ... print("You're old enough to get married") ... else: ... print("You're not old enough to drive or get married.") Python also has keywords like: and, or, not, True, False Bibek Gautam Intro to Programming: With Python 23/38
  37. 4. Python Basics Loops Loops • loops are for when

    you have to execute a block of code multiple times. • there are two modes of loops: for and while loop. Bibek Gautam Intro to Programming: With Python 24/38
  38. 4. Python Basics Loops Loops Figure: Basic Logic of Loop

    Bibek Gautam Intro to Programming: With Python 24/38
  39. 4. Python Basics Loops For loop • For loop iterates

    through a collection of iterables object or generator function • for eg. a list is an iterable and so is a string • dictionary is also an iterable What are generator functions? • range() is an example • another is open() which is used to open files. We’ll come to this later. Bibek Gautam Intro to Programming: With Python 25/38
  40. 4. Python Basics Loops For loop • For loop iterates

    through a collection of iterables object or generator function • for eg. a list is an iterable and so is a string • dictionary is also an iterable What are generator functions? • range() is an example • another is open() which is used to open files. We’ll come to this later. Bibek Gautam Intro to Programming: With Python 25/38
  41. 4. Python Basics Loops For loop • For loop iterates

    through a collection of iterables object or generator function • for eg. a list is an iterable and so is a string • dictionary is also an iterable What are generator functions? • range() is an example • another is open() which is used to open files. We’ll come to this later. Bibek Gautam Intro to Programming: With Python 25/38
  42. 4. Python Basics Loops For loop • For loop iterates

    through a collection of iterables object or generator function • for eg. a list is an iterable and so is a string • dictionary is also an iterable What are generator functions? • range() is an example • another is open() which is used to open files. We’ll come to this later. Bibek Gautam Intro to Programming: With Python 25/38
  43. 4. Python Basics Loops For loop Let’s talk about range()

    Figure: for loop with range Bibek Gautam Intro to Programming: With Python 26/38
  44. 4. Python Basics Loops For loop Let’s talk about range()

    Figure: for loop with range range(s, e, stp) with start, end, and step Bibek Gautam Intro to Programming: With Python 26/38
  45. 4. Python Basics Loops Loops Some more range: for i

    in range(1,11): print i for i in range(1,21,2): print i for i in range(11, 1, -1): # doesn't include i print i Bibek Gautam Intro to Programming: With Python 27/38
  46. 4. Python Basics Loops Loops Looping through lists for item

    in list: print(item) But, what if you have multiple dimensional array ?? That’s when you need nested loops ! Bibek Gautam Intro to Programming: With Python 28/38
  47. 4. Python Basics Loops Loops Looping through lists for item

    in list: print(item) But, what if you have multiple dimensional array ?? That’s when you need nested loops ! Bibek Gautam Intro to Programming: With Python 28/38
  48. 4. Python Basics Loops Loops Looping through lists for item

    in list: print(item) But, what if you have multiple dimensional array ?? That’s when you need nested loops ! Bibek Gautam Intro to Programming: With Python 28/38
  49. 4. Python Basics Loops Nesting Loops Nesting means using loops

    inside of loops : list_of_lists = [ [1,2,3], [4,5,6], [7,8,9] ] for list in list_of_lists: for item in list: print(item) # above prints 1 through 9 when done Bibek Gautam Intro to Programming: With Python 29/38
  50. 4. Python Basics Loops While loop When you want to

    do something untill a certain condition is true use while loops • Use while loop when you dont have a tidy data structure to iterate through • or don’t have a relevant generator function. • when you want to decide when to stop from within the loop • Let’s see what I mean! Bibek Gautam Intro to Programming: With Python 30/38
  51. 4. Python Basics Loops While loop When you want to

    do something untill a certain condition is true use while loops • Use while loop when you dont have a tidy data structure to iterate through • or don’t have a relevant generator function. • when you want to decide when to stop from within the loop • Let’s see what I mean! Bibek Gautam Intro to Programming: With Python 30/38
  52. 4. Python Basics Loops While loop How many perfect cube

    numbers are less than 100000? this_many = 0 # this counts the number of cube numbers found cuberoot = 1 while cuberoot**3 < 100000: this_many += 1 cuberoot += 1 print(this_many) # executes when the loop completes. Bibek Gautam Intro to Programming: With Python 31/38
  53. 4. Python Basics Loops While loop How many perfect cube

    numbers are less than 100000? this_many = 0 # this counts the number of cube numbers found cuberoot = 1 while cuberoot**3 < 100000: this_many += 1 cuberoot += 1 print(this_many) # executes when the loop completes. Bibek Gautam Intro to Programming: With Python 31/38
  54. 4. Python Basics Functions Functions About functions: • Functions are

    similar to what we understand from maths. • Functions take some input(s) and return some ouput(s) • input and output could be different type of data Why use functions? • Functions allow us to divide the problem into logical chunks of sub-problems that we can separately deal with. • makes code more readable and more structured! • makes debugging easy ! Bibek Gautam Intro to Programming: With Python 32/38
  55. 4. Python Basics Functions Functions About functions: • Functions are

    similar to what we understand from maths. • Functions take some input(s) and return some ouput(s) • input and output could be different type of data Why use functions? • Functions allow us to divide the problem into logical chunks of sub-problems that we can separately deal with. • makes code more readable and more structured! • makes debugging easy ! Bibek Gautam Intro to Programming: With Python 32/38
  56. 4. Python Basics Functions Functions About functions: • Functions are

    similar to what we understand from maths. • Functions take some input(s) and return some ouput(s) • input and output could be different type of data Why use functions? • Functions allow us to divide the problem into logical chunks of sub-problems that we can separately deal with. • makes code more readable and more structured! • makes debugging easy ! Bibek Gautam Intro to Programming: With Python 32/38
  57. 4. Python Basics Functions Functions About functions: • Functions are

    similar to what we understand from maths. • Functions take some input(s) and return some ouput(s) • input and output could be different type of data Why use functions? • Functions allow us to divide the problem into logical chunks of sub-problems that we can separately deal with. • makes code more readable and more structured! • makes debugging easy ! Bibek Gautam Intro to Programming: With Python 32/38
  58. 4. Python Basics Functions Functions About functions: • Functions are

    similar to what we understand from maths. • Functions take some input(s) and return some ouput(s) • input and output could be different type of data Why use functions? • Functions allow us to divide the problem into logical chunks of sub-problems that we can separately deal with. • makes code more readable and more structured! • makes debugging easy ! Bibek Gautam Intro to Programming: With Python 32/38
  59. 4. Python Basics Functions Functions About functions: • Functions are

    similar to what we understand from maths. • Functions take some input(s) and return some ouput(s) • input and output could be different type of data Why use functions? • Functions allow us to divide the problem into logical chunks of sub-problems that we can separately deal with. • makes code more readable and more structured! • makes debugging easy ! Bibek Gautam Intro to Programming: With Python 32/38
  60. 4. Python Basics Functions Functions About functions: • Functions are

    similar to what we understand from maths. • Functions take some input(s) and return some ouput(s) • input and output could be different type of data Why use functions? • Functions allow us to divide the problem into logical chunks of sub-problems that we can separately deal with. • makes code more readable and more structured! • makes debugging easy ! Bibek Gautam Intro to Programming: With Python 32/38
  61. 4. Python Basics Functions Functions Let’s see an example def

    toPercent(num, denum): ''' Takes a fraction and returns equivalent percentage ''' percent = num/denum * 100 percent = int(percent) return percent # return is used to output print("4/5 = ", toPercent(4,5), "%.") Bibek Gautam Intro to Programming: With Python 33/38
  62. 4. Python Basics Functions Namescope • Namescope is like a

    dictionary that maps variable names to their values • Every function has its own namespace. • which means variable declared in one function can’t be accessed from another. Bibek Gautam Intro to Programming: With Python 34/38
  63. 5. Object Oriented Programming with Python Overview OOP Figure: OOP

    in Games Bibek Gautam Intro to Programming: With Python 35/38
  64. 5. Object Oriented Programming with Python Objects heirarchy Figure: Objects

    and inheritence Bibek Gautam Intro to Programming: With Python 36/38
  65. 5. Object Oriented Programming with Python Objects heirarchy Attributes and

    methods Variables encapculated inside a class are its attributes. And functions encapculated within a class are called its methods. Parent Class The class above a class in class heirarchy is called its parent. Child class The classes that derive from a class are its children. Inheritence Child class retains all the methods and attributes from the parents. This is known as inheritence. Bibek Gautam Intro to Programming: With Python 37/38
  66. 5. Object Oriented Programming with Python To be continued... Thank

    You! Bibek Gautam Intro to Programming: With Python 38/38