Python Symbols

अब Quizwiz के साथ अपने होमवर्क और परीक्षाओं को एस करें!

None

A constant frequently used to represent the absence of a value, as when default arguments are not passed to a function.

False

A constant representing the false value of the boolean type.

True

A constant representing the true value of the boolean type.

.

A dot separates an object's name from the object's attribute being accessed or method being called. Note that some programmers refer to methods as attributes since they belong to an object. car.door='red' car.start()

lists

A list is a series of values. In Python, these values are assigned by placing them within square braces and separating them by commas like this: <name of list> = [ <value>, <value>, <value> ] girls = ['sugar', 'spice', 'everything nice'] To access a part of a list, one uses the same kind of phrase as one used for a string literal: <name of list>[<index number>]

floating point number

A real number (that is, a number that can contain a fractional part). To convert a number into floating point: >> a = 1 >> b = float(a) 1.0

strings

A string literal, or string, holds any combination of letters and numbers you would like it to hold. Any number it holds, however, is not treated like a numerical value but is preserved as if it were a word.

long number

Long integers have unlimited precision. >> a = 1 >> b = long(a) 1L Long numbers also take up a lot of processing power.

%

Modulus - Divides left hand operand by right hand operand and returns remainder

%=

Modulus AND assignment operator, It takes modulus using two operands and assign the result to left operand c %= a is equivalent to c = c % a

*

Multiplication - Multiplies values on either side of the operator

*=

Multiply AND assignment operator, It multiplies right operand with the left operand and assign the result to left operand c *= a is equivalent to c = c * a

%%

No argument is converted, results in a '%' character in the result.

%u

Obsolete type - it is identical to 'd'.

elif

The 'elif' keyword stands for 'else if'. In a boolean control structure, 'elif' defines that if the first test evaluates to False, we continue with the next one. If none of the tests is True, the else statement is executed. name = "Luke" if name == "Jack": print "Hello Jack!" elif name == "John": print "Hello John!" else: print "Hello there!"

else

The 'else' keyword is optionally used in an if-statement. The statement after the 'else' keyword is executed, unless the condition prefaced by 'if' is True. age = 17 if age > 18: print "Driving licence issued" else: print "Driving licence not permitted"

except

The 'except' keyword clause(s) specify one or more exception handlers. When no exception occurs in the 'try' clause, no exception handler is executed. When an exception occurs in the 'try' suite, a search for an exception handler is started. This search inspects the 'except' clauses in turn until one is found that matches the exception. f = None try: f = open('films', 'r') for i in f: print i, except IOError: print "Error reading file" finally: if f: f.close()

exec

The 'exec' keyword executes Python code dynamically. exec("for i in [1, 2, 3, 4, 5]: print i,")

finally

The 'finally' keywords is used in various 'try' statements. If 'finally' is present, it specifies a 'cleanup' handler. f = None try: f = open('films', 'r') for i in f: print i, except IOError: print "Error reading file" finally: if f: f.close()

for

The 'for' keyword is used to iterate over items of a collection in order that they appear in the container. i = [1, 2, 3] for x in i: print x

from

The 'from' keyword is used for importing a specific variable, class, or a function from a module.

global

The 'global' keyword is used to access variables outside a function. x = 15 def function(): global x x = 45 function() print x >> 45 Normally, assigning to x variable inside a function, we create a new local variable, which is valid only in that function. But if we use the 'global' keyword, we change a variable outside the function definition.

if

The 'if' keyword is used in a control statement to determine which statements are going to be executed. age = 17 if age > 18: print "Driving licence issued" else: print "Driving licence not permitted"

import

The 'import' keyword is used to import other modules into a Python script. import math print math.pi

in

The 'in' keyword points a test from an expression to an object. print 4 in (2, 3, 5, 6) >> False print 4 in (2, 3, 4, 5) >> True The 'in' keyword tests if the number four is in the tuple. The second usage is traversing a tuple in a 'for' loop.

is

The 'is' keyword tests for object identity. Whether we are talking about the same object. Note, that multiple variables may refer to the same object. It answers the question "Do I have two names for the same object?" m is x False

lambda

The 'lambda' keyword creates a new anonymous function. An anonymous function is a function, which is not bound to a specific name. It is also called an inline function. for i in (1, 2, 3, 4, 5): a = lambda x: x * x print a(i) We do not create a new function with a def keyword. Instead we use an inline function on the fly.

not

The 'not' keyword negates a boolean value. grades = ["A", "B"] grade = "G" if grade not in grades: print "unknown grade" This tests whether the grade value is from the list of possible grades.

pass

The 'pass' keyword does nothing. def function(): pass This function is not implemented yet. It will be later. The body of the function must not be empty. So we can use a 'pass' keyword here.

print

The 'print' keyword is use to print numbers and characters to the console. >>print 2 2

raise

The 'raise' keyword and associated statement forces a specified exception to occur. answer = 'y' if (answer != 'yes' or answer != 'no'): raise YesNoException else: print 'Correct value' The YesNoException is raised if answer != 'yes' or 'no'.

return

The 'return' keyword is closely connected with a function definition. 'Return' exits the function and returns a value. def root(x): return x * x

try

The 'try' statement specifies exception handlers and/or cleanup code for a group of statements. while True: try: x = int(raw_input("Enter a number: ")) break except ValueError: print "Not a valid number. Try again..."

while

The 'while' keyword is a basic keyword for controlling the flow of the program. The statements inside the while loop are executed, until the expression evaluates to False.

with

The 'with' keyword is used to wrap the execution of a block with methods defined by a context manager. This allows common 'try...except...finally' usage patterns to be encapsulated for convenient reuse. The 'with' statement is a control-flow structure whose basic structure is: with expression [as variable]: with-block with open('/etc/passwd', 'r') as f: for line in f: print line ... more processing code ... It is used when working with unmanaged resources (like file streams). It creates the resource, performs the code in the block, then it closes the resource.

yield

The 'yield' keyword is used with generators. def gen(): x = 11 yield x print gen().next() >> 11 The 'yield' keyword exits the generator and returns a value.

\r

The carriage return \r is a control character for end of line return to beginning of line.

\t

The horizontal tab puts a space between text. print "Towering\tinferno" # prints Towering inferno

\n

The new line is a control character, which begins a new line of text.

@

This is known as decorator syntax. Decorators allow you to inject or modify code in functions or classes. @decoratorName def desiredFunction(): pass

tuple

Tuples can be thought of as read-only lists. One can index, slice and concatenate, but one cannot append or alter the values of the tuple after it has been initialized. directions = ('north', 'south', 'east', 'west')

{ }

Used to create a dictionary object.

[ ]

Used to create a list object.

( )

Used to define the parameters of a function, specify arguments passed to a function, or to specify the order of operations in a formula.

>

Checks if the value of left operand is greater than the value of right operand, if yes then condition becomes true.

<=

Checks if the value of left operand is less than or equal to the value of right operand, if yes then condition becomes true.

<

Checks if the value of left operand is less than the value of right operand, if yes then condition becomes true.

!=

Checks if the value of two operands are equal or not, if values are not equal then condition becomes true.

<>

Checks if the value of two operands are equal or not, if values are not equal then condition becomes true. (a <> b) is true. This is similar to != operator.

==

Checks if the value of two operands are equal or not, if yes then condition becomes true.

:

Colons denote the beginning of a block of code, or the presence of an index between the objects on its left and right.

,

Commas separate parameters or arguments.

complex number

Complex numbers have a real and imaginary part, which are each a floating point number. >> a = 1 >> b = complex(a) (1+0j)

continue

The 'continue' keyword is used to interrupt the current cycle without jumping out of the whole cycle. num = 0 while (num < 1000): num = num + 1 if (num % 2) == 0: continue print num

def

The 'def' keyword is used to create a new user defined function. def newFunction():

del

The 'del' keyword deletes objects.

\b

ASCII Backspace (BS) Next we examine the backspace control character. print "Python\b\b\booo" # prints Pytooo

\a

ASCII Bell (BEL)

\f

ASCII Formfeed (FF)

\v

ASCII Vertical Tab (VT)

+=

Add AND assignment operator. It adds right operand to the left operand and assign the result to left operand. c += a is equivalent to c = c + a

+

Addition - Adds values on either side of the operator

integers

An integer in Python, also known as a 'numeric literal', is simply a name used for a numeric value. For this reason, these values are commonly called integers even if they are assigned the value of a real number in the form of an integer and a decimal value.

\\

Backslash (\)

>=

Checks if the value of left operand is greater than or equal to the value of right operand, if yes then condition becomes true.

dictionary

Dictionary is the Python term for an associative array. An array is, like a list, a series of values in two dimensions. An associative array gives one a way of accessing the values by a key, a term associated with the value instead of an item's index number. These are similar to hashes in Ruby. my_dictionary = { "author" : "Andrew Melville", "title" : "Moby Dick", "year" : "1851", "copies" : 5000000 } One accesses a dictionary member by its key: >>> a = my_dictionary["author"] >>> print a Andrew Melville

/=

Divide AND assignment operator, It divides left operand with the right operand and assign the result to left operand c /= a is equivalent to c = c / a

/

Division - Divides left hand operand by right hand operand

\"

Double quote (")

**

Exponent - Performs exponential (power) calculation on operators

**=

Exponent AND assignment operator, Performs exponential (power) calculation on operators and assign value to the left operand c **= a is equivalent to c = c ** a

%F

Floating point decimal format.

%f

Floating point decimal format.

%e

Floating point exponential format (lowercase).

%E

Floating point exponential format (uppercase).

%g

Floating point format. Uses lowercase exponential format if exponent is less than -4 or not less than precision, decimal format otherwise.

%G

Floating point format. Uses uppercase exponential format if exponent is less than -4 or not less than precision, decimal format otherwise.

//=

Floor Dividion and assigns a value, Performs floor division on operators and assign value to the left operand c //= a is equivalent to c = c // a

//

Floor Division - The division of operands where the result is the quotient in which the digits after the decimal point are removed. 9//2 is equal to 4 and 9.0//2.0 is equal to 4.0

or

In a boolean control structure, the keyword 'or' is used if at least one condition must be True for the boolean expression to result to True. if x < y or y < z: print "x"

;

Semicolons can separate different statements on a single line of code. a = b; d = b + 1; f = "cat"

%x

Signed hexadecimal (lowercase).

%X

Signed hexadecimal (uppercase).

%d

Signed integer decimal.

%i

Signed integer decimal.

%o

Signed octal value.

=

Simple assignment operator, Assigns values from right side operands to left side operand c = a + b will assign value of a + b into c

%c

Single character (accepts integer or single character string).

\'

Single quote (')

%r

String (converts any Python object using repr()).

%s

String (converts any Python object using str()).

-=

Subtract AND assignment operator, It subtracts right operand from the left operand and assign the result to left operand c -= a is equivalent to c = c - a

-

Subtraction - Subtracts right hand operand from left hand operand

and

The 'and' keyword in a boolean expressions specifies that conditions on both sides of the keyword must be True in order for the expression to result to True.

as

The 'as' keyword is used to give a module a different alias. import random as rnd print rnd.radint(1,10)

assert

The 'assert' keyword is used for debugging purposes. assert salary > 0 If the assertion fails, the interpreter will complain.

break

The 'break' keyword is used to interrupt the cycle, if needed. import random while (True): val = random.randint(1, 30) print val, if (val == 22): break If the number equals to 22, the cycle is interrupted with the 'break' keyword.

class

The 'class' keyword is used to create new user defined objects. class Random: class definition...


संबंधित स्टडी सेट्स

Brain and cranial nerves Chap14 (images)

View Set

AP Biology Unit 1: Chemistry of Life - Nucleic Acids (Practice Quiz)

View Set

SHRM BOCK: Key Terms, SHRM Code of Ethics, Legal and regulatory influences - FINAL SCP, Relationship Management, Global and Cultural Effectiveness, Business Acumen - Organizational budgeting, Business Acumen - organizational compensation, Consultatio...

View Set

ECON Exam 1- Ch. 4-5 Study Questions & Explanations

View Set