Showing posts with label PYTHON. Show all posts
Showing posts with label PYTHON. Show all posts

Arguments are the value(s) provided in function call/invoke statement. PYTHON

Arguments are the value(s) provided in function call/invoke statement. 
List of arguments should be supplied in same way as parameters are listed.
 Bounding of parameters to arguments is done 
1:1, and so there should be same number and type of arguments as mentioned in parameter list.

Example: Arguments in function call
>>> SI (1000,2,10)
1000,2,10 are arguments. An argument can be constant, variable, or expression.

Example: Write the output from the following function:
def SI(p,r=10,t=5):
 return(p*r*t/100)
if we use following call statement:
SI(10000)
SI(20000,5)
SI(50000,7,3)

Output
>>> SI(10000)
5000
>>> SI(20000,5)
5000
>>> SI(50000,7,3)

10500

Operators and Operands in Python - 12th CBSE

Operators are special symbols that represent computation like addition and multiplication. The values
that the operator is applied to are called operands. Operators when applied on operands form an
expression. Operators are categorized as Arithmetic, Relational, Logical and Assignment. Following is the
partial list of operators:
Mathematical/Arithmetic operators: +, -, *, /, %, ** and //.
Relational operators: <, <=, >, >=, != or <> and ==.
Logical operators: or, and, and not
Assignment Operator: =, +=, -=, *=, /=, %=, **= and //=
Program need to interact with end user to accomplish the desired task, this is done using Input-Output
facility. Input means the data entered by user (end user) of the program. In python, raw_input() and input (
) functions are available for input.
Syntax of raw_input() is:
Variable = raw_input ([prompt])
Example:
>>>x = raw_input ('Enter your name: ')
Enter your name: ABC
Example:
y = int(raw_input ("enter your roll no"))
will convert the accepted string into integer before assigning to 'y'
Syntax for input() is:
Variable = input ([prompt])
Example:
x = input ('enter data:')
Enter data: 2+ ½.0
Will supply 2.5 to x
Print: This statement is used to display results.
Syntax:
print expression/constant/variable
Example:
>>> print "Hello"
Hello
Comments: As the program gets bigger and more complicated, it becomes difficult to read it and difficult
to look at a piece of code and to make out what it is doing by just looking at it. So it is good to add notes to
the code, while writing it. These notes are known as comments. In Python, comments start with '#' symbol.
Anything written after # in a line is ignored by interpreter. For more than one line comments, we use the
following;
Place '#' in front of each line, or

Use triple quoted string. ( """ """)

Variables and Types: in Python -12TH CBSE

Variables and Types: One of the most powerful features of a programming language is the ability to
manipulate variables. When we create a program, we often like to store values so that it can be used later.
We use objects (variables) to capture data, which then can be manipulated by computer to provide
information. By now, we know that object/variable is a name which refers to a value.
Every object has:
An Identity,
A type, and
A value.
A. Identity of the object is its address in memory and does not get change once it is created. We may know
it by typing id (variable)
We would be referring to objects as variable for now.
B. Type (i.e data type) is a set of values, and the allowable operations on those values. It can be one of the
following:
2
2
2
3
Computer Science
4
1. Number: Number data type stores Numerical Values. This data type is immutable i.e. value of its
object cannot be changed. Numbers are of three different types:
Integer & Long (to store whole numbers i.e. decimal digits without fraction part)
Float/floating point (to store numbers with fraction part)
Complex (to store real and imaginary part)
2. None: This is special data type with a single value. It is used to signify the absence of value/false in a
situation. It is represented by None.
3. Sequence: A sequence is an ordered collection of items, indexed by positive integers. It is a
combination of mutable (a mutable variable is one, whose value may change) and immutable (an
immutable variable is one, whose value may not change) data types. There are three types of sequence
data type available in Python, they are Strings, Lists & Tuples.
3.1 String- is an ordered sequence of letters/characters. They are enclosed in single quotes (' ') or
double quotes ('' "). The quotes are not part of string. They only tell the computer about where the
string constant begins and ends. They can have any character or sign, including space in them.
These are immutable. A string with length 1 represents a character in Python.
3.2 Lists: List is also a sequence of values of any type. Values in the list are called elements / items.
These are mutable and indexed/ordered. List is enclosed in square brackets ([]).
3.3 Tuples: Tuples are a sequence of values of any type and are indexed by integers. They are
immutable. Tuples are enclosed in ().
4. Sets: Set is unordered collection of values of any type with no duplicate entry. It is immutable.
5. Mapping: This data type is unordered and mutable. Dictionaries fall under Mappings.
5.1 Dictionaries: It can store any number of python objects. What they store is a key -value pairs,
which are accessed using key. Dictionary is enclosed in curly brackets ({}).
C. Value: Value is any number or a letter or string. To bind value to a variable, we use assignment
operator (=).
2
2
2
Data Types
Numbers None Sequences Sets Mappings
Dictionary Integer Strings Tuple List
Boolean
Floating Complex
Point
Computer Science
Keywords - are used to give some special meaning to the interpreter and are used by Python
interpreter to recognize the structure of program.
A partial list of keywords in Python 2.7 is
and del from not
while as elif global
or with assert else
if pass Yield break
except import print class
exec in Raise continue
finally is return def

for lambda try

Review of Python & Concept of Oops - 12th CBSE

Computer Science Class–XII - CBSE
Unit-1: Review of Python & Concept of Oops

We have learnt Python programming language in the 11th class and continue to learn the same language program in class 12th also. We also know that Python is a high level language and we need to have Python interpreter installed in our computer to write and run Python program. Python is also considered as an interpreted language because Python programs are executed by an interpreter. We also learn that Python shell can be used in two ways, viz., interactive mode and script mode. Interactive Mode: Interactive Mode, as the name suggests, allows us to interact with OS. Hear, when we type Python statement, interpreter displays the result(s) immediately. That means, when we type Python expression / statement / command after the prompt (>>>), the Python immediately responses with the output of it. Let's see what will happen when we type print "WELCOME TO PYTHON PROGRAMMING" after the prompt


>>>print "WELCOME TO PYTHON PROGRAMMING"

WELCOME TO PYTHON PROGRAMMING

Example:
>>> print 5+10
15
 >>> x=10

>>> y=20

>>> print x*y 200

Script Mode: In script mode, we type Python program in a file and then use interpreter to execute the content of the file. Working in interactive mode is convenient for beginners and for testing small pieces of code, as one can test them immediately. But for coding of more than few lines, we should always save our code so that it can be modified and reused. Python, in interactive mode, is good enough to learn, experiment or explore, but its only drawback is that we cannot save the statements and have to retype all the statements once again to re-run them.

Example: Input any two numbers and to find Quotient and Remainder.
Code: (Script mode)
a = input ("Enter first number")
b = input ("Enter second number")
print "Quotient", a/b
print "Remainder", a%b
Output: (Interactive Mode)
Enter first number10
Enter second number3
Quotient 3
Remainder 1 

Python implementation of automatic Tic Tac Toe game using random number

Python implementation of automatic Tic Tac Toe game using random number

Tic-tac-toe is a very popular game, so let’s implement an automatic Tic-tac-toe game using Python.
The game is automatically played by the program and hence, no user input is needed. Still, developing a automatic game will be lots of fun. Let’s see how to do this.
numpy and random Python libraries are used to build this game. Instead of asking the user to put a mark on the board, code randomly chooses a place on the board and put the mark. It will display the board after each turn unless a player wins. If the game gets draw, then it returns -1.
Explanation :
play_game() is the main function, which performs following tasks :
  • Calls create_board() to create a 9×9 board and initializes with 0.
  • For each player (1 or 2), calls the random_place() function to randomly choose a location on board and mark that location with the player number, alternatively.
  • Print the board after each move.
  • Evaluate the board after each move to check whether a row or column or a diagonal has the same player number. If so, displays the winner name. If after 9 moves, there are no winner then displays -1.
Below is the code for the above game :
# Tic-Tac-Toe Program using
# random number in Python

# importing all necessary libraries
import numpy as np
import random
from time import sleep

# Creates an empty board
def create_board():
return(np.array([[0, 0, 0],
[0, 0, 0],
[0, 0, 0]]))

# Check for empty places on board
def possibilities(board):
l = []

for i in range(len(board)):
for j in range(len(board)):

if board[i][j] == 0:
l.append((i, j))
return(l)

# Select a random place for the player
def random_place(board, player):
selection = possibilities(board)
current_loc = random.choice(selection)
board[current_loc] = player
return(board)

# Checks whether the player has three
# of their marks in a horizontal row
def row_win(board, player):
for x in range(len(board)):
win = True

for y in range(len(board)):
if board[x, y] != player:
win = False
continue

if win == True:
return(win)
return(win)

# Checks whether the player has three
# of their marks in a vertical row
def col_win(board, player):
for x in range(len(board)):
win = True

for y in range(len(board)):
if board[y][x] != player:
win = False
continue

if win == True:
return(win)
return(win)

# Checks whether the player has three
# of their marks in a diagonal row
def diag_win(board, player):
win = True
y = 0
for x in range(len(board)):
if board[x, x] != player:
win = False
win = True
if win:
for x in range(len(board)):
y = len(board) - 1 - x
if board[x, y] != player:
win = False
return win

# Evaluates whether there is
# a winner or a tie
def evaluate(board):
winner = 0

for player in [1, 2]:
if (row_win(board, player) or
col_win(board,player) or
diag_win(board,player)):

winner = player

if np.all(board != 0) and winner == 0:
winner = -1
return winner

# Main function to start the game
def play_game():
board, winner, counter = create_board(), 0, 1
print(board)
sleep(2)

while winner == 0:
for player in [1, 2]:
board = random_place(board, player)
print("Board after " + str(counter) + " move")
print(board)
sleep(2)
counter += 1
winner = evaluate(board)
if winner != 0:
break
return(winner)

# Driver Code
print("Winner is: " + str(play_game()))

Decorator example Python

85. Decorator example 
def document_it(func):
    def new_function(*args, **kwargs):
        print('Running function:', func.__name__)
        print('Positional arguments:', args)
        print('keyword arguments:', kwargs)
        result = func(*args, **kwargs)
        print('Result:', result)
        return result
    return new_function

def add_ints(a,b):
    return a + b

add_ints(3,5)

cooler_add_ints = document_it(add_ints)
cooler_add_ints(3,5)
#ALITER
@document_it
def add_ints(a,b):
    return a + b

add_ints(3,5)

Python Interview Questions 11

81. Example of key value
names = {'a': 1, 'b': 2, 'c': 3}
print(names)
x = names.keys()
print(x)
print(names['c'])

82. Program for fibonacci
def fib(n):
    a,b = 0,1
    while b < n:
        print(b)
        a,b = b , a+b

fib(3)

83. Program to check vowel 
letter = 'o'
if letter == 'a' or letter == 'e' or letter == 'i' \
or letter == 'o' or letter == 'u':
    print (letter, 'is a vowel')
else:
    print(letter, 'is not a vowel')
   
84. Example of multi-dimensional array
rows = range(1,4)
cols = range(1,3)

cells = [(row,col) for row in rows for col in cols]
for cell in cells:
    print(cell)

Python Interview Questions 10


76. Example of return
def allowed_dating_age(my_age):
    girls_age = my_age/2 + 7
    return girls_age

Age_limit = allowed_dating_age(34)
print("You can date girls", Age_limit, "or older")
allowed_dating_age(34)

77. Example of set
groceries = {'cereal','milk','starcrunch','beer','duct tape','lotion','beer'}
print(groceries)

if 'milk' in groceries:
    print("You already have milk hoss!")
else:
    print("Oh yes you need milk!")

78. Example of variable scope
#a = 1514
def test1():
    a = 1514
    print(a)

def test2():
    print(a)

test1()
test2()

79. Example of dictionary
myDict = {'manish': 'bidsar','abc': 'efg'}
print(myDict)
print(myDict['manish'])
print(myDict["manish"])

varstr = "this is manish " \
         "from  Karnataka " \
         "India."
   
   
80. Example for prime number
for num in range(2,20):
    if num%2 == 0:
        print ('num is not prime')
        #break
    else:
        print ('num is prime number')

x = range(2,9)
print(x)

Python Interview Questions 9


71. Example of for 
foods = ['apple', 'banana', 'grapes', 'mango']
for f in foods:
    print(f)
    print(len(f))

72. function example
def cisco():
    print("Python, fucntions are cool!")
cisco()

def bitcoin_to_usd(btc):
    amount = btc*527
    print(amount)

bitcoin_to_usd(3.85)

73. Example of if else
name = "Lucy"
if name is "Manish":
    print("hey there Manish")
elif name is "Lucy":
    print("What's up Lucy")
elif name is "Sammy":
    print("What's up Sammy")
else:
    print("Please sign up for the Site!")

74. Example of key argument 
def dumb_sentence(name='manish',action='ate',item='tuna'):
    print(name,action,item)

dumb_sentence()
dumb_sentence("Sally", "plays", "gently")
dumb_sentence(item ='awesome', action= 'is')

75. Example of range
for x in range(10):
    print("Hello manish")

for x in range(5, 12):
    print(x)
for x in range(10, 40, 5):
    print(x)

Python Interview Questions 8

66. """Module for demonstrating files."""
import sys
def main(filename):
  f = open(filename, mode='rt', encoding='utf-8')
  for line in f:
      sys.stdout.write(line)
  f.close()

if __name__ == '__main__':
  main(sys.argv[1])

67. Write a function to add two numbers
def add_numbers(*args):
    total = 0
    for a in args:
        total += a
    print (total)

add_numbers(3)
add_numbers(3, 42)

68.  How to un-pack arguments
def health_calculator(age, apples_ate, cigs_smoked):
    answer = (100-age) + (apples_ate * 3.5) - (cigs_smoked * 2)
    print(answer)

data = [27,20,0]
health_calculator(data[0],data[1],data[2])
health_calculator(*data)


  
69. Example of continue
numbersTaken = [2,5,12,33,17]
print ("Here are the numbers that are still available:")
for n in range(1,20):
    if n in numbersTaken:
        continue
    print(n)

70. Example of default arg
def get_gender(sex='Unknown'):
    if sex is "m":
        sex = "Male"
    elif sex is "f":
        sex = "Female"
    print(sex)

get_gender('m')
get_gender('f')
get_gender()

Python Interview Questions 7

61. How will you reverse a list?
list.reverse() − Reverses objects of list in place.

61. How will you sort a list?
list.sort([func]) − Sorts objects of list, use compare func if given.

62. Multiple assignment
>>> target_color_name = first_color_name = 'FireBrick'
>>> id(target_color_name) == id(first_color_name)
True
>>> print(target_color_name)
FireBrick
>>> print(first_color_name)
FireBrick
>>>

63. Word count
import sys

def count_words(filename):
    results = dict()
    with open(filename, 'r') as f:
        for line in f:
            for word in line.split():
                results[word] = results.setdefault(word, 0) + 1

    for word, count in sorted(results.items(), key=lambda x: x[1]):
        print('{} {}'.format(count, word))

count_words(sys.argv[1])

64. Word list
from urllib.request import urlopen

with urlopen('http://sixty-north.com/c/t.txt') as story:
    story_words = []
    for line in story:
        line_words = line.split()
        for word in line_words:
            story_words.append(word)

print(story_words)

65. """Demonstrate scoping."""

count = 0

def show_count():
    print("count = ", count)

def set_count(c):
    global count
    count = c

Python Interview Questions 6

51.What is the output of L[-2] if L = [1,2,3]?
L[-1] = 3, L[-2]=2, L[-3]=1

52.What is the output of L[1:] if L = [1,2,3]?
2, 3, Slicing fetches sections.

53. How will you compare two lists?
cmp(list1, list2) − Compares elements of both lists.

54. How will you get the length of a list?
len(list) − Gives the total length of the list.

55.How will you get the max valued item of a list?
max(list) − Returns item from the list with max value.

56. How will you get the min valued item of a list?
min(list) − Returns item from the list with min value.

57. How will you get the index of an object in a list?
list.index(obj) − Returns the lowest index in list that obj appears.

58.How will you remove last object from a list?
list.pop(obj=list[-1]) − Removes and returns last object or obj from list.

59. How will you remove last object from a list?
list.pop(obj=list[-1]) − Removes and returns last object or obj from list.

60. How will you remove an object from a list?
list.remove(obj) − Removes object obj from list.

Python Interview Questions 5

41.How will you remove all leading whitespace in string?
lstrip() − Removes all leading whitespace in string.

42.How will you replaces all occurrences of old substring in string with new string?
replace(old, new [, max]) − Replaces all occurrences of old in string with new or at most max occurrences if max given.

43.How will you remove all leading and trailing whitespace in string?
strip([chars]) − Performs both lstrip() and rstrip() on string.

44.How will you get titlecased version of string?
title() − Returns "titlecased" version of string, that is, all words begin with uppercase and the rest are lowercase.

45.What is the output of len([1, 2, 3])?
3.

46.What is the output of [1, 2, 3] + [4, 5, 6]?
[1, 2, 3, 4, 5, 6]

47.What is the output of ['Hi!'] * 4?
['Hi!', 'Hi!', 'Hi!', 'Hi!']

48.What is the output of 3 in [1, 2, 3]?
True

49.What is the output of for x in [1, 2, 3]: print x?
1 2 3

50.What is the output of L[2] if L = [1,2,3]?
3, Offsets start at zero.

Python reference Interview questions

1)HCL Python scripting developer Interview questions:-
1) How do you check list of files in the given path in python ??
2) How do you check whether file is exist or not in python
3) How do you perform copy file cmd in python ??
4) What is d use of setup.py in python
5) What is d use of __init__=__main__: condition in python??
6) What is d type of *args and **kargs ??
7) sys.path use in python ??

 2) CES Limited Python developer Interview Face2Face Interview questions:-

1.Basic questions on oops:
  *.Implement Base class using Instance, static and Abstract method
    instance method - takes two arguments to add operation
    static method - takes two args to multiply operation
    abstract method - takes two args to div operation
  *. Implement child class using 3 instance methods
    instance - takes three args for add operation
    instance - takes two args for multiplicatio operation
    instance - takes two args for div opration
    create a relation between two classes
2. How you realate two objects in python? For example Book and Page.
3. find the sum of sequence by skipping the between elements without using slicing.
    Ex seq = [1, 2, 3, 4, 5, 6, 7, 8, 9] where x = 4, y = 7
       skip elements between x and y(including x and y i,e. [4, 5, 6, 7]) always y
       comes after x
       output: 1+2+3+8+9 = 23
4. File question:
   File has following data:
   Print the words of the file by sorting order of the corresponding integers.
   Expected output:
    ABC, IJK, PQR, TUV, DEF
   =======
   TUV
   7
   PQR
   4
   ABC
   1
   DEF
   8
   IJK
   3
   =========
5. What is decorator? use of decorator? How you implement the decrator for argumented functions to override the behaviour.
6. Difference between __new__ and __init__ ??

 3)One of the Leading Bank company Telophonic Interview questions for Python developer:-  My friend doesnt want to reveal company name.

1) What is d diffrence between python and other laungages ??
2) Comprehension vs generators expression ??
3) What is d use of yield keyword in python ??
4) What is d use of "with file open "?? How do you implement ur own context manager ??
5) Abstract class in python ??
6) Java type constructor in python ??
7) list vs tuple vs dictinary vs set
8) Metaclasses in python
9) How do you connect with Oracle dtabase from the python
10) Which Test framework are you familar ?? (example pytest framework..)

4)Microsoft written Interview questions for Python Developer:-

1) Addition of two binary strings a ="11" and b = "1" and output "100"
2) Permutation of ABC
3) Input string "aaabccdee" then output "3ab2cd2e"
4) Validstings
      {}
      ({})
      [{()}]
      and invalid string
       (}
       {{)}
       [{[{()})]