Python for C programmers

Similar documents
Lists, loops and decisions

CSC 148 Lecture 3. Dynamic Typing, Scoping, and Namespaces. Recursion

Java Bytecode (binary file)

CS1 Lecture 3 Jan. 18, 2019

CS1 Lecture 3 Jan. 22, 2018

Introduction to Python

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

Introduction to: Computers & Programming: Review prior to 1 st Midterm

CSE : Python Programming

Accelerating Information Technology Innovation

Accelerating Information Technology Innovation

MEIN 50010: Python Flow Control

Intro. Scheme Basics. scm> 5 5. scm>

Intro to Programming. Unit 7. What is Programming? What is Programming? Intro to Programming

python 01 September 16, 2016

1 Getting used to Python

STATS 507 Data Analysis in Python. Lecture 2: Functions, Conditionals, Recursion and Iteration

Python: common syntax

Python for Non-programmers

Lecture #15: Generic Functions and Expressivity. Last modified: Wed Mar 1 15:51: CS61A: Lecture #16 1

Beyond Blocks: Python Session #1

Python 1: Intro! Max Dougherty Andrew Schmitt

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

EXPRESSIONS, STATEMENTS, AND FUNCTIONS 1

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

CS 11 python track: lecture 3. n Today: Useful coding idioms

CSE : Python Programming

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

A Little Python Part 1. Introducing Programming with Python

Running a C program Compilation Python and C Variables and types Data and addresses Functions Performance. John Edgar 2

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

Coral Programming Language Reference Manual

File input and output and conditionals. Genome 559: Introduction to Statistical and Computational Genomics Prof. James H. Thomas

THE IF STATEMENT. The if statement is used to check a condition: if the condition is true, we run a block

Python as a First Programming Language Justin Stevens Giselle Serate Davidson Academy of Nevada. March 6th, 2016

61A Lecture 2. Friday, August 28, 2015

Python. Tutorial Lecture for EE562 Artificial Intelligence for Engineers

CSE : Python Programming. Homework 5 and Projects. Announcements. Course project: Overview. Course Project: Grading criteria

Python Intro GIS Week 1. Jake K. Carr

A function is a named piece of code that performs a specific task. Sometimes functions are called methods, procedures, or subroutines (like in LC-3).

Functions Structure and Parameters behind the scenes with diagrams!

C++ for Python Programmers

Introduction to Python

Key Differences Between Python and Java

Introduction to Python

Variables, expressions and statements

Unit E Step-by-Step: Programming with Python

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

CPSC 217-T03/T08. Functions Ruting Zhou

>>> * *(25**0.16) *10*(25**0.16)

CS 220: Introduction to Parallel Computing. Beginning C. Lecture 2

A Brief Introduction to Python

Introduction to Python. Genome 559: Introduction to Statistical and Computational Genomics Prof. James H. Thomas

Lecture 4. Defining Functions

Introduction to Python (All the Basic Stuff)

Week - 01 Lecture - 04 Downloading and installing Python

PYTHON FOR KIDS A Pl ayfu l I ntrodu ctio n to Prog r am m i ng J a s o n R. B r i g g s

Senthil Kumaran S

Some material adapted from Upenn cmpe391 slides and other sources

Getting Started with Python

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

ECE 364 Software Engineering Tools Lab. Lecture 3 Python: Introduction

Lecture 05 I/O statements Printf, Scanf Simple statements, Compound statements

CMSC 201 Fall 2016 Lab 09 Advanced Debugging

CS Advanced Unix Tools & Scripting

CS 11 Haskell track: lecture 1

Introduction to Python. Genome 559: Introduction to Statistical and Computational Genomics Prof. James H. Thomas

1 Truth. 2 Conditional Statements. Expressions That Can Evaluate to Boolean Values. Williams College Lecture 4 Brent Heeringa, Bill Jannen

Programming to Python

cis20.1 design and implementation of software applications I fall 2007 lecture # I.2 topics: introduction to java, part 1

Lecture 02, Fall 2018 Friday September 7

cs1114 REVIEW of details test closed laptop period

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

DEBUGGING TIPS. 1 Introduction COMPUTER SCIENCE 61A

Problem Solving through Programming In C Prof. Anupam Basu Department of Computer Science & Engineering Indian Institute of Technology, Kharagpur

Algorithms and Programming I. Lecture#12 Spring 2015

Programming in Python 3

A lot of people make repeated mistakes of not calling their functions and getting errors. Make sure you're calling your functions.

Exam 1 Format, Concepts, What you should be able to do, and Sample Problems

Getting Started Values, Expressions, and Statements CS GMU

Full file at

Exam 1 Prep. Dr. Demetrios Glinos University of Central Florida. COP3330 Object Oriented Programming

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

CSCI-243 Exam 1 Review February 22, 2015 Presented by the RIT Computer Science Community

28-Nov CSCI 2132 Software Development Lecture 33: Shell Scripting. 26 Shell Scripting. Faculty of Computer Science, Dalhousie University

CS 1803 Pair Homework 3 Calculator Pair Fun Due: Wednesday, September 15th, before 6 PM Out of 100 points

Scripting Languages. Python basics

Lecture 02 Making Decisions: Conditional Execution

27-Sep CSCI 2132 Software Development Lecture 10: Formatted Input and Output. Faculty of Computer Science, Dalhousie University. Lecture 10 p.

Introduction to Python Code Quality

ENGR 101 Engineering Design Workshop

C Language Part 1 Digital Computer Concept and Practice Copyright 2012 by Jaejin Lee

Lists and the for loop

CIS192 Python Programming. Robert Rand. August 27, 2015

Advanced Python. Executive Summary, Session 1

Hello World! Computer Programming for Kids and Other Beginners. Chapter 1. by Warren Sande and Carter Sande. Copyright 2009 Manning Publications

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

COSC2031 Software Tools Introduction to C

Stored (and reused) Steps

PHP Personal Home Page PHP: Hypertext Preprocessor (Lecture 35-37)

Transcription:

Python for C programmers The basics of Python are fairly simple to learn, if you already know how another structured language (like C) works. So we will walk through these basics here. This is only intended to be a quick overview, not a deep dive into how Python works. We will spend more time talking about certain topics (such as higher order functions) in later lectures, but for more details about the "basics," please talk to the instructors or the TA, or take a look at the Python reference pages (https://docs.python.org/2/reference/index.html) One big difference between C and Python is that C is compiled while Python is interpreted. This means that to run a C program, you first have to compile it (e.g., with gcc) and then run it; but once you compile the program, you have a standalone executable (e.g., a.out). With a Python program, you do not have to compile the program but to run the program you need to run it in the Python interpreter (e.g., > python hw0.py) In practice, at least for this class, this distinction will not really matter (it can matter more once you get to long-running programs that operate over large amounts of data) Variables and Types Perhaps the biggest difference between C and Python is that C variables are statically typed -- you need to say whether a variable x is an int or a float right up front. In Python, you don't: In [1]: x = 1 type(x) Out[1]: int Note that this means that we don't need to "declare" variables -- we can just use them whenever we need to. What's interesting about Python, though, is that while we say the type of x is an int, what's really happening is that x is a reference to an integer object, which happes to have the value 1. x itself doesn't have a fixed type. We can re-assign it: In [2]: x = 1.2 type(x) Out[2]: float You can even make x a string:

In [3]: Out[3]: x = "hello" type(x) str Python does its type checking dynamically. It will not tell you until you try to do something with a variable whether the operation is legal or not: In []: len(x) #this will work because x is a string Out[]: 5 In [5]: x = 1.2 len(x) #what will happen here? -------------------------------------------------------------------- ------- TypeError Traceback (most recent cal l last) <ipython-input-5-31756c9ed6f5> in <module>() 1 x = 1.2 ----> 2 len(x) #what will happen here? TypeError: object of type 'float' has no len() Python will also perform type coercion: when it makes sense, it will convert an object from one type to another to let an operation work: In [6]: p = 1 print (type(p)) #the parentheses around the argument to print are opti onal q =.2 print (type(q)) r = p + q print (type(r)) print ("value of r: {}".format(r)) #compare this to printf! <type 'int'> <type 'float'> <type 'float'> value of r: 1.2

Control statements Control statements in Python look a lot like their counterparts in C: if statements, while loops, for loops. The biggest difference is that in Python whitespace matters. We do not use { and } to separate blocks. Instead, we use colons (:) to mark the beginning of a block and indentation to mark what is in the block. If Statements Here is the equivalent of the C statement: if (r < 3) printf("x\n"); else printf("y\n"); In [7]: if r < 3: print "x" else: print "y" x And an example of multiline blocks: In [8]: if r < 1: print "x" print "less than 1" elif r < 2: print "y" print "less than 2" elif r < 3: print "z" print "less than 3" else: print "w" print "otherwise!" y less than 2 While Loops while loops are similar:

In [9]: x = 1 y = 1 while (x <= 10) : y *= x x += 1 print y 3628800 In [10]: x = 1 y = 1 while (x <= 10) : if x File "<ipython-input-10-0f6722897ca>", line if x ^ SyntaxError: invalid syntax For Loops for loops are a little trickier. They do not take the same form as C for loops. Instead, for loops iterate over collections in Python (e.g., lists). These are more like foreach loops that you might see in other languages (or the for (x : list) construct you see in Java). So let's start by talking about lists: In [11]: data = [1,, 9, 0,, 2, 6, 1, 2, 8,, 5, 0, 7] print data [1,, 9, 0,, 2, 6, 1, 2, 8,, 5, 0, 7] In [12]: hist = 5 * [0] print hist [0, 0, 0, 0, 0] Lists work like a combination of arrays in C (you can access them using []) and lists (you can append elements, remove elements, etc.) In [13]: length = len(data) print "data length: {} data[{}] = {}".format(length, length - 1, data[ length - 1]) data length: 1 data[13] = 7

In [1]: data.append(8) length = len(data) print "data length: {} data[{}] = {}".format(length, length - 1, data[ length - 1]) data length: 15 data[1] = 8 You can then iterate over the elements of the list: In [15]: for d in data : print d 1 9 0 2 6 1 2 8 5 0 7 8 In [16]: for d in data : hist[d / 2] += 1 print hist [, 2,, 2, 3] How do you write a for loop with an index variable that counts from 0 to, like you might in C? for (int i = 0; i < 5; i++) Use the standard function range, which generates a list with values that count from a lower bound to an upper bound: In [17]: r = range(0,5) print r [0, 1, 2, 3, ]

In [18]: for i in range(0, 5): print i 0 1 2 3 Functions Basic functions in Python work a lot like functions in C. The key differences are: 1. You don't have to specify a return type. In fact, you can return more than one thing! 2. You don't have to specify the types of the arguments 3. When calling functions, you can name the arguments (and thus change the order of the call) In [19]: def foo(x) : return x * 2 print foo(10) 20 In [20]: def foo2(x) : return x * 2, x * (a, b) = foo2(10) print a, b 20 0 In [21]: def foo3(x, y) : return 2 * x + y print foo3(7, 10) print foo3(y = 10, x = 7) 2 2 There are more complicated things you can do with functions -- nested functions, functions as arguments, functions as return values, etc. We will look at these in the lecture when we talk about Map and Reduce