Python Syntax tips Henrike Zschach. 2DTU Systems Biology, Technical University of Denmark Why are we talking about syntax ’Good’ coding Good syntax should.

Slides:



Advertisements
Similar presentations
CATHERINE AND ANNIE Python: Part 3. Intro to Loops Do you remember in Alice when you could use a loop to make a character perform an action multiple times?
Advertisements

COMP 116: Introduction to Scientific Programming Lecture 37: Final Review.
CMSC 330: Organization of Programming Languages Tuples, Types, Conditionals and Recursion or “How many different OCaml topics can we cover in a single.
ECS 15 if and random. Topic  Testing user input using if statements  Truth and falsehood in Python  Getting random numbers.
Computer Science 1620 Loops.
Python Control of Flow.
1 Python Control of Flow and Defining Classes LING 5200 Computational Corpus Linguistics Martha Palmer.
Introduction to Python Lecture 1. CS 484 – Artificial Intelligence2 Big Picture Language Features Python is interpreted Not compiled Object-oriented language.
Lists in Python.
Builtins, namespaces, functions. There are objects that are predefined in Python Python built-ins When you use something without defining it, it means.
1 Session 3: Flow Control & Functions iNET Academy Open Source Web Programming.
 Expression Tree and Objects 1. Elements of Python  Literals, Strings, Tuples, Lists, …  The order of file reading  The order of execution 2.
Meet Perl, Part 2 Flow of Control and I/O. Perl Statements Lots of different ways to write similar statements –Can make your code look more like natural.
Built-in Data Structures in Python An Introduction.
Q and A for Sections 2.9, 4.1 Victor Norman CS106 Fall 2015.
Getting Started with Python: Constructs and Pitfalls Sean Deitz Advanced Programming Seminar September 13, 2013.
Python uses boolean variables to evaluate conditions. The boolean values True and False are returned when an expression is compared or evaluated.
Python Primer 1: Types and Operators © 2013 Goodrich, Tamassia, Goldwasser1Python Primer.
More about Strings. String Formatting  So far we have used comma separators to print messages  This is fine until our messages become quite complex:
CS105 Computer Programming PYTHON (based on CS 11 Python track: lecture 1, CALTECH)
9/21/2015BCHB Edwards Python Data Structures: Lists BCHB Lecture 6.
Xiaojuan Cai Computational Thinking 1 Lecture 8 Loop Structure Xiaojuan Cai (蔡小娟) Fall, 2015.
Loops and Simple Functions CS303E: Elements of Computers and Programming.
1 Printing in Python Every program needs to do some output This is usually to the screen (shell window) Later we’ll see graphics windows and external files.
Loops and Files. 5.1 The Increment and Decrement Operators.
CPSC 217 T03 Week V Part #1: Iteration Hubert (Sathaporn) Hu.
More Sequences. Review: String Sequences  Strings are sequences of characters so we can: Use an index to refer to an individual character: Use slices.
CS 330 Programming Languages 11 / 15 / 2007 Instructor: Michael Eckmann.
September 7, 2004ICP: Chapter 3: Control Structures1 Introduction to Computer Programming Chapter 3: Control Structures Michael Scherger Department of.
Midterm Exam Topics (Prof. Chang's section) CMSC 201.
9. ITERATIONS AND LOOP STRUCTURES Rocky K. C. Chang October 18, 2015 (Adapted from John Zelle’s slides)
Repetition Structures The long awaited …. Repetition Structures I repeat …
Introduction to Programming Oliver Hawkins. BACKGROUND TO PROGRAMMING LANGUAGES Introduction to Programming.
PROGRAMMING INFORMATION. PROCEDURES IN PYTHON Procedures can make code shorter, simpler, and easier to write. If you wanted, for example, to use a certain.
Winter 2016CISC101 - Prof. McLeod1 CISC101 Reminders Quiz 3 next week. See next slide. Both versions of assignment 3 are posted. Due today.
Quiz 3 Topics Functions – using and writing. Lists: –operators used with lists. –keywords used with lists. –BIF’s used with lists. –list methods. Loops.
1 Agenda  Unit 7: Introduction to Programming Using JavaScript T. Jumana Abu Shmais – AOU - Riyadh.
Python Simple file reading Peter Wad Sackett. 2DTU Systems Biology, Technical University of Denmark Simple Pythonic file reading Python has a special.
How to python source: Web_Dev fan on pinterest.
Python – May 18 Quiz Relatives of the list: Tuple Dictionary Set
CMSC201 Computer Science I for Majors Lecture 17 – Dictionaries
Python Comprehension and Generators
Basic operators - strings
Miscellaneous Items Loop control, block labels, unless/until, backwards syntax for “if” statements, split, join, substring, length, logical operators,
While Loops in Python.
CISC101 Reminders Quiz 2 this week.
CISC101 Reminders Quiz 1 grading underway Assn 1 due Today, 9pm.
LING/C SC/PSYC 438/538 Lecture 10 Sandiway Fong.
Context.
T. Jumana Abu Shmais – AOU - Riyadh
CSC 458– Predictive Analytics I, Fall 2018, Intro. To Python
I210 review.
Patterns to KNOW.
Arrays .
Lists in Python Creating lists.
Ruth Anderson UW CSE 160 Winter 2017
Python Data Structures: Lists
Python Tutorial for C Programmer Boontee Kruatrachue Kritawan Siriboon
Python Primer 1: Types and Operators
Python – a HowTo Peter Wad Sackett and Henrike Zschach.
CISC101 Reminders All assignments are now posted.
CISC101 Reminders Assignment 2 due today.
Python Data Structures: Lists
Python Data Structures: Lists
Ruth Anderson CSE 160 University of Washington
And now for something completely different . . .
Ruth Anderson UW CSE 160 Spring 2018
Introduction to Computer Science
Ruth Anderson UW CSE 160 Winter 2016
PYTHON - VARIABLES AND OPERATORS
Presentation transcript:

Python Syntax tips Henrike Zschach

2DTU Systems Biology, Technical University of Denmark Why are we talking about syntax ’Good’ coding Good syntax should be concise while maintaining a maximum level of straightforwardness and readability. While evaluating the exercises I have experienced that many students use syntax that is unnecessarily complicated (in fact so often that I learned how to spell ’unnecessarily’ without looking it up) so I’m going to show some examples of how to make simpler and easier to read code.

3DTU Systems Biology, Technical University of Denmark Initialization Intializing a variable to an emtpy instance and then initializing it again to the desired value. OBS: I’m not talking about initializing to empty and then filling it with a loop or function. #don’t my_dict = dict() my_dict = {'ATT':'I', 'ATC':'I',..., 'TGA':'STOP’} #instead: my_dict = {'ATT':'I', 'ATC':'I',..., 'TGA':'STOP’} So what if I want an empty dict? empty_dict = {} The same applies to lists, strings, ect.

4DTU Systems Biology, Technical University of Denmark List building Task: I have some info in this line that I want to save in a list -> Many build-in functions actually return lists, e.g. split() #don’t data_list = list() for item in line.split(): data_list.append(item) #instead: data_list = line.split() Also, our favorite sys.argv is already a list #don't input_files = list() for index in range(1, len(sys.argv)): input_files.append(sys.argv[index]) #instead input_files = sys.argv[1:] Take advantage of splicing.

5DTU Systems Biology, Technical University of Denmark List building But I want to append to an existing list. -> Ok, so use extend. data_list.extend(line.split()) What is the difference between extend and append? (Pro tip: I also call this ’How to mess up your data structure in one line’.)

6DTU Systems Biology, Technical University of Denmark Abuse of iterators There is no need to create an iterator if you don’t use it. #don't split_line = line.split() for i in range(0,len(split_line)): sum += float(split_line[i]) #instead: for number in line.split(): sum += float(number) Also, you should name your iterable something sensible. This is will enhance readability of your code.

7DTU Systems Biology, Technical University of Denmark ‘Dumping’ complex data structures into print I’ve seen this many times: print(my_list) print(my_dict) Please don't. It's not just a question of aesthetics (thought it is hard to read), your output will be useless to any follow-up analysis or task. There are build-in solutions for printing of lists: print('\n'.join(my_list))

8DTU Systems Biology, Technical University of Denmark Overuse of regex “Some people, when confronted with a problem, think "I know, I'll use regular expressions." Now they have two problems.” - Jamie Zawinski Regex are a very useful and powerful concept, but for many problems there exist simpler solutions. Regex are slow compared to ’simple’ functions because they have huge overhead. They are also often harder to follow and hard to get right without missing rare cases. Task: I want to split this string on space/ tab/ semicolon. -> Regex is overkill for splitting on elementary separators. #don’t: pattern = re.compile("\s") split_line = pattern.split(line) #instead: split_line = line.split()

9DTU Systems Biology, Technical University of Denmark Overuse of Regex Task: I want to extract information from a line with clear separators (e.g. Tabs, semicolons, ect). Such files are e.g. Output files from other program (BLAST) or comma separated files. -> use str.split() Hit_ID = line.split()[1] Task: I want to check if the line I’m reading contains the information I’m looking for (and possibly where it is). -> use ’in’, str.startswith(), str.endswith() or str.find() if ’ CDS ’ in line: position = line.find(”join(”)

10DTU Systems Biology, Technical University of Denmark The True-and-false-ness of variables Task: I want to check if my flag has been set. Which comparison should I use? if flag:#preferred syntax if flag == True:#depricated if flag is True:#in special cases In Python, every non-empty value is treated as true in context of condition checking. In the context of Boolean operations, and also when expressions are used by control flow statements, the following values are interpreted as false: False, None, numeric zero of all types, and empty strings and containers (including strings, tuples, lists, dictionaries, sets and frozensets). All other values are interpreted as true. ( operations) The ’is’ comparative operator is useful, when you make actual distinction between True value and every other that could be treated as true. The same applies to if cond is False. This expression is true only if cond has actual value of False - not empty list, empty tuple, empty set, zero etc.