CS Midterm Questions
Formatting numbers using the format() function
# Python3 program to demonstarte # the str.format() method # using format option in a simple string print ("{}, A computer science portal for geeks." .format("GeeksforGeeks")) # using format option for a # value stored in a variable str = "This article is written in {}" print (str.format("Python")) # formatting a string using a numeric constant print ("Hello, I am {} years old !".format(18))
for x in range(5): print (x)
0 1 2 3 4
for x in [0, 5]: print (x)
0 5
for x in [1,2,3,4,5]: print (x)
1 2 3 4 5
for p in range(1,10): print (p)
1 2 3 4 5 6 7 8 9 always includes left bound but never right bound
5 % 2
1 integer
x = 10 y = 0 while x > y: print (x, y) x = x - 1 y = y + 1
10 0 9 1 8 2 7 3 6 4
for q in range(100,50,-10): print (q)
100 90 80 70 60
keepgoing = True x = 100 while keepgoing: print (x) x = x - 10 if x < 50: keepgoing = False
100 90 80 70 60 50
c = 0 for x in range(10): for y in range(5): c += 1 print (c)
50 (y run 5 times per 1 run of x because x is A bigger loop)
'5' + '2'
52 string
'5' * 2
55 string
commenting code
Comments in Python start with the hash character, # , and extend to the end of the physical line. A comment may appear at the start of a line or following whitespace or code, but not within a string literal. A hash character within a string literal is just a hash character.
**
Exponent Performs exponential (power) calculation on operators a**b = 10 to the power 20
//
Floor Division - The division of operands where the result is the quotient in which the digits after the decimal point are removed. But if one of the operands is negative, the result is floored, i.e., rounded away from zero (towards negative infinity) − 9//2 = 4 and 9.0//2.0 = 4.0, -11//3 = -4, -11.0//3 = -4.0
!=
If values of two operands are not equal, then condition becomes true. (a != b) is true.
<>
If values of two operands are not equal, then condition becomes true. (a <> b) is true. This is similar to != operator.
%
Modulus Divides left hand operand by right hand operand and returns remainder b % a = 0
*
Multiplication Multiplies values on either side of the operator a * b = 200
Trace the output for: a = 10 b = 20 c = 30 if c > b + a: print ("N\nY\nU\n") else: if b + a >= c: print ("C\nO\nU\nR\nA\nN\nT\n") else: print ("S\nT\nE\nR\nN\n") print (a,b,c)
N Y U 10 20 30 >>>
Syntax Errors
Occur when the programmer does not follow the rules of the programming language. ie forgetting a comma or name = "Jim. Misspelling a keyword is a common syntax error.
str.lower
Return a copy of the string with all the cased characters [4] converted to lowercase. Case manipulation (x = str.lower('CRAIG') # converts the string literal 'CRAIG' to 'craig')
len
Returns the number of characters in a text string len('cat') 3 integer
Identify three functions that convert data from one data type to another. Provide a practical example of each function and describe when you would use it in an actual program.
The float(), int() and str() functions convert data from one data type to another. Here are a few examples: # turn the user's input into a floating point number answer = float(input("Enter a number: ")) # turn a String into an integer a = "525" b = int(a) # convert a number into a String a = 525 b = str(a)
Imagine you have the following while loop. Describe two different ways to stop this loop from iterating(repeating). keepgoing = "yes" while keepgoing == "yes": # statements go here
You could call the "break" statement from within the loop or you could flip the value of "keepgoing" to something other than "yes" keepgoing = "yes" while keepgoing == "yes": break
+=, -=, *=, /=, %=
c += a is equivalent to c = c + a c -= a is equivalent to c = c - a c *= a is equivalent to c = c * a c /= a is equivalent to c = c / ac /= a is equivalent to c = c / a c %= a is equivalent to c = c % a c **= a is equivalent to c = c ** a c //= a is equivalent to c = c // a
for statements
for loops are traditionally used when you have a block of code which you want to repeat a fixed number of times. for x in range(0, 3): print "We're on time %d" % (x)
format
format(5.1, '.2f') 5.10 string format(5.1, '>10.2f') "5.10" string
/n
new line
escape characters
print 'apple', 'orange', 'pear' apple orange pear print ('apple\torange') apple orange print ('apple\norange') apple orange
Multiplying a string (x = 'hi' * 5)
print 'red' * 3 Redredred
random.randint
returns randoms integers random.randint(start, end) (start, end) : Both of them must be integer type values. A random integer within the given range as parameters. random.randint(1,5) 3 integer
'/t'
space between things you print and goes to another line
variables
x = ... y = ....
Boolean variables
a variable which stores a Boolean value (true or false). 10 > 2 True Boolean 2 < 1 False Boolean 2 != 4 True Boolean 4 == 2**2 True Boolean 'cat' < 'dog' True Boolean 'Cat' < 'dog' True Boolean 5 > 2 and 10 > 11 False Boolean 5 > 2 or 10 > 11 True Boolean 5 > 2 and not (10 > 11)True Boolean
for y in range(500,100,100): print ("*", y)
no output
x = 10 y = 5 for i in range(x-y*2): print ("%", i)
no output because 10-10 = 0, and a range of 0 won't run because it's not a range
Concatenation
str1 = "Hello" str2 = "World" str1 + str2 Python cannot concatenate a string and integer. print 'red' + 'yellow' Redyellow >>> print 'red' * 3 Redredred >>> print 'red' + 3 Traceback (most recent call last):
sep="
tells R to not separate objects by a space #code for disabling the softspace feature print('G','F','G', sep='') #for formatting a date print('09','12','2016', sep='-') #another example print('pratik','geeksforgeeks', sep='@') Output: GFG 09-12-2016 pratik@geeksforgeeks print('C','O','D','E', sep='')
Write a program that continually asks the user for a series of prices. Keep track of the running total as the user enters prices. Prompt the user after each price to see if they wish to continue entering prices. When they are finished, print out the total amount entered.
total = 0 again = "yes" while again == "yes": p = float(input("Enter a price: ")) total += p again = input("Enter another price? (yes or no): ")
str.upper
*uppercases* string
for z in range(-500,500,100): print (z)
-500 -400 -300 -200 -100 0 100 200 300 400 (Jumps positively because it starts at A negative number, if you tried -100, nothing would pop up because that's out of the range)
for x in range(3): for y in range(4): print (x,y,x+y)
0 0 0 0 1 1 0 2 2 0 3 3 1 0 1 1 1 2 1 2 3 1 3 4 2 0 2 2 1 3 2 2 4 2 3 5 the range on top determines the columns, 12 rows because 3 x 4 = 12
Convert 1ffd from hexadecimal to binary
0001 1111 1111 1101
x = 0 while True: x += 1 print (x) if x ** 2 > 36: #x squared break elif x % 2 == 0: continue # if remainder = 0 continue. Go back to while true print ("looping!")
1 looping! 2 3 looping! 4 5 looping! 6 7
for x in [1,2,3]: for y in [4,5,6]: print (x,y)
1 4 1 5 1 6 2 4 2 5 2 6 3 4 3 5 3 6
Explain what a Boolean expression is and why you would use one while programming. Give three examples
A Boolean expression is an expression that compares two or more values. It almost always involves the use of a relational operator (>, <, ==, !=, etc) and always evaluates to True or False. We use Boolean expressions in Python to ask a question (i.e. if number < 0 then print "no negative numbers allowed!"), to control a repetition structure (i.e. while keepgoing == True, perform some operation) and to store a logical value in a variable (i.e. answer = 5 > 2)
function
A function is a block of organized, reusable code that is used to perform a single, related action. Functions provide better modularity for your application and a high degree of code reusing.
end=
A keyword parameter for the print() function that causes the function to NOT add a newline at the end of the string. print("Python" , end = '@') print("GeeksforGeeks") Output : Python@GeeksforGeeks print("Welcome to" , end = ' ') print("Code Speedy") Welcome to Code Speedy
Run-time Error
An error in a program that makes it impossible to run to completion. Also called an "exception" ie. print("you cannot add text and numbers" + 12), or print(1/0), or callMe = "Maybe" print(callme) division by zero performing an operation on incompatible types using an identifier which has not been defined accessing a list element, dictionary value or object attribute which doesn't exist trying to access a file which doesn't exist
Explain the differences and similarities between the "if" statement and a "while" statement in Python
Both an "if" and "while" statements utilize Boolean expressions. In the case of an "if" statement, if the attached Boolean expression evaluates to True then the body of the "if" statement will execute one time. In the case of a "while" statement, if the attached Boolean expression evaluates to True, then the body of the "while" statement will execute, and then the condition will be re-evaluated at the end of the statement to see if it is still True - if so the body of the "while" statement will be executed again.
Trace the output for: a = 10 b = 20 c = 30 if c > b + a: print ("N\nY\nU\n") else: if b + a >= c: print ("C\nO\nU\nR\nA\nN\nT\n") else: print ("S\nT\nE\nR\nN\n") print (a,b,c)
C O U R A N T 10 20 30
/
Division Divides left hand operand by right hand operand b / a = 2
Logical Error
Errors in the program that occur when there is a fallacy in reasoning and is caught when the program executes. They occur when the program runs without crashing, but produces an incorrect result. The error is caused by a mistake in the program's logic. using the wrong variable name indenting a block to the wrong level using integer division instead of floating-point division getting operator precedence wrong making a mistake in a boolean expression off-by-one, and other numerical errors
count = 0 while count < 10: print ('Hello') count += 1
Hello Hello Hello Hello Hello Hello Hello Hello Hello Hello (TEN HELLO'S)
Name and describe three different data types in Python and when they could be used in a program
Integer: used to store whole number values. Useful for creating "counter" accumulator variables. Float: used to store floating-point numbers. Useful for storing currency values. String: used to store sequences of characters, such as "Hello, World!"
float
Integers, floating point numbers and complex numbers fall under Python numbers category. They are defined as int, float and complex class in Python. 0.0 num = float(input("Enter a number:")) print(num)
Data types
Integers, floating point numbers and complex numbers falls under Python numbers category. They are defined as int, float and complex class in Python.
a = 5 b = 6 c = 20 d = 24 if a < b and b * 2 < c: print ("Python Case 1") print ("A", '\t', "B", '\t', "C") if a * 2 == c: print (a*2, '\t', a*2, '\t', a*2) elif a * 3 == c: print (a*3, '\t', a*3, '\t', a*3) elif a * 4 == c: print (a*4, '\t', a*4, '\t', a*4) else: print ('?', '\t', '?', '\t', '?') else: print ("Python Case 2") print ("a", '\t', "b", '\t', "c") if b * 2 == d: print (b*2, '\t', b*2, '\t', b*2) elif b * 3 == d: print (b*3, '\t', b*3, '\t', b*3) elif b * 4 == d: print (b*4, '\t', b*4, '\t', b*4) else: print ('?', '\t', '?', '\t', '?')
Python Case 1 A B C 20 20 20
not
The not keyword is a logical operator. The return value will be True if the statement(s) are not True, otherwise it will return False.
a = 5 b = 10 c = 25 if a + b == c: print ("X1") else: if c == a + b*2: print ("Y1") elif a == c - 2 * b: print ("Y2") else: print ("Y3")
Y1
x = 'cupid' z = 'arrow' if x < z: t = x x = z z = t v = x + " <--> " + z if ( ( (5 + 2 >= 6.0) and (1.0 < 0.5) ) or True): print (x,z,v, sep='\t') else: print (v,z,x, sep='\n')
cupid arrow cupid <--> arrow
Write a program that prints out all even numbers between 1 and 100,000.
for i in range(2, 100001, 2): print (i)