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

Introduction to Python Programming

Introduction to Python Programming

A workshop on basics of Python programming language

Avatar for Ramkishore M

Ramkishore M

February 01, 2017

Other Decks in Programming

Transcript

  1. Exercise 1 Swap the values of 2 variables(x,y) without using

    a third variable x = 5 ; y = 72 Make it x = 72 and y = 5 without using a new variable
  2. Let’s get the obligatory details out of the way •

    Founded by Guido Van Rossum • Developed for public use by Python Software Foundation • Has been around since Feb 20, 1991 • Free and Open-source with community based development • Used primarily in ◦ Robotics ◦ Web Development (Django, Flask etc.,) ◦ Scripting (Desktop scripts, Hacking etc.,) ◦ Data Science
  3. Key Stuff to know • Built-in memory management (No pointers,

    memory leaks to worry about. yayy!) • Dynamic typing (Just do x = 5. No need to declare type. More on this later) • Strict Indentation Language (Indentation is not optional. It is used by python interpreter to identity code blocks • Python 3 has some syntax differences from Python 2 and is not backwards compatible (We will learn Python 3. You can pick up python 2 easily later if needed)
  4. Syntax overlook - Lot of focus on Readability, Explicitness •

    Base types ◦ Numerical (int, float) ◦ Text (str) ◦ Boolean (True or False) ◦ No Value (None) • Structures ◦ Lists (list) ◦ Tuples (tuple) ◦ Dictionaries (dict) Data types, Structures
  5. Exercise 2 Calculate simple interest for principle Rs.30,000 and interest

    per month of 1.5%. Also calculate balance amount to pay after 5 months to payback in full if you have paid Rs.12,000 so far.
  6. Syntax overlook - Lot of focus on Readability, Explicitness •

    Python is a strict-indentation language. • Indentation is used by the interpreter to isolate code blocks like conditional statements and loops. • Make sure you use spaces (4 or 8 is the norm). Using tabs usually leads to errors. Indentation
  7. Syntax - Conditional Code Flow • Similar to other languages

    python uses if, elif, else to control the flow of a program based on conditions • Follow the if, elif keywords with the condition you want to test
  8. Exercise 3 Find if a year is leap year or

    not 1. Set year value 2. If the number is divisible by 4, it is a leap year 3. But, if it is divisible by 100, it is not a leap year 4. But, but, if it is divisible by 400, it is a leap year
  9. Exercise 3 solution if year%4==0: if year%100==0: if year%400==0: print

    ("It's a leap year") else: print ("Not a leap year") else: print ("It's a leap year") else: print ("Not a leap year")
  10. Syntax - Lists, Tuples • Lists can contain one or

    more values of same or different data types. • Retrieve individual items using [ ] operator like arrays in other languages. Index starts at 0. • Tuples are similar to lists but you cannot add items to them or assign element values individually (immutable)
  11. Syntax - Looping • for loops are more readable in

    python and hence a bit different and used to iterate over elements or a range. • while loops are also an option in cases of looping under a specific condition • Interrupt loop prematurely using break statement
  12. Exercise 4 Write a Python program to change the position

    of every n-th value with the (n+1)th in a list. Sample list: [0,1,2,3,4,5] Expected Output: [1, 0, 3, 2, 5, 4] Hint: range(0, list_size, step)
  13. Exercise 4 solution lis = [0,1,2,3,4,5] for i in range(0,

    len(lis), 2): lis[i], lis[i+1] = lis[i+1], lis[i]
  14. Syntax - Getting Input from user • argv list inside

    sys module contains the values of command-line arguments • sys.argv[0] contains the name of the file • sys.argv[1] contains the first argument • input() to get user input during runtime
  15. Exercise 5 Get 2 integers through command-line arguments, one with

    runtime input and find the biggest of the 3 numbers.
  16. Exercise 5 solution import sys value1, value2 = sys.argv[0], sys.argv[1]

    value3 = input('Enter 3rd number:') print max([value1, value2, value3])
  17. Slice and Dice, the pythonic way • Slicing is one

    of those things that make python what it is • More specific way to index lists • List_name[x:y:z]. • x -> start index • y -> end index + 1 • z -> step
  18. Exercise 6 Generate a list where the values are square

    of numbers between 1 and 20 (both included). Then print the first 5 elements in the list and the last two.
  19. Dictionaries • Dictionaries or dicts are the most used python

    data structure • Map values of a list to meaningful keys instead of sequential indices • Retrieve values by indexing with key • Interpreter reads elements in a pseudo arbitrary order
  20. Exercise 7 Generate a dictionary containing months on the calendar

    as keys and number of characters in the month as values. Start by manually creating a list of months. Print the dictionary.
  21. Exercise 7 solution month_list = ['January', 'February', 'March', 'April', 'May',

    'June', 'July', 'August', 'September', 'October', 'November', 'December'] month_dict = {} for month in month_list: month_dict[month] = len(month) print (month_dict)
  22. Functions • Blocks of code to be reused multiple times

    • Declared with def function_name(arguments = default_values): • Use return statement to return a value (optional) • Called using function_name(arguments)
  23. Exercise 8 solution def is_prime(num): # prime numbers are greater

    than 1 if num > 1: # check for factors for i in range(2,num): if (num % i) == 0: print(num,"is not a prime number") break # remember breaking loop prematurely else: print(num,"is a prime number") else: print(num,"is not a prime number") # not prime if <= 1
  24. Mini Project - Guess my number The program will first

    randomly generate a 2-digit number unknown to the user. The user needs to guess what that number is. (In other words, the user needs to be able to input information.) If the user’s guess is wrong, the program should return some sort of indication as to how wrong (e.g. The number is too high or too low). If the user guesses correctly, a positive indication should appear. You’ll need functions to see the difference between the inputted number and the randomly generated numbers, and to then compare the numbers. Hint: import random random.randint(start, end) Extension: Show useful message if user enters invalid data (eg: not a number)
  25. Mini Project - Guess my movie name Despite the name,

    the actual “hangman” part isn’t necessary. The main goal here is to create a sort of “guess the word” game. The user needs to be able to input letter guesses. A limit should also be set on how many guesses they can use. This means you’ll need a way to grab a word to use for guessing. (Use a name of a mainstream english movie). You will also need functions to check if the user has actually inputted a single letter, to check if the inputted letter is in the hidden word (and if it is, how many times it appears), to print letters, and a counter variable to limit guesses.