






































Study with the several resources on Docsity
Earn points by helping other students or get them with a premium plan
Prepare for your exams
Study with the several resources on Docsity
Earn points to download
Earn points by helping other students or get them with a premium plan
Community
Ask the community for help and clear up your study doubts
Discover the best universities in your country according to Docsity users
Free resources
Download our free guides on studying techniques, anxiety management strategies, and thesis advice from Docsity tutors
Material Type: Notes; Professor: Sloan; Class: Data Structures; Subject: Computer Science; University: Wofford College; Term: Fall 2006;
Typology: Study notes
1 / 46
This page cannot be seen from the preview
Don't miss anything!
Joe Sloan^
Python and C/C++: Side-by-side^
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
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^
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
Python and C/C++: Side-by-side^
Joe Sloan^
Page 5 of 46^ 7:54:41 AM 9/29/
Keywords in Python asmsignedandautosizeofand_eqbreakstaticbitandcasestructbitorcharswitchboolconsttypedefbreakcontinueunioncatchdefaultunsignedclassdovoidcompldoublevolatileconst_castelsewhiledeleteenumdynamic_castexternexplicitfloatexportforfalsegotofriendifinlineintmutablelongnamespaceregisternewreturnnotshortnot_eq
operatorandpassorassertprintor_eqbreakraiseprivateclassreturnprotectedcontinuetrypublicdefwhileregisterdelyieldreinterpret_caelifstelsestatic_castexcepttemplateexecthisfinallythrowfortruefromtryglobaltypeidiftypenameimportusinginvirtualiswchar_tlambdaxornotxor_eqor
Python and C/C++: Side-by-side^
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^
Joe Sloan^
Page 8 of 46^ 7:54:41 AM 9/29/
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.
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^
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^
Joe Sloan^
Page 11 of 46^ 7:54:41 AM 9/29/
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^
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^
Joe Sloan^
Page 14 of 46^ 7:54:41 AM 9/29/
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
Python and C/C++: Side-by-side^
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"
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^
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^
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
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^
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'
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'