Basic Python Revision Notes With help from Nitish Mittal

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

Python. Karin Lagesen.

Introduction to Python

PYTHON FOR MEDICAL PHYSICISTS. Radiation Oncology Medical Physics Cancer Care Services, Royal Brisbane & Women s Hospital

LISTS WITH PYTHON. José M. Garrido Department of Computer Science. May College of Computing and Software Engineering Kennesaw State University

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

Selection Statement ( if )

Introduction to programming using Python

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

Fundamentals of Programming (Python) Object-Oriented Programming. Ali Taheri Sharif University of Technology Spring 2018

CS 234 Python Review Part 2

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

#5: Strings, Lists Reading: Chapter 4 and 5

University of Washington CSE 140 Introduction to Data Programming Winter Midterm exam. February 6, 2013

Real Python: Python 3 Cheat Sheet

Conditional Expressions and Decision Statements

GE PROBLEM SOVING AND PYTHON PROGRAMMING. Question Bank UNIT 1 - ALGORITHMIC PROBLEM SOLVING

Python for Non-programmers

Chapter 8 Dictionaries. Dictionaries are mutable, unordered collections with elements in the form of a key:value pairs that associate keys to values.

Advanced Algorithms and Computational Models (module A)

Introduction to Python

Compound Data Types 2

There are four numeric types: 1. Integers, represented as a 32 bit (or longer) quantity. Digits sequences (possibly) signed are integer literals:

Data Handing in Python

Sequences and Loops. Indices: accessing characters in a string. Old friend: isvowel. Motivation: How to count the number of vowels in a word?

Types, lists & functions

Downloaded from Chapter 2. Functions

CMPT 120 Lists and Strings. Summer 2012 Instructor: Hassan Khosravi

ENGR 102 Engineering Lab I - Computation

ENGR 101 Engineering Design Workshop

Princeton University COS 333: Advanced Programming Techniques A Subset of Python 2.7

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

Python. Executive Summary

Introduction to Computer Programming CSCI-UA 2. Review Midterm Exam 1

Introduction to Python

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

Python Lists: Example 1: >>> items=["apple", "orange",100,25.5] >>> items[0] 'apple' >>> 3*items[:2]

UNIVERSITÀ DI PADOVA. < 2014 March >

Student Number: Comments are not required except where indicated, although they may help us mark your answers.

Sequences and Loops. Indices: accessing characters in a string. Old friend: isvowel. Motivation: How to count the number of vowels in a word?

Variable and Data Type I

About the Final. Saturday, 7-10pm in Science Center 101. Closed book, closed notes. Not on the final: graphics, file I/O, vim, unix

Overview of List Syntax

Data Structures. Dictionaries - stores a series of unsorted key/value pairs that are indexed using the keys and return the value.

CSCE 110: Programming I

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

Introduction to Python

Data Structures. Lists, Tuples, Sets, Dictionaries

Advanced Python. Executive Summary, Session 1

Python Class-Lesson1 Instructor: Yao

Lists, loops and decisions

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

Control flow statements

Chapter 4 : Informatics Practices. Data Handling. Class XI ( As per CBSE Board) Visit : python.mykvs.in for regular updates

Sequences and iteration in Python

The Pyth Language. Administrivia

Python: common syntax

1 Docstrings. COSC 101 Lecture #14 Handout: Defining Functions, Part 4 Spring 2015

Question 1. CSC 120H1 F Midterm Test Solutions Fall 2017

Announcements. Lecture Agenda. Class Exercise. Hashable. Mutability. COMP10001 Foundations of Computing Iteration

CS S-02 Python 1. Most python references use examples involving spam, parrots (deceased), silly walks, and the like

Script language: Python Data structures

Variable and Data Type I

Part I. Wei Tianwen. A Brief Introduction to Python. Part I. Wei Tianwen. Basics. Object Oriented Programming

CS Introduction to Computational and Data Science. Instructor: Renzhi Cao Computer Science Department Pacific Lutheran University Spring 2017

Python allows variables to hold string values, just like any other type (Boolean, int, float). So, the following assignment statements are valid:

age = 23 age = age + 1 data types Integers Floating-point numbers Strings Booleans loosely typed age = In my 20s

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

Chapter 3 : Computer Science. Class XI ( As per CBSE Board) Data Handling. Visit : python.mykvs.in for regular updates

Practice Question. Omar Khan / Atif Alvi. October 10, 2016

DM550/DM857 Introduction to Programming. Peter Schneider-Kamp

Sharing, mutability, and immutability. Ruth Anderson UW CSE 160 Spring 2018

VALLIAMMAI ENGINEERING COLLEGE

Part 1 (80 points) Multiple Choice Questions (20 questions * 4 points per question = 80 points)

Dictionaries. Looking up English words in the dictionary. Python sequences and collections. Properties of sequences and collections

Compound Data Types 1

More Loop Examples Functions and Parameters

CS2304: Python for Java Programmers. CS2304: Sequences and Collections

ECS15, Lecture 14. Reminder: how to learn Python. Today is the final day to request a regrade of the midterm. Topic 4: Programming in Python, cont.

(CC)A-NC 2.5 by Randall Munroe Python

WELCOME CSCA20 REVIEW SEMINAR

Lists How lists are like strings

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

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

Python and Bioinformatics. Pierre Parutto

CSC148 Fall 2017 Ramp Up Session Reference

Ex: If you use a program to record sales, you will want to remember data:

List of squares. Program to generate a list containing squares of n integers starting from 0. list. Example. n = 12

Python Evaluation Rules

AI Programming CS S-02 Python

Comp Exam 1 Overview.

Chapter 6: List. 6.1 Definition. What we will learn: What you need to know before: Data types Assignments

Final Exam(sample), Fall, 2014

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

Lab1. Introduction to Python. Lab 4: Selection Statement. Eng. Mai Z. Alyazji

Python for ArcGIS. Lab 1.

List Processing Patterns and List Comprehension

Professor: Sana Odeh Lecture 3 Python 3.1 Variables, Primitive Data Types & arithmetic operators

Chapter 2: Using Data

Algorithmic Thinking: Computing with Lists

Transcription:

Basic Python Revision Notes With help from Nitish Mittal HELP from Documentation dir(module) help() Important Characters and Sets of Characters tab \t new line \n backslash \\ string " " or ' ' docstring """ """ comparison operators ==, <, >, <=, >=,!= Python type boolean True, False. Logical operators not, and, or Order of Operations (from Emory) Operator Description () Parentheses (grouping) f(args...) Function call x[index:index] Slicing x[index] Subscription x.attribute Attribute reference ** Exponentiation +x, -x Positive, negative *, /, % Multiplication, division, remainder +, - Addition, subtraction in, not in, is, is not, <, <=, >, >=, Comparisons, membership, identity <>,!=, == not x Boolean NOT and Boolean AND or Boolean OR

Variable Names case sensitive cannot start with a number (ex, 1_assd is not allowed) Six Steps to Defining a Function 1. What should your function do? Type a couple of example calls. 2. Pick a meaningful name (often a verb or verb phrase): What is a short answer to "What does your function do"? 3. Decide how many parameters the function takes and any return values 4. Describe what your function does and any parameters and return values in the docstring 5. Write the body of the function 6. Test your function. Think about edge cases. Integers and Strings >>> int(45) 45 >>> int('45') 45 >>> str(45) '45' >>> str('45') '45' >>> int(str(45)) 45 Calling Methods module_name.function_name(x) math.sqrt(x) random.randrange(2,5) Conditionals and Branching if elif else We have a boolean logic expression for if which works when the Boolean evaluates to True

String Operators Description Operator Example Output equality == 'cat' == 'cat' True inequality!= 'cat'!= 'Cat' True less than < 'A' < 'a' True greater than > 'a' > 'A' True less than or equal <= 'a' <= 'a' True greater than or equal >= 'a' >= 'A' True contains in 'cad' in 'abracadabra' True length of str s len(s) len("abc") 3 String Indexing and Slicing (s[a:b] means index a to length (b-a) or a to b index but not including b) s[2:3] s[0] s[:5] s[4:] String is immutable (ex. s[4]='a' will not replace 'a' and index 4 of s) String Methods A method is a function inside of an object. The general form of a method call is: o object.method(arguments) o dir(str) o help(str.method) for Loops num_vowels = 0 for char in s: if char in 'aeiouaeiou': num_vowels = num_vowels + 1 print num_vowels vowels = '' for char in s: if char in 'aeiouaeiou': vowels = vowels + char print vowels

Lists Like for strings, slicing and indexing can also be used for lists List = ['a','b',1] length of list len(list) smallest element in list min(list) largest element in list max(list) sum of elements of list (where list items must be numeric) sum(list) >>> a=[1,'ab',2,'pq'] >>> a[1][0] 'a' >>> a[1][1] 'b' >>> a[3][1] 'q' >>> a[3][2] List Methods append a value or string list.append('a') extended by another list list.extend(['a', 'b']) >>> a = [5] + [6] + ['a',7] >>> print (a) [5, 6, 'a', 7] List Mutability We say that lists are mutable: they can be modified. >>> lst = [1, 2, 3] >>> lst[0] = 'apple' >>> lst ['appple, 2, 3]

List Aliasing Consider the following code: >>> lst1 = [11, 12, 13, 14, 15, 16, 17] >>> lst2 = lst1 >>> lst1[-1] = 18 >>> lst2 [11, 12, 13, 14, 15, 16, 18] After the second statement executes, lst1 and lst2 both refer to the same list. When two variables refer to the same objects, they are aliases. If that list is modified, both of lst1 and lst2 will see the change. But be careful about: >>> lst1 = [11, 12, 13, 14, 15, 16, 17] >>> lst2 = lst1 >>> lst1 = [5, 6] >>> lst2 [11, 12, 13, 14, 15, 16, 17] And also: >>> lst1 = [1,2,3] >>> lst2 = lst1[:] >>> lst2.remove(2) >>> lst1 [1,2,3] while Loops i = 0 while i < len(s) and not (s[i] in 'aeiouaeiou'): print(s[i]) i = i + 1 for char in s: if not (char in 'aeiouaeiou'): print(char) The difference between the two is that the for loop looks at every character in s, but the while loop ends as soon a vowel is found. So the loops differ on any string where a consonant follows a vowel. while is an if statement in motion. It is a repeated loop until the boolean test evaluates to False.

def secret(s): i = 0 result = '' while s[i].isdigit(): result = result + s[i] i = i + 1 print result >>> secret('123') will give an error message when it runs the fourth time. Global and Local Variables Variables defined outside functions are global variables. Their values may be accessed inside functions without declaration. To modify to a global variable inside a function, the variable must be declared inside the function using the keyword global. def x(): global num num = 5 def y(): num = 4 >>> num = 7 >>> print (num) 7 >>> x() >>> print (num) 5 >>> y() >>> print (num) 5 Dictionaries The values of a dictionary can be of any type, but the keys must be of an immutable data type such as strings, numbers, or tuples. keys can be numbers, strings, Booleans o a list is unhashable in a dictionary (cannot be used as a key) o a tuple is hashable in a dictionary (can be used as a key). values can be dicts, strings, numbers, booleans, lists for key in my_dict: value = my_dict[key] This is same as: for key, value in my_dict.items():