Q. Source Code Encoding

By default, Python source files are treated as encoded in UTF-8

Q. Where is the default directory in windows system?

%LOCALAPPDATA%\Programs\Python\Python36-32

Q. First-class object

Everything in Python is an object, and everything can have attributes and methods.

In Python, functions are first-class objects. You can pass a function as an argument to another function. Modules are first-class objects. You can pass an entire module as an argument to a function. Classes are first-class objects, and individual instances of a class are also first-class objects.

Q.Arbitrary Argument Lists

A function can be called with an arbitrary number of arguments. These arguments will be wrapped up in a tuple. zero or more normal arguments may occur.

The names *args and **kwargs are only by convention but there's no hard requirement to use them.

def print_everything(*args): 
    for count, thing in enumerate(args):
        print( '{0}. {1}'.format(count, thing))

print_everything('apple', 'banana', 'cabbage')

# output here ...
0. apple
1. banana
2. cabbage

**kwargs allows you to handle named arguments that you have not defined in advance:

def table_things(**kwargs): 
    for name, value in kwargs.items():
        print( '{0} = {1}'.format(name, value))

table_things(apple = 'fruit', cabbage = 'vegetable')

# output here ...
cabbage = vegetable
apple = fruit

You can also use both in the same function definition but *args must occur before **kwargs.

Q. Exceptions

Python encourages the use of exceptions, which you handle. Python uses try...except blocks to handle exceptions, and the raisestatement to generate them.

raise ValueError('number must be non-negative')

Catching Errors
try:
    import chardet
except ImportError:
    chardet = None

Q. DateTypes

Due to some legacy issues left over from Python 2, booleans can be treated as numbers. True is 1; False is 0

You can use the type() function to check the type of any value or variable.

type(1)

isinstance(1, int)

Tuples

A tuple is an immutable list.

a_tuple = ("a", "b", "mpilgrim", "z", "example")

Sets

A set is an unordered “bag” of unique values.

a_set = { 2, 4, 5, 9, 12, 21, 30, 51, 76, 127, 195 }

Dictionaries

A dictionary is an unordered set of key-value pairs.

a_dict = {'server': 'db.diveintopython3.org', 'database': 'mysql'}

You can not have duplicate keys in a dictionary.

You can add new key-value pairs at any time.

Dictionary values can be any datatype, including integers, booleans, arbitrary objects, or even other dictionaries.

SUFFIXES = {1000: ['KB', 'MB', 'GB', 'TB', 'PB', 'EB', 'ZB', 'YB'],

1024: ['KiB', 'MiB', 'GiB', 'TiB', 'PiB', 'EiB', 'ZiB', 'YiB']}

List Comprehensions

A list comprehension provides a compact way of mapping a list into another new list by applying a function to each of the elements of the list.

a_list = [1, 9, 8, 4]

# To make sense of this, look at it from right to left

a_list = [elem * 2 for elem in a_list]

You can use any Python expression in a list comprehension.

print([os.path.realpath(f) for f in glob.glob('*.py')])

To filter a list, you can include an if clause at the end of the list comprehension.

print([f for f in glob.glob('*.py') if os.stat(f).st_size > 1000])

Dictionary Comprehensions

metadata_dict = {f:os.stat(f) for f in glob.glob('*l*.py')}

It contains two expressions separated by a colon. The expression before the colon (f in this example) is the dictionary key; the expression after the colon (os.stat(f) in this example) is the value.

# new dict { os.path.splitext(f)[0] : meta.st_size }

# at condition "if meta.st_size > 1000"

metadata_dict = {os.path.splitext(f)[0]:meta.st_size for f, meta in metadata_dict.items() if meta.st_size > 1000}

Set Comprehensions

It is remarkably similar to the syntax for dictionary comprehensions. The only difference is that sets just have values instead of key:value pairs.

Q. Strings

In Python 3, all strings are sequences of Unicode characters. Bytes are not characters; bytes are bytes. Characters are an abstraction. A string is like a tuple (immutable) of characters

Python 3 supports formatting values into strings. Strings are objects, and objects have methods.

print("{0}'s password is {1}".format("welen", "5566"))

Another Example

# {0} refer to first argument

# {0[0]} refer to the first item of the list si_suffixes

# {0[1]} refer to the 2nd item of the list si_suffixes

print("1000{0[0]} = 1{0[1]}".format(si_suffixes))

results matching ""

    No results matching ""