Docsity
Docsity

Prepare for your exams
Prepare for your exams

Study with the several resources on Docsity


Earn points to download
Earn points to download

Earn points by helping other students or get them with a premium plan


Guidelines and tips
Guidelines and tips

Side by Side: Python and C++ - Lecture Notes | COSC 350, Study notes of Data Structures and Algorithms

Material Type: Notes; Professor: Sloan; Class: Data Structures; Subject: Computer Science; University: Wofford College; Term: Fall 2006;

Typology: Study notes

Pre 2010

Uploaded on 08/16/2009

koofers-user-u2s
koofers-user-u2s 🇺🇸

10 documents

1 / 46

Toggle sidebar

This page cannot be seen from the preview

Don't miss anything!

bg1
Joe Sloan Page 1 of 46 7:54:41 AM 9/29/2006
DRAFT
Side-by-side: Python and C/C++
Caveat Emptor: A Few Words about this Document
In writing this document, I have tried to provide a quick introduction to Python for programmers with a basic knowledge of C/C++. Since this is written for
programmers, basic programming concepts are not explained. While this is formatted to presents C/C++ and Python side-by-side, I do not provide a detailed
comparison of the two languages. Rather, I am trying to show how similar things are done in each, and to point out some unique features in Python.
I do not go beyond the basics for either C/C++ or Python. My goal is to provide C/C++ programmers enough information to get started writing Python
programs. This document is asymmetric: it is for C/C++ programming learning Python, not for Python programmers learning C or C++. Since my C/C++ skills
are a little rusty (and C++ is definitely a moving target) and the Python material was written as I learned Python, you shouldn’t consider me an expert in either
C/C++ or Python. Some features of Python are used in examples before they are explained, but the meaning should be obvious from the context.
This is not a stand-alone document. In particular, I do not discuss the philosophy behind Python; nor do I describe how to use the Python interpreter. With that
in mind, there are additional resources listed at the end of this document that you might want to consult before you actually begin using Python. I assume that
you will consult other documentation and delve further into Python as needed and hope you will quickly outgrow this document.
The Side-by-Side Presentation
Throughout this document, the C/C++ code is presented in the left column or columns with the corresponding Python code will be to the right of the C/C++ code.
When C and C++ differ, there may be three columns—one for C, one for C++, and one for Python. All code is presented in colored boxes-light blue, darker blue
and light green for C, C++, and Python respectively. When describing a feature of Python that has no corresponding feature in C or C++, no C/C++ code will be
included. Similarly, when the code in C or C++ isn’t germane or is radically different, it is also omitted. Comments and discussion of the code will span the
columns or will be to the right of the code. Output from code is placed to the right of the code when germane to the discussion. Courier New is used for code
and output.
pf3
pf4
pf5
pf8
pf9
pfa
pfd
pfe
pff
pf12
pf13
pf14
pf15
pf16
pf17
pf18
pf19
pf1a
pf1b
pf1c
pf1d
pf1e
pf1f
pf20
pf21
pf22
pf23
pf24
pf25
pf26
pf27
pf28
pf29
pf2a
pf2b
pf2c
pf2d
pf2e

Partial preview of the text

Download Side by Side: Python and C++ - Lecture Notes | COSC 350 and more Study notes Data Structures and Algorithms in PDF only on Docsity!

Joe Sloan^

DRAFT Side-by-side: Python and C/C++ Page 1 of 46^ 7:54:41 AM 9/29/

Caveat Emptor: A Few Words about this Document In writing this document, I have tried to provide a quick introduction to Python for programmers with a basic knowledge of C/C++. Since this is written forprogrammers, basic programming concepts are not explained. While this is formatted to presents C/C++ and Python side-by-side, I do not provide a detailedcomparison of the two languages. Rather, I am trying to show how similar things are done in each, and to point out some unique features in Python.I do not go beyond the basics for either C/C++ or Python. My goal is to provide C/C++ programmers enough information to get started writing Pythonprograms. This document is asymmetric: it is for C/C++ programming learning Python, not for Python programmers learning C or C++. Since my C/C++ skillsare a little rusty (and C++ is definitely a moving target) and the Python material was written as I learned Python, you shouldn’t consider me an expert in eitherC/C++ or Python. Some features of Python are used in examples before they are explained, but the meaning should be obvious from the context.This is not a stand-alone document. In particular, I do not discuss the philosophy behind Python; nor do I describe how to use the Python interpreter. With thatin mind, there are additional resources listed at the end of this document that you might want to consult before you actually begin using Python. I assume thatyou will consult other documentation and delve further into Python as needed and hope you will quickly outgrow this document. The Side-by-Side Presentation Throughout this document, the C/C++ code is presented in the left column or columns with the corresponding Python code will be to the right of the C/C++ code.When C and C++ differ, there may be three columns—one for C, one for C++, and one for Python. All code is presented in colored boxes-light blue, darker blueand light green for C, C++, and Python respectively. When describing a feature of Python that has no corresponding feature in C or C++, no C/C++ code will beincluded. Similarly, when the code in C or C++ isn’t germane or is radically different, it is also omitted. Comments and discussion of the code will span thecolumns or will be to the right of the code. Output from code is placed to the right of the code when germane to the discussion. Courier New is used for codeand output.

Python and C/C++: Side-by-side^

DRAFT

Joe Sloan^

Page 2 of 46^ 7:54:41 AM 9/29/ Python Basic Syntax A Simple Program Here is “Hello World!” in C++ and Python.^ #include def main():using namespace std;print "Hello World!"int main(void){main()cout << “Hello World!”;return 0;} There are a few things to note with this simple example. Since Python is interpreted, we didn’t really need a program at all. We could have typed^ print "Hello World!" directly into the interpreter. With both C/C++ and Python we define and invoke the function

main(). With C/C++^ main()^ is called automatically. With Python, we need to explicitly call it. But since we are explicitly calling

main()^ in Python, we could have named the function something else. Unlike C/C++, Python programs don’t have to have a^ main()^ function.Also, with Python, we didn’t need any libraries for this simple example. At times Python will require libraries such as

math^ or^ random , but a little more seems to be built into core Python than in core C/C++. In this example, there are no semicolons at the ends of the lines. Typically, Python interpreters allowsemicolons, but they are rarely used. The exception is when several commands are placed on the same line. In Python you can write^ x = 3; y = 4; z = x + y; print z

7 is displayed Note that the statements are evaluated in order. In general, it is best to avoid using semicolons since they are an interpreter feature than a language requirement.

Python and C/C++: Side-by-side^

DRAFT

Joe Sloan^

Page 4 of 46^ 7:54:41 AM 9/29/ // C++ added single-line comments Unlike C/C++, Python supports imbedded comments know as^ docstrings

that are not discarded when the code is compiled, but is retained at runtime. These comments are coded as strings at the top of a module file, top of a function, or top of a class statement. Python automatically shifts these into the

doc---- attribute.^ For example, if you load the following code:^ """spam functiona meaningless function"""def spam(x):return x + 42^ and then enter the following at the interpreter:

the interpreter will display print docspam function-- -- a meaningless function

Identifiers Legal variable names are basically the same in C/C++ and Python. (Length restrictions may vary from compiler to compiler in C/C++.) Variables must start witha letter or underscore, followed by any combination of letters, digits, or underscores. Both languages are case sensitive.^ datumdatumfoo1spam1_bar_eggs Like C/C++, Python has some conventions about when to use variables that start with an underscore so you should use such variables with care. For example,those that start and end with two underscores have special meaning to the interpreter in Python. Names that begin with a single underscore aren’t imported withwildcard imports, e.g.,^ from^ module^ import *. Names beginning with two underscores but not ending in two underscores within a class definition arepseudo-private attributes to the class. The name consisting of just the single underscore in the interpreter typically holds the result of the last evaluation.In C/C++ and Python, keywords are reserved and cannot be used as identifiers. Like C/C++, some of the words that you might hope were reserved includingbuilt-in commands like^ open^ aren’t included.

Python and C/C++: Side-by-side^

DRAFT

Joe Sloan^

Page 5 of 46^ 7:54:41 AM 9/29/

Keywords^ Keywords in C^ Keywords C++ added to C

Keywords in Python asmsignedandautosizeofand_eqbreakstaticbitandcasestructbitorcharswitchboolconsttypedefbreakcontinueunioncatchdefaultunsignedclassdovoidcompldoublevolatileconst_castelsewhiledeleteenumdynamic_castexternexplicitfloatexportforfalsegotofriendifinlineintmutablelongnamespaceregisternewreturnnotshortnot_eq

operatorandpassorassertprintor_eqbreakraiseprivateclassreturnprotectedcontinuetrypublicdefwhileregisterdelyieldreinterpret_caelifstelsestatic_castexcepttemplateexecthisfinallythrowfortruefromtryglobaltypeidiftypenameimportusinginvirtualiswchar_tlambdaxornotxor_eqor

Python and C/C++: Side-by-side^

DRAFT

Joe Sloan^

Page 7 of 46^ 7:54:41 AM 9/29/ With simultaneous assignments, Python is treating both the left and right-hand sides as implicit tuples. The same approach can be taken explicitly with lists.^ [a, b, c] = [1, 2, 3] (Tuples and lists are discussed later in this tutorial.) Simple Types Integer Types^ C/C++ has four kinds of integers that vary based onPython has two kinds of integers. The default integerthe storage allocated for each.type is the same as C’s long integer). Arbitrarilylong integers vary in size. They are denotedexplicitly with an L (deprecated) or implicitly whenthe numerical value used is too large for a plaininteger.^ int foo = 1;^ spam = 1long int bar = -2;longspam = 3Lshort int baz = 3;longspam = 327898769835329324232344unsigned int bang = 4;^ In this example, conversion to a long integer isautomatic. After the first assignment, the variable is aplain integer, but with the second assignment, thevariable changes to a long integer.^ spam = 3foo = 3278987698353293242323424 Decimal, octal, and hex are denoted the same way in each language, i.e. by the leading digit or digits.^ int x = 255;^ //decimalx = 255int y = 0377;^ //octalint z = 0xff;^ //hex

#in decimaly = 0377^ #in octal (decimal 255)z = 0xff^ #in hex (decimal 255)

Python and C/C++: Side-by-side^

DRAFT

Joe Sloan^

Page 8 of 46^ 7:54:41 AM 9/29/

Floating Point Numbers^ C/C++ provides two storage sizes for floating pointPython has a single floating point type thatnumbers.corresponds to C/C++’s double.^ float f = 12.34;^ f = 12.34double ff = 12.34e50;ff = 12.34e50 Imaginary Numbers Unlike C/C++, Python includes imaginary numbers as a core type.^ spam = 2 + 3jrealSpam = spam.realimaginarySpam = spam.imag

You must use a leading integercoefficient with the imaginary part.The operators^ .real^ and^ .imag extract the real value and thecoefficient for imaginary part of thenumber.

Boolean Type Although not originally included in either C++ or Python, Boolean variable are now a part of each language.^ bool x, y;x = Truex = true;y = Falsey = false;

Note the difference in case As with C and C++, Python will interpret a zero as false and any other number as true in a conditional expression.(Strictly speaking, Boolean variables in Python are another integer type.)^ if (1) printf("true");if (1): print "true"if (0.001) printf("true");if (0+1j): print "true"if (0) printf("false");if (0): print "false"

truetrue no output is displayed (In general, it is best to avoid tests like these.)

Python and C/C++: Side-by-side^

DRAFT

Joe Sloan^

Page 10 of 46^ 7:54:41 AM 9/29/ Operators and Precedence Operators and precedence are very similar. In a few cases, core Python includes operators that are available via libraries in C/C++.Python evaluates expression from left to right except that the right-hand side of an assignment is evaluated before the left-hand side. The following table givesprecedence from highest to lowest. The descriptions match the Python operators.^ C++ Operations^ Python Operations

Python Description (...), [...], {...}, ‘...‘ [[Add C++ chart]] X.attr , tuples, list, dictionary and strings X [ i ], X [ i:j ], f ( X,Y, ...) attributes, indexing, slices,function calls ** exponentiation +, -, ~ unary sign, bit complement *, /, % multiplication, division, modulus +, - addition subtraction >>, << bit shifts & bit and ^ bit xor | bit or in, not in, is, is not, <, membership, identity, relational <=, >, >=, <>, !=, == operators not logical not and logical and or logical or lambda anonymous function definition

Python and C/C++: Side-by-side^

DRAFT

Joe Sloan^

Page 11 of 46^ 7:54:41 AM 9/29/

Math operators^ ++-- //% %//

AdditionSubtractionMultiplicationDivision (truncates on integersonly)RemainderDivision with truncationExponentiation The division with truncation operators, //, rounds fractions down for both integers and floats.There has been some discussion to redesign the / division operator in Python so that with integer division it coerces the result into a float if necessary rather thantaking the floor. For example, 1/2 would return 0.5 rather than 0. You would use 1//2 if you really want 0. While this change might produce a cleaner, moreconsistent language, it would break a lot of existing code. If you want to force this behavior, you can add

from^ futureimport division^ to your --^ --^ code. This redefines / to coerce results into floats as necessary. For example,^ from^

futureimport division-- --^ 1/2 0. Like C/C++, Python supports update operators but adds a few operators to the mix.^ x += 1;x += 1x -= 2;x -= 2x *= 3;x *= 3x /= 4;x /= 4x %= 5;x %= 5x //= 6x **= 7

AdditionSubtractionMultiplicationDivision with truncation)RemainderDivision with truncationExponentiation Others include the bit operations^ &= ,^ ^= ,^ <<= ,^ |= , and^ >>=. While Python supports bit operations such as shifts, etc., they are rarely used and not covered here.In C/C++ and Python, evaluation of the expression to the right of the equal sign is completed before the variable is updated.

Python and C/C++: Side-by-side^

DRAFT

Joe Sloan^

Page 13 of 46^ 7:54:41 AM 9/29/ Unlike C/C++, Python does allow simple range testing.In C/C++, “OK” is printed. This is not what wasIn Python, nothing is printed which is probably whatmeant.you want.^ int x = 0;^ x = 0if (1 < x < 3) printf("Ok");if 1 < x < 3: print "Ok" Also, in Python, statements can’t be used as expressions.This is an error in PythonLegal C/C++ code—x^ is reassigned.^ if (x = 1) printf("Ok");^ if 1 = 3: print "Ok" So, for example, when doing file I/O in Python, you won’t be able to combine fetching a value and testing for an end-of-file condition in one operation. Butwhile Python is a little less versatile in this respect, this eliminates a number of very common errors found in C/C++ code.Python also allows distinguishes between equivalent objects and identical objects with the

is^ and^ is not^ operations. st1 = "Welcome to my world!"st2 = "Welcome to my world!"st3 = st1st3 == st1^ Truest3 == st2Truest3 is st1Truest3 is st2Falsest3 is not st2True Note, because Python caches short strings, this doesn’t always work the way you might expect it to.^ st1 = "a"st2 = "a"st1 is st

True Comparisons are applied recursively to data structures.

Python and C/C++: Side-by-side^

DRAFT

Joe Sloan^

Page 14 of 46^ 7:54:41 AM 9/29/

Logical Operators Functionally, the same logical operators are available in C/C++ and Python, but different symbols or identifiers are used.^ (done && found)(done and found)(done || found)(done or found)(! done)(not done)

logical andlogical inclusive ornegation Like C/C++, Python supports short-circuit evaluation. In Python, these

and^ and^ or^ return either the left or right item. A common idiom in Python is to use this to select items.^ x = 2 or 3print xx = 2 and 3print x

Printing Both C and C++ use libraries for I/O. For C, the^ printf^ family of commands found in

stdio.h^ are typically used. In C++ these have been largely superseded

with stream operations found in^ iostream^ such as^ cout^ and^ cin. Python’s print commands are much closer to those of C than those of C++. Libraries^ For C, use stdio.h^ You do not need to access external modules whenprinting in Python^ #include <stdio.h>^ For C++, use iostream.h^ #include

Python and C/C++: Side-by-side^

DRAFT

Joe Sloan^

Page 16 of 46^ 7:54:41 AM 9/29/ You can also use an escape sequence to specify any other character.^ \ooo^ \ooo^

character code in octal \xhh^ \xhh^

character code in hex \uhhh Unicode 16-bit hex \Uhhh Unicode 32-bit hex \N {id} Unicode dbase id For example, the ASCII character code for @ is 100 in octal and 40 in hex.^ printf("\100\x40");^ print "\100\x40"

Formatting^ In C or C++ you need to explicitly include spacesPrint automatically adds spaces between items andbetween item or indicate a linefeed is needed.will automatically append a linefeed.^ printf("Hello World\n");^ print "Hello", "World"cout <<"Hello" << " " << "World" <<endl;

Hello World If you don’t want a space, you can build a string. print "Hello"+"World"^ HelloWorldprint "Hello""World"HelloWorld If you want to continue on the same line, end theprint statement with a comma. if 1:print "Hello",print "World" Hello World Formatting the output in C^ You do not need to access external modules forPython

output printf("int or decimal: %d", 100);^ print "int or decimal: %d" % 100printf("float: %f", 12.34);print "float: %f" % 12.34printf("formatted int: %5d", 100);print "formatted int: %5d" % 100printf("formatted float: %5.2f",print "formatted float: %5.2f" % \12.3456);

int or decimal: 100float: 12.340000formatted int:^ 12. (^100) formatted float: 12.

Python and C/C++: Side-by-side^

DRAFT

Joe Sloan^ Note that the % operator is overloaded for strings.This form of substitution can be done in generaleven if you aren’t printing. (See the section onstrings.) "%d+%d=%d" % (1, 1, 2)^ '1+1=2' Page 17 of 46^ 7:54:41 AM 9/29/ The general format for a code is^ %[flag][width][.precision]code. For example,

%+8.2f^ could be used to specify printing a float within an eight field including the appropriate sign with a precision of two decimal places. (See reference manuals for additional flags.) Here are the common formatting codes with examples:^ %c^ %c^ printf("|%c|", 'a'); character^

print "%c" % 'c'^ |a| %d^ %d^ printf("|%5d|", 23); decimal integer^

print"|%5d|" % 23^ |^ 23| %e^ %e^ printf("|%5e|", 0.0005); float in exponentform

print "|%5e|" % 0.0005^ |5.000000e-04| %E^ %E^ float in exponent^ printf("|%5.3E|", 0.0005); form withuppercase E

print "|%5.3E|" % 0.0005^ |5.000E-04| %i^ %i^ printf("|%i|", 123); integer^

print "|%i|" % 123^ |123| %f^ %f^ printf("|%5.2f|", 0.00005); floating pointdecimal

print "|%5.2f|" % 0.00005^ | 0.00| %g^ %g^ floating point e or f^ printf("|%5g|", 0.00005);

print "|%5g|" % 0.00005^ |5e-05| %G^ %G^ printf("|%5.2G|", 0.00005); floating point E or f^

print "|%5.2G|" % 0.00005^ |5E-05| %p^ printf("|%p|", p1); pointer^

|0xcccccccc| %r print "|%r|" % "hello"^ |'hello'| string (using repr() inPython) %s^ %s^ string (using^ printf("|%s|", "hello");^ str()^ in Python)

print "|%s|" % "hello"^ |hello| %u^ %u^ unsigned^ printf("|%u|", 123);

print "|%u|" % 123^ |123| %o^ %o^ printf("|%o|", 04); octal integer^

print "|%o|" % 04^ |4| %x^ %x^ hex integer^ printf("|%x|", 0xff);

print "|%x|" % 0xff^ |ff| %X^ %X^ printf("|%X|", 0xff); hex integer withuppercase

print "|%X|" % 0xff^ |FF| %%^ %%^ printf("10%%"); literal^ “%”^

print "%i%%" % 10^

Python and C/C++: Side-by-side^

DRAFT

Joe Sloan^

Page 19 of 46^ 7:54:41 AM 9/29/ means you won’t be able to (or need to) iterate over a sting looking for its end. Perhaps a more significant difference is that strings in Python are immutable. Youcan’t directly change strings in Python. Rather, when you need to “change” a sting in Python, you will construct a new string based on the original.For C, strings are just arrays of characters^ For C++, you’ll need to include the librarystring

For Python, strings are an intrinsic type#include In some contexts, such as printing, you can use string literals as constants without declaring them^ printf("Hello");^ cout << "Hello";

print "Hello" Usually, however, you’ll need to declare and initialize your strings.^ char s[] = "Once upon a time";^ string s = "Once upon a time";

s = "Once upon a time" char s[] = "";^ string s1 = "";

s = "" char s[4] = {'C', 'a', 't',\0'};

s = 'Cat' n the second line we created empty strings. Notice the use of single quotes in the last line. Single quoted delimit characters in C. Since characters aren’t aseparate type in Python, either single or double quotes can be use to delimit strings. There are some other ways to delimit strings in Python. Having two differentdelimiters for strings in Python make it easier to specify strings with embedded quotes. IYou can delimit strings with triple quotes inPython. Triple quotes allow you to include newlinesin the text. But you could also use escape sequencesto get the same results.^ s1 = '''Hello'''s2 = """HelloSailor"""

'Hello''Hello\n\nSailor' Raw strings ignore escape sequences. Compare thefollowing: s3 = "\\t\"^ \print s3s4 = r"\\t\"print s4\\t\

Python and C/C++: Side-by-side^

DRAFT

Joe Sloan^ Unicode strings include Unicode characters. s5 = u'spam\u0020eggs'print s5^ spam eggs s1[1] = 'a' Page 20 of 46^ 7:54:41 AM 9/29/ Note that the last example is illegal in Python. You cannot change part of as string. However, you can easily construct new strings.s1 = s1[:1]+'a'+s1[2:]print s

'Hallo'

This new construct makes use of string slices, described in the next section. String Slices In C you typically work with one character at a time. If you want more functionality, you link to the appropriate library. C++ provides methods through the stringclass that provide even greater functionality. With Python, this is all built-in. Indexing is from zero in C/C++ and Python.In C you typically work with one character at aWith C++, the at method provides boundstime without bounds checkingchecking.

Python also provides bounds checking. char s[] = "Hello sailor";^ string s = "Hello sailor";printf("%c\n", s[0]);printf("%c\n", s[1]);printf("%c\n", s.at(1));

s = "Hello Sailor"print s[0] In C, this produces garbage.In C++, this generates an exception.

In Python, this generates an exception. printf("%c\n", s[20]);^ printf("%c\n", s.at(20));

print s[20] Using a technique know as slices, Python provides a easy mechanism to work with parts of strings. Slices allow you to specify a range within a string and Pythonreturns a new string constructed from that range. Remember, Python strings are immutable so you must create copies.Indexing starts at 0 and goes to one less than thelength of the string. The character at the first indexis included but the slice stops just before the lastindexed character.^ s1 = "Hello Sailor"s1[0:5]s1[1:2]

'Hello''e'