101 102 – C Python Starter
[Pages:5]101 102 ? C Python Starter
This document is meant to help with the transition from C to Java. It focuses only on the aspects of the C language covered in the previous version of 101 and the Python material covered in the new version of 101. As such, this mapping is necessarily and intentionally incomplete.
1 Functions
A function to return the square of a value might look as follows in C.
double square(double x) {
return x * x; }
A similar function in Python might be written as follows.
def square(x): return x**2
Note the following: ? A function definition is introduced with the def keyword. ? The function header ends with a : character. ? There are no type annotations. A variable's type is determined from its value. As such, the function "assumes" that a number is passed to the function (and will fail if called without a number). ? The body of the function is determined by the indentation. Those statements at the same level of indentation define the body of the function. Use spaces for your indentation; avoid tabs. Do not mix spaces and tabs. In Python, every function will return a value. If a return statement is not evaluated, then the function will
return the None value.
2 Variables
In C, a variable must be declared (with its type) before use.
int func(int x, int y) {
int z; z = x + y; return z; }
In Python, a variable is created when it is assigned a value.
def func(x, y): z=x+y return z
Such a variable will be local to the function (analogous to the example in C). To assign to a global variable, you will need to declare your intent as follows (avoid the use of global variables).
def func(x, y): global goodness why z=x+y goodness why = z * 2 return z
3 Conditionals and Boolean Operators
The differences here are only syntactic.
int weird(int x, int y) {
if (x < y && x > 0) {
return x; } else if (x < y || x == 9) {
return y; } else {
return 3; } }
In Python, a variable is created when it is assigned a value.
def weird(x, y): if x < y and x > 0: return x elif x < y or x == 9: return y else: return 3
4 Loops
Python supports a while statement very much as in C and a for statement that is less general, but arguably more clear, than that in C. In C:
void func(int x) {
int i = 0; while (i < x) {
printf("%d\n", i); i++; } }
In Python:
def func(x): i=0 while i < x: print(`{}'.format(i)) i += 1
The for statement works on collections or generators. It is often referred to as a "for each" statement. There are many ways to get a valid generator so consider the following as only a single example of looping over a range of integers. In Python:
def func(x): for i in range(0, x): print(`{}'.format(i))
This can be simplified to:
def func(x): for i in range(x): print(`{}'.format(i))
The more common use of for will be demonstrated in the next section.
5 Arrays Lists
In C, sequenced data is stored in an array; in Python it is stored in a list. Lists in Python support many interesting operations beyond the basics that will be shown here (check the documentation, especially about slices).
Consider this C function.
void func(int nums[], int len) {
int i; for (i = 0; i < len; i++) {
printf("%d\n", nums[i]); } }
The following function illustrates explicitly accessing elements in a list (similar to the C version) in Python.
def func(nums): i=0 while i < len(nums): print(`{}'.format(nums[i])) i += 1
This could, of course, be rewritten using a for statement over a range of values from 0 to the length of the list.
def func(nums): for i in range(0, len(nums)): print(`{}'.format(nums[i]))
Or, one can use the for statement to iterate over each element of the list (i.e., do some action for each
element in the list). The for can be read as "for each num in nums, print".
def func(nums): for num in nums: print(`{}'.format(num))
When first learning these different uses of for statement, it can be easy to confuse iterating over indices and iterating over elements. One can attempt to avoid that confusion by using the enumerate function to generate both an element of a list and the index of that element.
def func(nums): for (i, num) in enumerate(nums): print(`{} == {}'.format(num, nums[i]))
An empty list can be created with the [] literal value. One can also create a list with known values (e.g., [1, 2, 3]).
A list, unlike an array in C, can grow. For instance, nums.append(2) will place the value 2 at the end of the list nums (changing the contents of the list nums).
Refer to the Python documentation for more functions on lists. You might also consider reading about slices and list comprehensions.
6 Compound Data
In C, a programmer may declare a new type of compound data by declaring a struct.
struct point {
double x; double y; };
One can then declare a variable of this new type and modify or access the fields using dot notation.
struct point translate point(struct point p, double dx, double dy) {
struct point new p; new p.x = p.x + dx; new p.y = p.y + dy; return new p; }
In Python, one creates a class to declare compound data. In this class is defined a function (method), named __init__, that is automatically invoked when an object is created and that is meant to initialize the fields of the newly created object1. This initialization is how an object's fields are (initially) determined; there is no explicit field declaration.
class Point: def init (self, x, y): self.x = x self.y = y
One can create a value (i.e., an object) of this class by using the name of the class as a function and passing the arguments (excluding self) required by the __init__ function.
For instance, pt = Point(1, 2).
1Depending on your 101 instructor, you may have been required/advised to define similar "creation functions" when using structures in C.
Fields are modified and accessed as in C.
def translate point(p, dx, dy): new p = Point(p.x + dx, p.y + py) return new p
Python also supports an additional type of compound data called a tuple. This is a form of sequenced data (like a list) that cannot change (so it is used more like an object). One creates a tuple by grouping commaseparated expressions in parentheses. The elements of a tuple can be accessed through indexing (like a list) or through tuple assignment (this is similar to what was done with enumerate previously).
t = (1, True, 3) t[0] + 2 (a, b, c) = t a, b, c = t
7 Aliasing
The coverage of pointers in 101 varies greatly by instructor since pointers are not a specifically required topic. Some instructors feel that pointers are fundamental to C (and they really are); others feel that 101 is not technically a course on C (and it is not). Philosophical debates aside, your experience with pointers is assumed to be very limited. As such, variables referring to an object in Python may be quite unfamiliar in that there may be multiple variables referring to the same object.
Assuming the Point class from before, the following code will illustrate this aliasing.
pt1 = Point(1, 2) pt2 = Point(1, 2) print(pt1 == pt2) # prints False pt3 = pt1 print(pt1 == pt3) # prints True, as one would expect
pt1.x += 10 print(pt1.x) # prints 11 print(pt2.x) # prints 1, no relation to pt1 print(pt3.x) # prints 11, pt3 refers to the same object as pt1
Be aware of aliasing. Take care when changing the value of a field (an attribute) of an object. Does it always make sense for the field to change?
8 Multiple Files
Python, like C, allows for development of a program across multiple files. In C, one would use #include to access struct declarations and function prototypes in a header file and then compile all of the source files together.
In Python, a source file that needs to access definitions in another file will import that file. Each definition is then accessed by prefixing it with the file's name2. This is illustrated through use of sqrt in the math module.
import math
x = math.sqrt(16)
2There are additional forms of import that remove this requirement; see the Python documentation for more details.
................
................
In order to avoid copyright disputes, this page is only a partial summary.
To fulfill the demand for quickly locating and searching documents.
It is intelligent file search solution for home and business.