Python BASICS. Introduction to Python programming, basic concepts: formatting, naming conventions, variables, etc.

Similar documents
STEAM Clown & Productions Copyright 2017 STEAM Clown. Page 1

Programming for AmI MOTIVATIONS AND GOALS

CSCE 110 Programming I Basics of Python: Variables, Expressions, Input/Output

CHAPTER 2: Introduction to Python COMPUTER PROGRAMMING SKILLS

Python INTERMEDIATE. Rapid prototyping using Python libraries and integration with local and remote services

Beyond Blocks: Python Session #1

Basic Concepts. Computer Science. Programming history Algorithms Pseudo code. Computer - Science Andrew Case 2

CSCE 110 Programming I

Getting Started with Python

Fundamentals of Programming (Python) Getting Started with Programming

Outline. Simple types in Python Collections Processing collections Strings Tips. 1 On Python language. 2 How to use Python. 3 Syntax of Python

ENGR 101 Engineering Design Workshop

Chapter 3 : Informatics Practices. Class XI ( As per CBSE Board) Python Fundamentals. Visit : python.mykvs.in for regular updates

PROGRAMMING FUNDAMENTALS

Algorithms and Programming I. Lecture#12 Spring 2015

Python Programming: Lecture 2 Data Types

CSCA20 Worksheet Strings

Variables, expressions and statements

The current topic: Python. Announcements. Python. Python

Lab 1: Course Intro, Getting Started with Python IDLE. Ling 1330/2330 Computational Linguistics Na-Rae Han

The Three Rules. Program. What is a Computer Program? 5/30/2018. Interpreted. Your First Program QuickStart 1. Chapter 1

Jython. secondary. memory

GIS 4653/5653: Spatial Programming and GIS. More Python: Statements, Types, Functions, Modules, Classes

Python language: Basics

Motivations. Luigi De Russis. Why Ruby (on Rails)?

Control flow statements

APT Session 2: Python

Table of Contents EVALUATION COPY

Python I. Some material adapted from Upenn cmpe391 slides and other sources

SD314 Outils pour le Big Data

Ruby AN OVERVIEW. Luigi De Russis Dipartimento di Automatica e Informatica Politecnico di Torino

Programming in Python

Interactive use. $ python. >>> print 'Hello, world!' Hello, world! >>> 3 $ Ctrl-D

D R S H YA M N C H AW D A

Introduction to Python

Brush up Python. December 20, 2018

PRG PROGRAMMING ESSENTIALS. Lecture 2 Program flow, Conditionals, Loops

Interactive use. $ python. >>> print 'Hello, world!' Hello, world! >>> 3 $ Ctrl-D

Introduction to Python! Lecture 2

There are two ways to use the python interpreter: interactive mode and script mode. (a) open a terminal shell (terminal emulator in Applications Menu)

Compound Data Types 1

Programming to Python

MEIN 50010: Python Introduction

Getting Started. Office Hours. CSE 231, Rich Enbody. After class By appointment send an . Michigan State University CSE 231, Fall 2013

Introduction to Python

Constants. Variables, Expressions, and Statements. Variables. x = 12.2 y = 14 x = 100. Chapter

Begin to code with Python Obtaining MTA qualification expanded notes

Lecture 7: Python s Built-in. in Types and Basic Statements

Python for Analytics. Python Fundamentals RSI Chapters 1 and 2

Python review. 1 Python basics. References. CS 234 Naomi Nishimura

Worksheet 6: Basic Methods Methods The Format Method Formatting Floats Formatting Different Types Formatting Keywords

Basic Syntax - First Program 1

Sequence types. str and bytes are sequence types Sequence types have several operations defined for them. Sequence Types. Python

OOP and Scripting in Python Advanced Features

Chapter 2 Writing Simple Programs

Introduction to Python

Lecture 27. Lecture 27: Regular Expressions and Python Identifiers

Visualize ComplexCities

Accelerating Information Technology Innovation

Python at Glance. a really fast (but complete) ride into the Python hole. Paolo Bellagente - ES3 - DII - UniBS

Control Structures 1 / 17

CMSC 201 Computer Science I for Majors

Python Programming, bridging course 2011

Expressions and Variables

Variables, Expressions, and Statements

Here n is a variable name. The value of that variable is 176.

Variable and Data Type I

And Parallelism. Parallelism in Prolog. OR Parallelism

Basic Python Revision Notes With help from Nitish Mittal

Python workshop. Week 2: Make choices and reuse code.

Revision of Basics of Python

DATA 301 Introduction to Data Analytics Python. Dr. Ramon Lawrence University of British Columbia Okanagan

CS177 Recitation. Functions, Booleans, Decision Structures, and Loop Structures

(CC)A-NC 2.5 by Randall Munroe Python

UNIVERSITÀ DI PADOVA. < 2014 March >

nostarch.com/pfk For bulk orders, please contact us at

Introduction to Python Code Quality

06/11/2014. Subjects. CS Applied Robotics Lab Gerardo Carmona :: makeroboticsprojects.com June / ) Beginning with Python

Download Python from Any version will do for this class

Some material adapted from Upenn cmpe391 slides and other sources

Introduction to Python

Databases in Python. MySQL, SQLite. Accessing persistent storage (Relational databases) from Python code

Data type built into Python. Dictionaries are sometimes found in other languages as associative memories or associative arrays.

4. Write the output that would be printed from each of the following code fragments. (6pts) a = 5 b = 4 temp = a a = b b = temp print(a, b, temp)

Lists, loops and decisions

Lecture 1. basic Python programs, defining functions

Introduction to Python

Lab 4 Fruitful Functions

MAS212 Scientific Computing and Simulation

STEAM Clown Productions. Python-Functions. Page 1

\n is used in a string to indicate the newline character. An expression produces data. The simplest expression

Crash Dive into Python

Python and Bioinformatics. Pierre Parutto

Java for Python Programmers. Comparison of Python and Java Constructs Reading: L&C, App B

Midterm 1 Review. Important control structures. Important things to review. Functions Loops Conditionals

Review. Input, Processing and Output. Review. Review. Designing a Program. Typical Software Development cycle. Bonita Sharif

Chapter 1 Summary. Chapter 2 Summary. end of a string, in which case the string can span multiple lines.

Python. Jae-Gil Lee Based on the slides by K. Naik, M. Raju, and S. Bhatkar. December 28, Outline

Introduction to Scientific Python, CME 193 Jan. 9, web.stanford.edu/~ermartin/teaching/cme193-winter15

Getting Started Values, Expressions, and Statements CS GMU

Transcription:

Python BASICS Introduction to Python programming, basic concepts: formatting, naming conventions, variables, etc.

Identikit First appeared in 1991 Designed by Guido van Rossum General purpose High level Emphasis on code readability and conciseness Website http://www.python.org We will use Python 3 not Python 2 06/03/19 Python basics 2

#include <stdio.h> int main() { } printf("hello, world!"); return 0; 06/03/19 Python basics 3

print("hello, world!") 06/03/19 Python basics 4

inline comment # this will print "Hello, world!" print("hello, world!") 06/03/19 Python basics 5

Keywords and del from not while as elif global or with assert else if pass yield break except import class exec in raise continue finally is return def for lambda try 06/03/19 Python basics 6

Variables this is a string language_name = "Python" naming convention: joined_lower 06/03/19 Python basics 7

Variables language_name = "Python" version = '3.7.0' introduced = 1991 is_awesome = True 06/03/19 Python basics 8

Type Inference play_with_types.py language_name = "Python" # string version = '3.7.0' # another string introduced = 1991 is_awesome = True # integer # boolean actual type can be checked with type() 06/03/19 Python basics 9

String some_string = "I'm a string" another_string = 'I'm a string, too' 06/03/19 Python basics 10

String some_string = "I'm a string" another_string = 'I'm a string, too' # SyntaxError: invalid syntax 06/03/19 Python basics 11

String another_string = 'I am a string, too' another_strig = 'I\'m a string, too' escape sequence 06/03/19 Python basics 12

String long_string = """I am a long string. I span over two lines.""" long_string = '''I am another long string. I span over three lines. I am composed by three sentences.''' 06/03/19 Python basics 13

If Statement people = 20 cats = 30 if people < cats: 4 spaces print("too many cats! We are doomed!") if people > cats: 4 spaces print("not many cats! We are safe!") 06/03/19 Python basics 14

If Statement people = 20 cats = 30 if people < cats: print("too many cats! We are doomed!") elif people > cats: print("not many cats! We are safe!") else: print("we can't decide.") 06/03/19 Python basics 15

Comparators and Booleans Operators print(2 == 1) print('string' == "string") print(not False) print(2==1 and True) print(2==1 or True) 06/03/19 Python basics 16

Comparators and Booleans Operators print(2 == 1) # False print('string' == "string") # True print(not False) # True print(2==1 and True) # False print(2==1 or True) # True 06/03/19 Python basics 17

Characters for char in "hello": print(char) h e l l o 06/03/19 Python basics 18

Characters say_hello = "hello!" print(say_hello[1]) index e 06/03/19 Python basics 19

Characters say_hello = "hello!" print(type(say_hello[1])) <class 'str'> 06/03/19 Python basics 20

Combining Strings language_name = "Python" version = '3.7.0' concatenation python_version = language_name + version # python_version is Python3.7.0 print("my " + "name") # my name 06/03/19 Python basics 21

Combining Strings language_name = "Python" repetition a_lot_of_python = language_name*3 # a_lot_of_python is PythonPythonPython 06/03/19 Python basics 22

Building Complex Strings a = 3 b = 5 # 3 times 5 is 15 print(a, "times", b, "is", a*b) works with print(), only 06/03/19 Python basics 23

Building Complex Strings a = 3 b = 5 # 3 times 5 is 15 result = a + " times " + b + " is " + a*b 06/03/19 Python basics 24

Building Complex Strings a = 3 b = 5 # 3 times 5 is 15 result = a + " times " + b + " is " + a*b #TypeError: unsupported operand type(s) 06/03/19 Python basics 25

Building Complex Strings a = 3 b = 5 # 3 times 5 is 15 result = str(a) + " times " + str(b) + " is " + str(a*b) 06/03/19 Python basics 26

String Interpolation a = 3 b = 5 Specifiers %s, format strings %d, format numbers %r, raw representation # 3 times 5 is 15 result = "%d times %d is %d" %(a, b, a*b) specifiers.py tuple 06/03/19 Python basics 27

String Interpolation a = 3 b = 5 # 3 times 5 is 15 result = "{} times {} is {}".format(a, b, a*b) new way! 06/03/19 Python basics 28

String Immutability # hello say_hello = "helko" # ops say_hello[3] = "l" 06/03/19 Python basics 29

String Immutability # hello say_hello = "helko" # ops say_hello[3] = "l" # TypeError 06/03/19 Python basics 30

String Immutability # hello say_hello = "helko" # ops say_hello = "hello" Other operations with strings? Python docs 06/03/19 Python basics 31

Getting Input print("how old are you?") age = input() # age is a string print("you are " + age + " years old") 06/03/19 Python basics 32

Getting Input print("how old are you?") age = input() # age is a string print("you are " + age + " years old") # I want "age" to be a number! age = int(input()) 06/03/19 Python basics 33

Getting Input age = input("how old are you? ") print("you are " + age + " years old") 06/03/19 Python basics 34

List fruits = ["apples", "oranges", "pears"] count = [1, 2, 3, 4, 5] change = [1, "pennies", 2, "dimes"] a datatype to store multiple items, in sequence 06/03/19 Python basics 35

Dictionary key, immutable value legs = {"ant": 6, "snake": 0, "cow": 4} states = {"Italy": "IT", "Germany": "DE"} a datatype to store multiple items, not in sequence 06/03/19 Python basics 36

Loops doctor = 1 while doctor <= 13: exterminate(doctor) doctor += 1 06/03/19 Python basics 37

For Loop: Strings for char in "hello": print(char) h e l l o 06/03/19 Python basics 38

For Loop: Ranges for number in range(0,5): print(number) 0 1 2 3 4 06/03/19 Python basics 39

For Loop: Ranges for number in range(0,25,5): print(number) 0 5 10 15 20 06/03/19 Python basics 40

For Loop: Lists fruits = ["apples", "oranges", "pears"] for fruit in fruits: print("i love", fruit) I love apples I love oranges I love pears 06/03/19 Python basics 41

For Loop: Dictionaries legs = {"ant": 6, "snake": 0, "cow": 4} for (animal, number) in legs.items(): print("{} has {} legs".format(animal, number)) ant has 6 legs snake has 0 legs cow has 4 legs 06/03/19 Python basics 42

Printing a List to_buy = ["eggs", "milk"] print(to_buy) ['eggs', 'milk'] 06/03/19 Python basics 43

Printing a List to_buy = ["eggs", "milk"] print(to_buy[0]) eggs 06/03/19 Python basics 44

Modifying a List to_buy = ["eggs", "milk"] print(to_buy[0]) to_buy[0] = "butter" print(to_buy[0]) eggs butter 06/03/19 Python basics 45

Modifying a List to_buy = ["eggs", "milk"] # I need to buy chocolate! to_buy.append("chocolate") ['eggs', 'milk', 'chocolate'] 06/03/19 Python basics 46

Modifying a List to_buy = ["eggs", "milk"] to_buy.append("chocolate") to_buy.extend(["flour", "cheese"]) ['eggs', 'milk', 'chocolate', 'flour', 'cheese'] 06/03/19 Python basics 47

Modifying a List to_buy = ["eggs", "milk"] to_buy.append("chocolate") concatenation to_buy = to_buy + ["flour", "cheese"] ['eggs', 'milk', 'chocolate', 'flour', 'cheese'] 06/03/19 Python basics 48

Modifying a List to_buy = ["eggs", "milk", "chocolate", "flour", "cheese"] slice operator print(to_buy[1:3]) ['milk', 'chocolate'] 06/03/19 Python basics 49

Modifying a List to_buy = ["eggs", "milk", "chocolate", "flour", "cheese"] # make a full copy of the list remember = to_buy[:] works with strings, too 06/03/19 Python basics 50

Modifying a List to_buy = ["eggs", "milk", "chocolate", "flour", "cheese"] # I don't need cheese! to_buy.pop() # neither milk, by the way! to_buy.pop(1) 06/03/19 Python basics 51

Modifying a List to_buy = ["eggs", "milk", "chocolate", "flour", "cheese"] # I don't need cheese! to_buy.remove("cheese") # neither milk, by the way! to_buy.remove("milk") 06/03/19 Python basics 52

Modifying a List to_buy = ["eggs", "milk", "chocolate", "flour", "cheese"] # I want my original list back! del to_buy[2:6] ['eggs', 'milk'] 06/03/19 Python basics 53

Strings vs. Lists A string is a sequence of characters but a list of characters is not a string language_name = "Python" # string to list name = list(language_name) 06/03/19 Python basics 54

Strings vs. Lists sentence = "this is AmI" # break a string into separate words words = sentence.split() ['this', 'is', 'AmI'] 06/03/19 Python basics 55

Copying Lists fruits = ['apple', 'orange'] favorite_fruits = fruits # add a fruit to the original list fruits.append('banana') print('the fruits now are:', fruits) print('my favorite fruits are', favorite_fruits) Fruits are: ['apple', 'orange', 'banana'] My favorite fruits are: ['apple', 'orange', 'banana']??? 06/03/19 Python basics 56

Copying Lists fruits = ['apple', 'orange'] favorite_fruits = fruits # add a fruit to the original list fruits.append('banana') We do not make a copy of the entire list, but we only make a reference to it! print('the fruits now are:', fruits) print('my favorite fruits are', favorite_fruits) 06/03/19 Python basics 57

Copying Lists (For Real!) # option 1: slice favorite_fruits = fruits[:] #option 2: create a new list - best! favorite_fruits = list(fruit) #extend an empty list favorite_fruits.extends(fruit) Other operations with lists? Python docs 06/03/19 Python basics 58

Printing a Dictionary legs = {"ant": 6, "snake": 0 } print(legs) {'ant': 6, 'snake': 0} 06/03/19 Python basics 59

Modifying a Dictionary legs = {"ant": 6, "snake": 0 } legs["spider"] = 273 {'ant': 6, 'snake': 0, 'spider': 273} 06/03/19 Python basics 60

Modifying a Dictionary legs = {"ant": 6, "snake": 0 } legs["spider"] = 273 # basically, run! legs["spider"] = 8 # better! {'ant': 6, 'snake': 0, 'spider': 8} 06/03/19 Python basics 61

Modifying a Dictionary legs = {"ant": 6, "snake": 0, "spider": 8} # I don't like spiders del legs["spider"] # Clear all the things! legs.clear() 06/03/19 Python basics 62

Retrieving a Value from a Dictionary legs = {"ant": 6, "snake": 0} # get "ant"! legs["ant"] # 6 # get "spider" legs["spider"] 06/03/19 Python basics 63

Retrieving a Value from a Dictionary legs = {"ant": 6, "snake": 0} # get "ant"! legs["ant"] # 6 # get "spider" legs["spider"] # KeyError: spider 06/03/19 Python basics 64

Retrieving a Value from a Dictionary legs = {"ant": 6, "snake": 0} # check if "spider" is in the dictionary "spider" in legs # False # get "spider" without throwing errors legs.get("spider") # None # get "spider" with a custom value legs.get("spider", "Not present") 06/03/19 Python basics 65

Functions def say_hello(): print("hello!") definition say_hello() call 06/03/19 Python basics 66

Functions with Parameters def say_hello_to(name): print("hello", name) say_hello_to("ami students") 06/03/19 Python basics 67

Default Parameter Values def say_hello_to(name="ami"): print("hello", name) say_hello_to() # Hello AmI say_hello_to("students") # Hello students 06/03/19 Python basics 68

Returning Values def build_greetings(name="ami"): return "Hello" + name greeting = build_greetings() print(greeting) # Hello AmI 06/03/19 Python basics 69

Returning Multiple Values def build_greetings(name="ami"): return ("Hello", name) (greeting, person) = build_greetings() print(greeting + " to " + person) # Hello to AmI 06/03/19 Python basics 70

Documenting Functions def build_greetings(name="ami"): '''Build a greeting in the format Hello plus a given name''' return ("Hello", name) docstring 06/03/19 Python basics 71

Modules A way to logically organize the code They are files consisting of Python code they can define (and implement) functions, variables, etc. typically, the file containing a module is called in the same way e.g., the math module resides in a file named math.py 06/03/19 Python basics 72

Importing a Module import math # import the math module print(math.pi) # print 3.141592 from math import pi # import pi, only! print(pi) # print 3.141592 from math import * # import all the names print(pi) DO NOT USE 06/03/19 Python basics 73

Command Line Parameters from sys import argv script, first = argv unpacking print("the script is called:", script) print("the parameter is:", first) > python my_script.py one The script is called: my_script.py The parameter is: one 06/03/19 Python basics 74

Reading Files from sys import argv filename = argv[1] txt = open(filename) open the file print("here's your file %r:", % filename) print(txt.read()) show the file content 06/03/19 Python basics 75

Writing Files from sys import argv filename = argv[1] # open in write mode and empty the file target = open(filename, "w") # write a string into the file target.write("this is the new content") target.close() # close the file 06/03/19 Python basics 76

References and Links Python Documentation, http://docs.python.org/3 The Python Tutorial, http://docs.python.org/3/tutorial/ Online Python Tutor, http://pythontutor.com «Think Python: How to think like a computer scientist», 2nd edition, Allen Downey, Green Tea Press, Needham, Massachusetts «Dive into Python 3», Mark Pilgrim «Learning Python» (5th edition), Mark Lutz, O'Reilly 06/03/19 Python basics 77

Questions? 01QZP AMBIENT INTELLIGENCE Luigi De Russis luigi.derussis@polito.it

License This work is licensed under the Creative Commons Attribution- NonCommercial-ShareAlike Unported (CC BY-NC-SA 4.0) License. You are free: to Share - to copy, distribute and transmit the work to Remix - to adapt the work Under the following conditions: Attribution - You must attribute the work in the manner specified by the author or licensor (but not in any way that suggests that they endorse you or your use of the work). Noncommercial - You may not use this work for commercial purposes. Share Alike - If you alter, transform, or build upon this work, you may distribute the resulting work only under the same or similar license to this one. To view a copy of this license, visit https://creativecommons.org/licenses/by-nc-sa/4.0/ 06/03/19 Python basics 79