CSCI1301 Midterm / Final

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

What will be the output of the following Python code? class test: def __init__(self, a="Hello World"): self.a = a def display(self): print(self.a) obj=test() obj.display()

"Hello World" is displayed

For the following code, the program will print the word "Here" and then print: print("Here ", end="") print("There " + "Everywhere") print("But not " + "in Texas")

"There Everywhere" on the same line as "Here"

Assume str = "abcdefg", to check whether string str contains "cd", use ________

"cd" in str

What will be the output of the following Python code? class test: def __init__(self): self.variable = 'Old' self.Change(self.variable) def Change(self, var): var = 'New' obj=test() print(obj.variable)

'Old' is printed

The function call plt.plot([5, 10, 15], [0.25, 0.34, 0.44]) plots an x,y coordinate at

(15, 0.44)

What is the correct extension of the Python file?

.py

Python modules are stored in which type of file?

.py file

Assume x=80; y=30; z=4 What is the result of x // y // z?

0

What will be the output of the following Python code? for x in range(10): if x == 5: break else: print( x, end=' ') else: print("Here")

0 1 2 3 4

What will be the output of the following Python code? for x in range(10): if x == 5: continue else: print( x, end=' ') else: print("Here")

0 1 2 3 4 6 7 8 9 Here

What will be the output of the following Python code? for x in range(5): if x == 5: break else: print( x, end=' ') else: print("Here")

0 1 2 3 4 Here

Assume a=80.0; b=30.0; c=4.0 What is the result of a / b / c?

0.67

What will be the output of the following Python code? my_list = ['One', 'Two', 'Three'] for i, x in enumerate( my_list): print('{}: {}'.format(i, x),end=" ")

0: One 1: Two 2: Three

What will be the output of the following Python code? def foo(): try: print(1) finally: print(2) foo() Question options:

1 2

What will be the output of the following Python code? def change(x = 0, y = 1): x = x + y y = y + 1 print(x, y) change(x = 0 , y = 1) change(x = 1 , y = 0) change(y = 1 , x = 0) change(y = 0 , x = 1)

1 2 1 1 1 2 1 1

What output of result in following Python program? list1 = [1,2,3,4] list2 = [2,4,5,6] result1 = list1 + list2 result2 = list1 * 2 print( result1 ) print( result2 )

1 2 3 4 2 4 5 6 1 2 3 4 1 2 3 4

What output in following Python program? list1 = [1,2,3,4] list2 = [2,4,5,6] list3 = [2,6,7,8] result1 = list1 + list2 result2 = list2 + list3 for i in result1:i f i not in result2: print( i )

1 3

What will be the output of the following Python code? my_dict={1:"A", 2:"B", 3:"C"} for i, j in my_dict.items(): print( i, j, end=" " )

1 A 2 B 3 C

Choose the container that best fits the described data. 1) Student test scores that may later be adjusted, ordered from best to worst. 2) A single student's name and their final grade in the class. 3) Names and current grades for all students in the class. Question options:

1) List 2) Tuple 3) Dict

What output is produced by the following code fragment? x = 0 for i in range(1, 5): x += i print(x)

10

What will be the output of the following Python code? def change(var, lst):var = 1lst[0] = 44 x = 10 my_list = [1, 2, 3] change(x, my_list) print(x) print(my_list)

10 [44, 2, 3]

What is the output of the following Python's code fragment: x = [-12, -43, 55, 67, -32, 12, -2]print( x[-2] )

12

What output is produced by the following code fragment? x = 1 while x < 100: x *= 2 print(x)

128

What will be the output of the following Python code? class fruits: def __init__(self, price): self.price = price obj=fruits(50) obj.quantity=10 obj.bags=2 print( obj.quantity + len( obj.__dict__ ) )

13

What value is contained in the integer variable size after the following statements are executed? size = 18 size = size + 12 size = size * 2 size = size / 4

15

Which expression checks whether the list my_list contains the value 15?

15 in my_list

What will be the output of the following Python code? my_dict={1:"A", 2:"B", 3:"C"} for i in my_dict.items(): print( i , end=" " )

1: 'A' 2:'B' 3:'C'

What will be the output of the following Python code? def foo(): try: return 1 finally: return 2 k = foo() print(k)

2

What will be the output of the following Python code? def change(a, b): a = a + 1 b = b + 1 print(a, b) change( a = 1, b = 0 ) change( a = 0, b = 1 )

2 1 1 2

What will be the output of the following Python code? a= [1, 2, 3, 4, 5] for i in range(1, 5): a[ i-1 ] = a[ i ]for number in a: print( number, end = " ")

2 3 4 5 5

What output is produced by the following code fragment? x = 1 while x < 100: x *= 2 if x == 64: break print(x, end=' ')

2 4 8 16 32

What output is produced by the following code fragment? x = 1 while x < 100: x *= 2 if x == 64: break print(x, end=' ') else: print(x)

2 4 8 16 32

What output is produced by the following code fragment? x = 1 while x < 100: x *= 2 if x == 64: continue print(x, end=' ')

2 4 8 16 32 128

What output is produced by the following code fragment? x = 1 while x < 100: if x == 64: break x *= 2 print(x, end=' ')

2 4 8 16 32 64

What output is produced by the following code fragment? x = 1 while x < 100: x *= 2 print(x, end=' ') else: print(x)

2 4 8 16 32 64 128 128

What will be the output of the following Python code? import turtle t=turtle.Turtle() for i in range(0,4): t.forward(100) t.left(90) t.left(90) t.forward(200) for i in range(0,4): t.forward(100) t.left(90)

2 squares, at a separation of100 units, joined by a straight line

Assume today is 10/31/2022, Monday, what output for the following code? import datetime d=datetime.date(2018,9,15) print(d) tday=datetime.date.today() print(tday) print( tday.weekday() ) print( tday.month )

2018-09-15 2022-10-31 0 10

What is the output of the following of Python code fragment? from datetime import datetime timestamp = [1591682671] for unix_time in timestamp: print( datetime.utcfromtimestamp( unix_time ).strftime( '%Y-%m-%d %H:%M:%S' ))

2020-06-09 06:04:31

What output is produced by the following code fragment? num = 1; max = 20 while num < max: num += 4 print(num)

21

Given str="Hello, labor day!" what is the output of str.count( 'l' )?

3

Given the nested if-else structure below: if a > 0 : if b < 0: x = x + 5 else: if a > 5: x = x + 4 else : x = x + 3 else : x = x + 2 If x is currently 0, a = 5 and b = 5, what will x become after the above statement is executed? Question

3

What is the output of print "yxyxyxyxyxy".count('yxy') ?

3

What will be the output of the following Python code? def printMax(a, b):if a > b:print(a, 'is maximum')elif a == b:print(a, 'is equal to', b)else:print(b, 'is maximum') x = 3 y = 4 printMax( x+1, y)

4 is equal to 4

What is the output of print( len( [ 'abcd', 786 , 2.23, 'john', 10 ] ) )?

5

What will be the output of the following Python code? def foo( arg1, *args ): result = 0 for i in args: result += i return result print( foo(1, 2, 3) ) print( foo(1, 2, 3, 4, 5) )

5 14

What will be the output of the following Python code? def foo( *args ): result = 0 for i in args: result += i return result print( foo(1, 2, 3) ) print( foo(1, 2, 3, 4, 5) )

6 15

Given str="Hello, labor day!" what is the output of str.find( 'a' )?

8

How many iterations will the following for loop execute? for count in range(2, 20, 2): print( count, end= ' ' )

9

What will be the output of the following Python code? def power(x, y=2): result = 1 for i in range(y): result = result * x return result print( power(3) ) print( power(3, 3) ) print( power(4) ) print( power(4, 3) )

9 27 16 64

What output is produced by the following code fragment? str = "abc123_def456_$5.0" i = 0 while i< len(str): if str[i].isalnum(): print( str[i].upper(), end=' ') i += 1

A B C 1 2 3 D E F 4 5 6 5 0

What output is produced by the following code fragment? str = 'abcd' for character in str: print(character.upper(), end=' ')

A B C D

What will be the output of the following Python code? str = 'abcd' print(str.upper())

ABCD

What will be the output of the following Python code? str = 'abcd'print(str.upper())print(str[1].upper())

ABCD B

What is the output of print str.title() if str = 'abcd' ?

Abcd

Where is function defined in Python?

All of above: Module Class Another function

Which are the advantages of functions in python?

All of above: Reducing duplication of code Decomposing complex problems into simpler pieces Improving clarity of the code

Which of the following is true about the Python package?

All of the above

Which of the following lines is a properly formatted comment? # This is a comment " " " This is a comment " " " " " " This is a comment " " "

All of them

When is the finally block executed?

Always

What are the two main types of functions in Python?

Built-in function & User defined function

A variable shared with all instances of a class.

Class attribute

A factory for creating new class instances.

Class object

Which of the following is not a core data type in Python programming? Number, String, Boolean List, Tuple Dict, Set Clsss

Clsss

What will be the output of the following Python code? def add(c,k): c.test=c.test+1 k=k+1 class A: def __init__(self): self.test = 0 def main(): Count=A() k=0 for i in range(0,25): add( Count, k) print("Count.test=", Count.test) print("k =", k) main( )

Count.test=25k=0

What is Instantiation in terms of OOP terminology?

Creating an instance of class

What will be the output of the following Python code? import time print( time.asctime() ) Question options:

Current date and time

# Assuming test.txt file has following 5 lines: # This is 1st line # This is 2nd line # This is 3rd line # This is 4th line # This is 5th line What will be the output of the following Python code? myfile = open("test.txt", "r+") print("Name of the file: ", myfile.name) for index in range(5): line = myfile.readline() print(f"Line No {index} - {line} ") myfile.close()

Displays Output Name of the file: myfile.txt Line No 0 - This is 1st lineLine No 1 - This is 2nd lineLine No 2 - This is 3rd lineLine No 3 - This is 4th lineLine No 4 - This is 5th line

What will be the output of the following code? import random print( random.choice( ['A','B','C', 1, 2, 3] ) ) Question

Either of 'A', 'B', 'C', 1, 2, or 3

What output is produced by the following code fragment? str = 'abcd' for x in range( len(str) ): print( x.upper(), end=' ')

Error

What will be the output of the following Python code? for x in range(2.0): print(x, end=' ')

Error

What will be the output of the following Python code? class test: def __init__( self, a ): self.a = a def display(self): print(self.a) obj=test() obj.display()

Error as one argument is required while creating the object

What output is produced by the following code fragment? x = 0 while x < 100: x *= 2 print(x)

Error. Go to infinite loop

A while statement always executes its loop body at least once.

False

All elements of a list must have the same type.

False

Every if statement requires an associated else statement, but not every else statement requires an associated if statement.

False

In Python, the symbol "=" and the symbol "==" are used synonymously (interchangeably).

False

Matplotlib is installed by default with Python.

False

The function must return a value.

False

What is "Hello World".replace( "l", "e")?

Heeeo Wored

What will be the output of the following Python code? def say(message, times = 1): print(message * times) say('Hello') say('World', 5)

HelloWorldWorldWorldWorldWorld

Which of the following best describes this code snippet? if (count != 400) print("Hello World!")

If the variable count is not equal to 400, "Hello World" will be printed.

Which of the following is used to define a block of code in Python language? Reserved key Indentation Brackets [ ] Parentheses ( )

Indentation

What error will be generated by the following Python code? myList = [1, 2, 3] print( myList [3] )

IndexError

A variable that exists in a single instance.

Instance attribute

Functions that are also class attributes.

Instance methods

Represents a single instance of a class.

Instance object

One important benefit of importing the sys modules as "import sys"; instead of, "from sys import *" is ? Question options:

It limits namespace conflict issues

What will be the output of the following Python code? student= ( 'Jack', 19, 3.6) result= ", ".join( str(d) for d in student ) print( student )

Jack, 19, 3.6

What output is produced by the following code fragment? str = "abcdef" while i in str: print( i, end=' ')

NameError, i is not defined.

What will be the output of the following Python code? def foo(): try: print( x + 4) finally: print('print finally block') print('print after finally block') foo( )

NameError: name 'x' is not defined

What is the output of print str[ : : 3 ] if str = 'Python Programming' ?

Ph oai

Does python code need to be compiled or interpreted?

Python code is both compiled and interpreted

About Python module, which statement is Not correct?

Python module is package.

Given the following tuple: my_tuple = (5, 10, 15, 25, 30) Suppose you want to update the value of this tuple at 3rd index to 20. Which of the following option will you choose?

The above actions are invalid for updating tuple

Which of these about a dictionary is false?

The keys of a dictionary can be accessed using values

A syntax error is a _____________________.

The program contains invalid code that cannot be understood. It is found before the program is ever run by the interpreter.

What is the value stored in sys.argv[0]?

The program's name

What is wrong, logically, with the following code? if x > 10: print("Large") elif x > 6 and x <= 10: print("Medium") elif x > 3 and x <= 6: print("Small") else : print("Very small")

There is no logical error, but there is no need to have (x <= 10) in the second conditional or (x <= 6) in the third conditional

Consider the following code that will assign a letter grade of 'A', 'B', 'C', 'D', or 'F' depending on a student's test score: if score >= 90: grade = 'A' if score >= 80: grade = 'B' if score >= 70: grade = 'C' if score >= 60: grade = 'D' else : grade = 'F'

This code will work correctly only if grade < 70

What will be the output of the following Python code if the input number is 100 ? valid = False while not valid: try: number =int(input("Enter a number: ")) while number % 2 == 0: print("This is even number") valid = True except ValueError: print("Invalid")

This is even number (print infinite number of times )

What will be the output of the following Python functions? import turtle t=turtle.Turtle() for i in range(0,3): t.forward(100) t.left(120) t.back(100) for i in range(0,3): t.forward(100) t.left(120) t.back(100) for i in range(0,3): t.forward(100) t.left(120)

Three triangles, joined at one vertex

A class can be used to group related variables together.

True

A function definition must be evaluated by the interpreter before the function can be called.

True

A local variable is defined inside a function, while a global variable is defined outside any function.

True

A program can modify the elements of an existing list.

True

Assume done = False; x = 10; y = 12 The expression not done or x > y is true.

True

Assume y = 11; str = "Goodbye" The expression len( str ) < y is true

True

Execution jumps to an except block only if an error occurs in the preceding try block.

True

The statement if a >= b : a = a+ 1 else : b = b -1 will do the same thing as the statement if a < b : b = b-1 else : a = a+1

True

What will be the output of the following Python code? >>> url ='https://ung.edu/' >>> url.startswith('http')

True

When using a with statement to open a file, the file is automatically closed when the statements in the block finish executing.

True

What are the outputs of the following Python script ? str = "abcd1234" print( str.isalnum( ) ) print( str.isalpha( ) ) print( str.isdigit( ) ) print( str.islower( ) ) print( str.capitalize( ) )

True False False True Abcd 1234

What error will be generated by the following Python code? print( int( '5.85') )

ValueError

What will be the output of the following Python code? def getMonth(month): if month<1 or month>12: raise ValueError( f"{month} is invalid in the month range" ) print(month) getMonth(20)

ValueError: ( 20 is invalid in the month range )

What will be the output of the following Python code? import time t=(2022, 11, 16, 10, 45, 12, 2, 0, 0) print( time.asctime( t ) )

Wed Nov 16 10:45:12 2022

When will the else part of try-except-else be executed?

When no exception occurs

What is the use of "w" in file handling?

Write

What will be the output of the following Python code? my_list= ["Apple","Ball","Cobra","Don","Accomplish"] my_list.sort( key=len ) print( my_list )

['Don', 'Ball', 'Apple', 'Cobra', 'Accomplish']

What is the output of print 'abcdefcdghcd'.split('cd') ?

['ab', 'ef', 'gh', '']

What is the output of print 'abcdefcdghcd'.split('cd', 1) ?

['ab', 'efcdghcd']

What will be the output of the following Python code? myList=["good", "oh!", "excellent!", "#450"] print( [item for item in myList if item.isalpha() or item.isdigit()] )

['good']

What is the content of mylist in the following Python's code fragment? mylist = [-12, -43, 55, 99, -32, 12, -2]mylist.insert(2, 67)

[-12, -43, 67, 55, 99, -32, 12, -2]

What is the output of the following python code fragment? values = [x**2 for x in range(0, 11)] print(values)

[0, 1, 4, 9, 16, 25, 36, 49, 64, 81, 100]

What will be the output of the following Python code? def foo( i, x=[ ]): x.append(i) return x if __name__ == "__main__": for i in range( 3 ): print( foo( i ) )

[0] [0, 1] [0, 1, 2]

What will be the value of 'result' in following Python program? list1 = [1,2,3,4] list2 = [2,4,5,6] list3 = [2,6,7,8] result = list() result.extend( i for i in list1 if i not in (list2+list3) and i not in result ) result.extend( i for i in list2 if i not in (list1+list3) and i not in result ) result.extend( i for i in list3 if i not in (list1+list2) and i not in result ) print(result)

[1, 3, 5, 7, 8]

What is the output of the following python code fragment?: list1 = [1, 2, 5, 7]list2 = [4, 2, 5, 3]print([item for item in list1 if item not in list2])

[1, 7]

What will be the output from the following Python code? x = ['a', 'b', 'c', 1, 2, 3] print( x [ : : -1] ) print( x [ : : 1] ) print( x [ : : 2] ) print( x [ 1: : 2] ) print( x [ 1 : 4] )

[3, 2, 1, 'c', 'b', 'a']['a', 'b', 'c', 1, 2, 3]['a', 'c', 2]['b', 1, 3]['b', 'c', 1]

What is the list comprehension equivalent for? {x : x is a whole number less than 20, x is even} (including zero)

[x for x in range(0, 20) if (x%2 ==0)]

A constructor method that initializes a class instance.

__init__

What will be the output of the following Python code? class Demo: def __init__(self): pass def test(self): print(__name__) obj = Demo() obj.test( )

__main__

Which of the following is a legal Python identifier? 1ForAll _oneForAll one/4/all one For all

_oneForAll

What output is produced by the following code fragment? str = 'abcd' for character in str: print(character, end=' ') str.upper()

a b c d

What output is produced by the following code fragment? str = "abcdef" i = 0 while i< len(str): print( str[i], end=' ') i += 1

a b c d e f

What will be the output of the following Python code? def func(a, b=5, c=10): print('a is', a, 'and b is', b, 'and c is', c) func(3, 7) func(25, c = 24) func(c = 50, a = 100)

a is 3 and b is 7 and c is 10 a is 25 and b is 5 and c is 24 a is 100 and b is 5 and c is 50

The readlines() method returns

a list of lines

In Python, a block statement is

a set of statements that are all indented to the same column.

What are the outputs of print the following statements ? 'xyyabcdxyy'.strip('xyy') 'xyyabcdxyy'.lstrip('xyy') 'xyyabcdxyy'.rstrip('xyy')

abcd abcdxyy xyyabcd

Which of the following is not an exception handling keyword in Python?

accept

A name following a "." symbol.

attribute

Which correctly defines two parameters x and y for a function definition:

calc_val (x, y) :

Given a function definition:def calc_val(a, b, c):and given variables i, j, and k, which are valid arguments in the call calc_val( )?

calc_val( k, i+ j, 99 )

As an argument, the plot() function of matplotlib.pyplot( ) ____

can accept two lists of x, y values for x, y coordinates

A group of related variables and functions

class

Which code can output "we will go to mountain" ?

class Foo: a = "mountain" def __init__(self, a): self.a = a def someday(self): return "we will go to " + Foo.a f1 = Foo("Hi, Jack") print(f1.someday())

To fix the error in the following Python code, which answer is correct? class Person: def __init__(self, the_last, the_first): last = the_last first = the_first def __str__(self): return( f"{last} {first} " ) p1 = Person( ) print( p1 )

class Person: def __init__(self, the_last, the_first): self.last = the_last self.first = the_first def __str__(self): return(f"{self.last} {self.first} " ) p1 = Person("AB","CD") print(p1)

_____ is used to create an object?

constructor

Suppose dictionary d1 = {"Susan":42, "John":40, "Peter":45} To get Susan's age, what command do we use?

d1.get("Susan")

Which keyword is used for function?

def

Suppose dictionary d1 = {"Susan":42, "John":40, "Peter":45} to delete the entry for "john" what command do we use?

del d1["John"]

Which of the following is NOT a valid way to define Python's dictionary?

dic = {('Albert': 23), ('Mary': 23), ('Simon': 43)}

To find distance between point (x1, y1) and point (x2, y2), which expression is correct?

distance = math.sqrt( (x2 - x1) * (x2 - x1) + (y2 - y1) * (y2 - y1) )

Matplotlib is a package that ____

enables creating visualizations of data using graphs and charts.

An exception handler for ValueError and NameError exceptions

except (NameError, ValueError):

An exception handler for NameError exceptions

except NameError:

A catch-all exception handler

except:

Which of the following for loop will cause the body of the loop to be executed 100 times?

for x in range (0, 100)

Which of the following can be a part of the Python module?

function class module

Which of the following expressions best represents the condition "if the grade is between 75 and 100"? Question options:

if 75 < grade and grade < 100 :

Suppose a function called add() is defined in a module called adder.py. Which of the following code snippets correctly show how to import and use the add( ) function? Select all that apply.

import adder result = adder.add(2, 3) from adder import add result = add(2, 3)

Which of the following is an incorrect syntax ?

import function from module

Which statement can create the following array by Numpy? [5, 15, 10, 20]

import numpy as np np.array( [5, 15, 10, 20] )

Which statement can create the following array by Numpy? [ [1, 1, 1] [1, 1, 1] [1, 1, 1] [1, 1, 1] ]

import numpy as np np.ones( (4, 3) )

An instantiation of a class

instance

What will be the output of the following Python code? try: if '1' != 1: raise "someError" else: print("someError has not occurred") except "someError": print ("someError has occurred")

invalid code

Given that str is a String, what does the following loop do? str = 'abcdef' for x in str[ : : -1 ] : print( x, end=' ')

it prints s out backwards: f e d c b a

Given that str is a String, what does the following loop do? str = 'abcdef' for x in str[ : -1 ] : print( x, end=' ')

it prints str out forwards: a b c d e f

What data type for [ 'abcd', 786 , 2.23, 'john', 10 ] ?

list

Assume, you are given two lists: list1 = [1,2,3,4,5] list2 = [6,7,8,9,10] Your task is to update list1 which has all the elements of list1 and list2. Which of the following python statement would you choose?

list1.extend(list2)

To remove given characters from the left end of the line, which operation is used in Python?

lstrip( )

In the try-except construct, how many except statements can have?

more than 0

Want to add 20 at 3rd place in my_tuple my_tuple = (5, 10, 15, 25, 30) And update the tuple as (5, 10, 15, 20, 25, 30) Which of the following code can help to realize the purpose?

my_tuple = (5, 10, 15, 25, 30)mylist = list(my_tuple)mylist.insert(3, 20)my_tuple = tuple(mylist)

To open a file c:\scores.txt for reading, we use____

myfile = open( "c:\\scores.txt", "r" )

Which function is used to close a file object myfile in python?

myfile.close()

To read the entire remaining contents of the file as a string from a file object myfile, we use____

myfile.read()

To read one line of the file from a file object myfile, we use ____

myfile.readline()

To read file's contents as a list of lines from a file object myfile, we use____

myfile.readlines()

What is the length of sys.argv?

number of arguments + 1

What output is produced by the following code fragment? limit =100; num1 = 15; num2 = 40 if limit <= 100 : if ( num1 == num2) : print( "lemon") print("orange")print( "grape")

orange grape

To open a file c:\scores.txt for appending data, we use____

outfile = open( "c:\\scores.txt", "a")

Which of the following is not built-in module in Python?

pi

Which command can help to install matplotlib in cmd terminal on Windows?

pip install matplotlib

What output is produced by the following code fragment? num = 1; max = 20 while num < max: if num%2 == 0: print( num, end=' ') num += 1

print even number from 2 to 18: 2, 4, 6, 8, 10, 12, 14, 16, 18

What output is produced by the following code fragment? for value in range (20, -1, -1): if value % 4 != 0: print( value, end=', ' )

print from 20 down to 0, except those that are evenly divisible by 4: 19, 18, 17, 15, 14, 13, 11, 10, 9, 7, 6, 5, 3, 2, 1,

Which of the following functions is a built-in function in python? randint( ) print() sqrt() factorial()

print()

For the following code, how to rewrite it by short hand if...else statement? if x > y: print( x + 1 ) else : print( y - 1 )

print(x + 1) if x > y else print(y-1)

Causes a ValueError exception to occur

raise ValueError

In file handling, what does "r+" means?

read or write

In file handling, what does this terms means "r, a"?

read, append

Assuming num1 = 1; num2 = 2 what output is produced by the following code fragment given the assumptions below? if num1 < num2 : print( 'red', end=' ')if (num1 +5) < num2 : print( 'white', end=' ' )else : print( 'blue', end=' ')print( 'yellow')

red blue yellow

What will be the output of the following Python code? colors = ('red', 'green', 'blue') rgb = '-'.join(colors)

red-green-blue

What will be the output of the following Python code? "abcdef".find("cd") == "cd" in "abcdef"

return False

A method parameter that refers to the class instance.

self

Assume str is 'abcd', to output it by upper case: A B C D. Which code fragment is correct?

str = 'abcd' for x in range(len(str) ): print( str[x].upper(), end=' ')

What is the output of print str[2:5] if str = 'Python Programming'?

tho

What is the output of print str[2: ] if str = 'Python Programming'?

thon Programming

Describes a block of code that uses exception-handling

try:

Which function is used to write all the characters?

write()

Which function is used to write a list of string in a file?

writelines()

Which of the following is an example of an invalid assignment or declaration statement? age = 30 money, dollars = 0; cents = 0 years = 1; months = 12; days = 365 x + 1 = 3

x + 1 = 3

Assume x = ['a', 'b', 'c', 1, 2, 3], to print items backward in x, which following code is NOT correct?

x = ['a', 'b', 'c', 1, 2, 3] for i in ''.join( reversed(x) ): print(i, end=' ') print()

Which statement reads value as integer type? x = input( ) x = input( 'Enter an integer' ) x =int( input( 'Enter an integer' ) ) x, y = input( 'Enter two integer' ).split( )

x =int( input( 'Enter an integer' ) )

What will be the output of the following Python code? x = 50 def func( ): global x print('x is', x) x = 2 print('Changed global x to', x) func( ) print('x is now', x)

x is 50 Changed global x to 2 Value of x is 2

What will be the output of the following Python code? x = 50 def func(x): print('x is', x) x = 2 print('Changed local x to', x) func(x) print('x is now', x)

x is 50 Changed local x to 2 x is now 50

What will be the output of the following Python code? dict1 = {1:"A", 2:"B", 3:"C"} dict2 = {4:"D", 5:"E"} dict1.update(dict2) dict3 = dict1.copy( ) dict3[ 2 ] = "Change" print(dict3)

{ 1: 'A', 2: 'Change', 3: 'C', 4: 'D', 5: 'E' }

What will be the output of the following Python code? total={} def insert( items ): if items in total: total[items] += 1 else: total[items] = 1 insert('Apple') insert('Banana') insert('Apple') insert('Orange') insert('Apple') insert('Orange') print( total )

{'Apple': 3, 'Banana': 1, 'Orange': 2}

What will be the output of the following Python code? numbers = {} letters = {} comb = {} numbers['Josh'] = 89 numbers['Alex'] = 95 letters[1] = 'B' letters[2] = 'A' comb['Numbers'] = numbers comb['Letters'] = letters print( comb ) print( comb.get( 'Numbers') ) print( comb.get( 'Letters').get(2) )

{'Numbers': {'Josh': 89, 'Alex': 95}, 'Letters': {1: 'B', 2: 'A'}} {'Josh': 89, 'Alex': 95} A


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

Chapter 16: Legal Guidelines and Business Considerations

View Set

Chapter 11 Nervous System and Nervous Tissue

View Set

Basic Coding-Ch.50 (I feel bad love, I feel sad love, Sometimes happy love)

View Set