Вы находитесь на странице: 1из 20

Concept 1.

Overall Program Structure

C language example #include <stdio.h> . . int main(void) { . . }

C# Language example using System; . . Class myClass { .

Python Language example No structural requirement. A Program consists of lines of code stored in a text file. When program starts executing it executes each line in the same sequence in which it is written.

2. How to comment/uncomm ent program lines

Static void Main() { . . } . } // single // single line line comments comments /* /* multi-line multi-line comments comments Start Start . . . . */ multi*/ multiline line comments

# is used as comment indicator For Multiline comments double quotes are used at start as well as at the end of multi line comments

3. Supported Data Types

comments end end int int float float double double char char long long unsigned int uint unsigned uchar char byte string

They support atomic and aggregated composite data types. Since we dont need a variable to be declared of some specific type hence no supported data types were found in iterature.
In python, every value has a datatype, but you dont need to declare the datatype of variable. It automatically declare according to to original assignment. Booleans either true or false. Numbers can be integer, floats, fractions(1/2) and even complex numbers (x^2 + 1 = 0). Strings sequence of Unicode characters. Bytes & byte arrays eg a JPEG image file. Lists odered sequence of values. Tuples odered sequence, immutable. Sets un-odered bags of values. Dictionaries un-odered bags of key-value pairs.

In Python, We never explicitly specify the data type of anything. Based on what value we assign, Python keeps track of the data type internally. All data values in Python are objects, and each object, or value, has a type. Python has built-in types for fundamental data types such as numbers, strings, tuples, lists, sets and dictionaries.

1) NUMBERS

The built-in number objects in Python support integers (plain and long) floating-point numbers, and complex numbers. Integer literals can be decimal, octal, or hexadecimal. For Example: A decimal literal is represented by a sequence of digits in which the first digit is nonzero. 1, 23, 3493 # Decimal integers To denote an octal literal, use 0 followed by a sequence of octal digits (0 to 7). 01, 027, 06645 # Octal integers To indicate a hexadecimal literal, use 0x followed by a sequence of hexadecimal digits (0 to 9 and A to F, in either upper- or lowercase). 0x1, 0x17, 0xDA5 LONG INTEGERS 1L, 23L, 99999333493L 01L, 027L, 01351033136165L 0x1L, 0x17L, 0x17486CBC75L Floating-point numbers # Hexadecimal integers # Long decimal integers # Long octal integers # Long hexadecimal integers

Floating points numbers can be reperesented as: 0., 0.0, .0, 1., 1.0, 1e0, 1.e0, 1.0e0 Complex numbers

A complex number is made up of two floating-point values, one each for the real and imaginary parts. A floating-point or decimal literal followed by a j or J: 0j, 0.j, 0.0j, .0j, 1j, 1.j, 1.0j, 1e0j, 1.e0j, 1.0e0j

2)STRINGS

A string literal can be represented as: 'This is a literal string' "This is another string" Strings in Python are immutable, meaning that when we perform an operation on strings, we always produce a new string object, rather than mutating an existing string.

3) TUPLES
A tuple is an immutable ordered sequence of items. The items of a tuple are arbitrary objects and may be of different types. Here are some tuples, all enclosed in the optional parentheses: (100, 200, 300) # Tuple with three items (3.14,) # Tuple with one item ( ) # Empty tuple (parentheses NOT optional!) We can also call the built-in type tuple to create a tuple. For example: tuple('wow') This builds a tuple equal to: ('w', 'o', 'w') tuple( ) without arguments creates and returns an empty tuple. When x is iterable, tuple(x) returns a tuple whose items are the same as the items in x.

4)LISTS

A list is a mutable ordered sequence of items. [42, 3.14, 'hello'] # List with three items [100] # List with one item [] # Empty list We can also call the built-in type list to create a list. For example: list('wow') This builds a list equal to: ['w', 'o', 'w'] List() same work as tuples.

5)SETS

Set works much like a list, but without allowing any duplicates, making it useful for identifying the unique objects in a collection. The most common use of sets is to determine membership, a task often asked of both lists and dictionaries as well. In the spirit of matching expectations, this uses the in keyword: >>>> example = {1,2,3,4,5} >>>> 4 in example True >>>> 6 in example False (from http://books.google.com.pk/books? id=9GPPLVcHd5cC&pg=PA39&dq=representation+of+sets+in+python&hl=en&ei=nbBQTq_PGsiHrAfYg9WsAg&sa=X &oi=book_result&ct=result&resnum=3&ved=0CDgQ6AEwAg#v=onepage&q=representation%20of%20sets%20in %20python&f=false

6)DICTIONARIES

Dictionary is written as key:value, where key is an expression giving the item's key and value is an expression giving the item's value. If a key appears more than once in a dictionary literal, only one of the items with that key is kept in the resulting dictionary object

dictionaries do not allow duplicate keys. Here are some dictionaries: {'x':42, 'y':3.14, 'z':7 } # Dictionary with three items and string keys {1:2, 3:4 } # Dictionary with two items and integer keys {} # Empty dictionary (From Python in a Nutshell)

4. How to Define a Variable

<Datatype> <variablename>;

<Datatype> <variablename>; double a,b,c;

In Python, there are no declarations. The existence of a variable depends on a statement that binds the variable, or, in other words, that sets a name to hold a reference to some object.
In Python, variables are never explicitly typed. Python figures out what type a variable is and keeps track of it internally. (From DiveintoPython) In Python there are no declarations. The existence of a variable begins with a statement that binds the variable, or, in other words, sets a name to hold a reference to some object.

5. Assigning values to variables

<Var-name> = <variable| value| expression>;

<Var-name> = <variable| value| expression >;

Plain assignment to a variable (e.g., name=value) is how you create a new variable or rebind an existing variable to a new value. Plain assignment to an object attribute (e.g., obj.attr=value) is a request to object obj to create or rebind attribute attr. Plain assignment to an item in a container (e.g., obj[key]=value) is a request to container obj to create or rebind the item with index key. Augmented assignment (e.g., name+=value) can rebind a variable, ask an object to rebind one of its existing attributes or items, or request the target object to modify itself The simplest expressions are literals and identifiers. You build other expressions by joining sub-expressions with the operators and/or delimiters. Operator precedence in expressions Operator `expr,...` {key:expr,...} Description String conversion Dictionary creation A NA NA

6. Mathematical Expression Writing/Evalua tion Rules Available mathematica l operators operators

A = b + c / 2 * (c 1) + / * % ++

+ / * % ++ --

precedence order of evaluation of expression

-+= -=

+= -=

[expr,...] (expr,...) f(expr,...) x[index:index] x[index] x.attr x**y ~x +x, -x x*y, x/y, x//y, x%y x+y, x-y x<<y, x>>y x&y x^y x|y x<y, x<=y, x>y, x>=y, x<>y, x!=y, x= =y x is y, x is not y x in y, x not in y Not x x and y

List creation Tuple creation or simple parentheses Function call Slicing Indexing Attribute reference Exponentiation (x to yth power) Bitwise NOT Unary plus and minus Multiplication, division, truncating division, remainder Addition, subtraction Left-shift, right-shift Bitwise AND Bitwise XOR Bitwise OR Comparisons (less than, less than or equal, greater than, greater than or equal, inequality, equality) Identity tests Membership tests Boolean NOT Boolean AND

NA NA L L L L R NA NA L L L L L L NA NA NA NA L

x or y Boolean OR L lambda arg,...: Anonymous simple function NA expr Operators with higher precedence are listed before those with

lower precedence. Operators listed together have the same precedence. The A column lists the associativity of the operator, which can be L (left-to-right), R (right-to-left), or NA (non-associative). 7. relational expressions <Value/vari able/expres sion> <reloperator> <variable/v alue/expres sion> > < >= <= == != <Value/var iable/expr ession> <reloperator> <variable/ value/expr ession> > < >= <= == != <Value/variable/expression> <variable/value/expression> <rel-operator>

x<y, x<=y, x>y, x>=y, x<>y, x!=y, x= =y x is y, x is not y x in y, x not in y Identity tests Membership tests

From Python in a Nutshell thinkCSpy.pdf

8. logical Expression Writing/Evalua tion Rules and their

! && ||

! && ||

There are three logical operators: and, or, and not. The semantics (meaning) of these operators is similar to their meaning in English. For example, x > 0 and x < 10 is true only if x is greater than 0 and less than 10. not x Boolean NOT x and y x or y Boolean AND Boolean OR

combination 9. Bit operators

(from Python In a Nutshell)

~ & | ^ >> <<

~ & | ^ >> <<

~ bitwise NOT & bitwise AND | bitwise OR ^ bitwise XOR >> << Right and left bitwise shift
(from Python In a Nutshell)

10. Overall precedence of mathematical, relational and logical operators

Python follows the same precedence rules for its mathematical operators that mathematics does. Parentheses have the highest precedence Exponentiation has the next highest precedence,Multiplication and Division have the same precedence, which is higher than Addition and Subtraction, Operators with the same precedence are evaluated from left to right. (from thinkCSpy.pdf)

BUT REMEMBER THE FOLLOWING Opera tor ** ~ + * / / / % + <, >, <=, >=, <>, ! =, == Not And Or Create Description Exponentiation (x to yth power) Complement (Bitwise NOT), unary plus (+x) and minus (-x) x*y, x/y, x//y, x%y Multiplication, division, truncating division, remainder Addition and subtraction x<y, x<=y, x>y, x>=y, x<>y, x! =y, x= =y Comparisons (less than, less than or equal, greater than, greater than or equal, inequality, equality) not x Boolean NOT x and y Boolean AND x or y Boolean OR strings with single quotes or double quotes. You can

11.

String

String are

handling Define Initiali ze

handled using char arrays char name[MAX] char name[] = How to learn;

String a; string a = abcdefghi jklm;

put single quotes inside double quotes and you can put double quotes inside single quotes. You can also escape characters with a backslash. e.g, >>> str1 = "that is jerry's ball" >>> str1 = 'say "goodbye", Bill' Strings are immutable, which means you can't change an existing string. The best we can do is create a new string that is a variation on the original: Original greeting = "Hello, world!" greeting[0] = 'J' # ERROR! print greeting Instead of producing the output Jello, world!, this code produces the runtime error TypeError: object doesn't support item assignment. Correct version greeting = "Hello, world!" newGreeting = 'J' + greeting[1:] print newGreeting (from thinkCSpy.pdf)

12. Statemen t separators

Statement separators are not normally needed. But, if we want more than one statement on a line, we use a statement separator, specifically a semi-colon. And, if we want to extend a statement to a second or third line and so on, we sometimes need to do a bit extra. Extending a Python statement to a subsequent line -- Follow these two rules: 1 Parentheses create an open context that tells Python that a statement extends to the next line:

total_count = (tree_count + vegetable_count + fruit_count) 2 A backslash as the last character on line tells Python that the current statement extends to the next line: total_count = tree_count + \ vegetable_count + fruit_count (http://www.rexx.com/~dkuhlman/python_workbook_01.html#indent ation-and-program-structure) Python has two functions designed for accepting data directly from the user:

13. Input Statements

scanf

Console.Re adLine(); // reads only strings How to read an integer string line = Console.Re adLine(); int i = Convert.To Int32(line ); OR int i =

input() raw_input()

raw_input() raw_input() asks the user for a string of data (ended with a newline), and simply returns the string. It can also take an argument, which is displayed as a prompt before the user enters the data. E.g. print raw_input('What is your name? ') prints out What is your name? <user input data here> input() input() uses raw_input to read a string of data, and then

Convert.To Int32(Cons ole.ReadLi ne());

attempts to evaluate it as if it were a Python program, and then returns the value that results.

14. Output Statements

printf

Console.Wr iteLine( ); Console.Wr iteLine(V alue of c = {0},c); Console.Wr iteLine(S um is {2} of {0} and {1},a,b,c ); Console.Wr iteLine( Sum of {0} + {1} = {2},a,b,c );

A print statement is denoted by the keyword print followed by zero or more expressions separated by commas. some examples of print statements: letter = 'c' print "give me a", letter, "..." # prints: give me a c ... answer = 42 print "the answer is:", answer # prints: the answer is: 42 "print" is a handy, simple way to output values in text form, mostly for debugging purposes. print outputs each expression x as a string that's just like the result of calling str(x). print implicitly outputs a space between expressions, and implicitly outputs \n after the last expression, unless the last expression is followed by a trailing comma (,). Here are some examples of print statements: EXAMPLE letter = 'c' print "give me a", letter, "..." # prints: give me a c... answer = 42 print "the answer is:", answer # prints: the answer is: 42 The destination of print's output is the file or file-like

object that is the value of the stdout attribute of the sys module. (From Python in a Nutshell) 15. Availabl e Library Functions Sin Cos Tan Log log10 sqrt Math.sin( variable| value | expression ) Math.cos( variable| value | expression ) Math.tan( variable| value | expression ) math.ceil(x) math.copysign(x, y) math.fabs(x) math.factorial(x) math.floor(x) math.fmod(x, y) math.frexp(x) math.fsum(iterable) math.isinf(x) math.isnan(x) math.ldexp(x, i) math.modf(x) math.trunc(x) math.exp(x) math.log(x[, base]) math.log1p(x) math.pow(x, y) math.sqrt(x) math.acos(x) math.asin(x) math.atan(x) math.atan2(y, x) math.cos(x) math.hypot(x, y) Return the Euclimath.sin(x) math.tan(x) math.degrees(x) math.radians(x)

math.acosh(x) math.asinh(x) math.atanh(x) math.cosh(x) math.sinh(x) math.tanh(x) 16. Selectio n Statements if (condition) statement; if (condition) {statements ;} if (condition) statement; else statement; switch (expression ) { case1: statement; break; case2: statement; default: } How to Program: C# Deitel BSCS-413 sec A Eve EP104933, 40, 13, 30, 19, 22, 31, 01, 02, 26, 15, 21, 09, 11, 18, 04, 03, EP094915 EP094910 EP094965
Note: In Python, all the statements indented by the same number of character spaces after a programming construct are considered to be part of a single block of code. Python uses indentation as its method of grouping statements. (http://tutorialspoint.com/python/python_if_else.htm)

if expression: statement(s) elif expression: statement(s) elif expression: statement(s) ... else expression: statement(s) The elif and else clauses are optional. Note that unlike some languages, Python does not have a switch statement, so you must use if, elif, and else for all conditional processing. The Python compound statement if, comprising if, elif, and else clauses, lets you conditionally execute blocks of statements. Here's the syntax for the if statement: if expression: statement(s) elif expression: statement(s)

... else: statement(s) The elif and else clauses are optional. Note that, unlike some languages, Python does not have a switch statement. Use if, elif, and else for all conditional processing. EXAMPLE if x < 0: print "x is negative" elif x % 2: print "x is positive and odd" else: print "x is even and non-negative" (From Python in a Nutshell) 17. Iterativ e Statements For While do-while For (int i = 0 ; I < 10 ; i++) statement; While (condition ) statement; Do { stat ement; } while (condition ); while expression: statement(s) A while statement can also include an else clause and break and continue statements for target in iterable: statement(s) example for letter in "ciao": print "give me a", letter, "..." for x in someseq: statement(s) (From Python in a Nutshell) array(typecode,init='')

18.

Arrays

Define Initialize use

int a[MAX]; <data-type> <Variable<Variablename>[array name>[inde -size]; x] <Variablename>[index]

Creates and returns an array object a with the given typecode. init can be a plain string whose length is a multiple of itemsize; the string's bytes, interpreted as machine values, directly initialize a's items. Alternatively, init can be a list (of characters when typecode is 'c', otherwise of numbers): each item of the list initializes one item of a.
array('l') array('u', 'hello \u2641') array('l', [1, 2, 3, 4, 5]) array('d', [1.0, 2.0, 3.14])

list = [2, 4, 7, 9] list2 = [3, "test", True, 7.4] a = range(5) #a = [0,1,2,3,4] a = range(10,0,-2) #a = [10,8,6,4,2] append command: a=[] a.append("test") a.append(5) print a -> ['test', 5] pop method: a.pop(5) print a Multi-dimensional lists: a=[[0,1,2],[3,4,5]] print a[1] -> [3, 4, 5] s = ["Lee", "Walsh", "Roberson"] s2 = ["Williams", "Redick", "Ewing", "Dockery"] s3 = [s, s2] print s3[1][2] -> Ewing

19. Modulari zation/Functio ns

<returndata-type> <functionname> ([parameter s]) { statement s; } It also requires prototypes of functions to be defined mentioned before they appear in the program

static double distance (int x1, int y1, int x2, int y2) {

Function blocks begin with the keyword def followed by the function name and parentheses ( ( ) ). Any input parameters or arguments should be placed within these parentheses. You can also define parameters inside these parentheses. The first statement of a function can be an optional statement - the documentation string of the function or docstring. The code block within every function starts with a colon (:) and is indented. The statement return [expression] exits a function, optionally passing back an expression to the caller. A return statement with no arguments is the same as return None.

def functionname( parameters ): "function_docstring" function_suite return [expression]


def printme( str ): "This prints a passed string into this function" print str; return;

20. Passing Values from /to Modules and Functions

Calling called Positional passing of arguments to parameters

Example of Passing a value def try_to_change(n): n = 'Changed' name = 'Init' try_to_change(name) print name

Put summary of the following page here http://docs.python.org/extending/extending.html 21. How arrays are passed to and from modules/functi ons Passing a list as an argument actually passes a reference to the list, not a copy of the list. For example, the function head takes a list as a parameter and returns the first element: def head(list): return list[0] Here's how it is used: >>> numbers = [1, 2, 3] >>> head(numbers) 1 The parameter list and the variable numbers are aliases for the same object. def f(x, y=[ ]): y.append(x) return y print f(23) prinf f(42) MORE INFO TO BE ADDED 22. External File/Data Handling fopen() fwrite() fread(), fseek(), fclose(), fprintf(), fscanf()
file object = open(file_name [, access_mode][, buffering])

# prints: [23] # prints: [23,42]

file_name: The file_name argument is a string value that contains the name of the file that you want to access. access_mode: The access_mode determines the mode in which the file has to be opened ie. read, write append etc. A complete list of possible values is given below in the table. This is optional parameter and the default file access mode is read (r) buffering: If the buffering value is set to 0, no buffering will take place. If the buffering value is 1, line buffering will be performed while accessing a file. If you specify the buffering value as an integer greater than 1, then buffering action will be performed with the indicated buffer size. If negative, the buffer size is the system

default(default behavior). Attribute Description file.closed Returns true if file is closed, false otherwise. file.mode Returns access mode with which file was opened. file.name Returns name of the file. file.softspace Returns false if space explicitly required with print, true otherwise.

The fileinput module lets you loop over all the lines in a list of text files. Close() Closes the whole sequence, so that iteration stops and no file remains open. FileInput class FileInput(files=None,inplace=0,backup='',bufsize=0) filelineno( ) Returns the number of lines read so far from the file now being read. filename( ) Returns the name of the file being read, or None if no line has been read yet. input(files=None,inplace=0,backup='',bufsize=0) nextfile( ) Closes the file now being read, so that the next line to be read will be the first one of the following file.
file = open("data/teams.txt","rb") team = "nonempty" while (team != ""): team = file.readline() if (team != ""): print team[:-1] #get rid of extra newline character file.close() file = open("data/teams.txt","rb") team = file.readlines() file.close() list = ["Florida","Clemson","Duke"] file = open("data/teams.txt","wb") for j in list: file.write(j+"\n") file.close()

import pickle, fcntl player = Player("J.J. Redick", "Duke", 4) file = open("data/players.txt", "a") fcntl.flock(file.fileno(), fcntl.LOCK_EX) pickle.dump(player, file) fcntl.flock(file.fileno(), fcntl.LOCK_UN) file.close()
F =open(poem.txt,w) f.write(poem) f.close() f.readline() Python provides a standard module called pickle using which you can store any Python object in a file and then get it back later.

23. Support for User Defined Data types

struct <structtype-name> { datatype variablenam e; . . . } <structvariablename> int86() int86x() intdos()

The struct module lets you pack binary data into a string, and then unpack the bytes of such a string back into the data they represent. Operations of module struct rely on struct format strings, which are ordinary strings that follow a specified syntax. @ = < >,! MORE TO BE ADDED FROM http://docs.python.org/library/struct.html

24. Integrat ion with Operating System

dirname(path) Returns the directory part of path, just like os.path.split(path)[0]. For example, os.path.dirname('b/c/d.e') returns 'b/c'. getatime(path),getmtime(path),getsize(path) Each of these functions returns an attribute from the result of os.stat(path): respectively, st_atime, st_mtime, and st_size. See stat on page 244 for more details about these attributes.

(From Python in a Nutshell) MORE TO BE ADDED 25. n Recursio Python supports recursion (i.e., a Python function can call itself), but there is a limit to how deep the recursion can be. Example def factorial(n): if n == 0: return 1 else; return n*factorial(n-1)
def trinumber(x): if x == 1: return 1 else: return x + trinumber(x-1) print "sum of single digits:",trinumber(9)

26.

Graphics

intigraph() , putpixel(), getpixel(), line(), circle(), fill(),

Python provides various options for developing graphical user interfaces (GUIs). Tkinter: Tkinter is the Python interface to the Tk GUI toolkit. wxPython: This is an open-source Python interface for wxWindows http://wxpython.org. JPython: JPython is a Python port for Java.

Tkinter provides various controls, such as buttons, labels, and text boxes, used in a GUI application. These controls are commonly called widgets. background (also bg)

Background color for the widget foreground (also fg) Foreground color for the widget highlightbackground Background color of the highlight region when the widget has focus highlightcolor Foreground color of the highlight region when the widget has focus All Tkinter widgets have access to specific geometry management methods,such as: The pack() Method The grid() Method The place() Method win = GraphWin( pt = Point(100, 50) pt.draw(win) cir = Circle(pt, 25) cir.draw(win) line = Line(pt, Point(150, 100)) line.draw(win) message.draw(win) win.getMouse()

Вам также может понравиться