12
12.1
An inflatable kayak.
"int"
10020
3.14
5 + 5.1 =
10.1
55.1
"5.1, 5"
"5" + "5.1" =
"55.1"
'55.1'
capitalize()
title()
upper()
Python can be used in data science
Python works on all major operating systems
Python cannot be used to make desktop applications
username = 'eagle05'if len(username) >= 7: print("Your username is valid!")
eagle05
Your username is valid!
Your username is not valid!
technical_data = {"strength": 115.5, "density": 15.1}technical_data = dict(strength=115.5, density=15.1)
They both create the same object.
They both have the same syntax.
They both use the same third-party library.
seq = list(dict(x=str(2), y=(str(3))))
Dictionary
List
Tuple
ltr = ['a', 'd', 'l', 'i', 'e', 's', 'm']print(ltr[-2] + ltr[-1] + ltr[3] + ltr[2] + ltr[-3])
if a == 3: print("Correct")
if (a == 3) { System.out.println("Correct");}
load at x3000. X3000 0010 001 0 0000 0110; LD R1, x006 x3001 0110 010 001 000000
planets = ("Mars", "Earth", "Venus")
planets is a list of four items
planets is a list of three items
planets is a tuple of three strings
coordinates = (10.1, 11.2)
company = {'employees': 14, 'managers':3}
grades = ['F', 'D', 'A', 'C']
grades = ( 8, 9, 10, 9, 7)
grades = { 9, 8, 7, 9, 10}
Inventory( '55', '88', '99')
Inventory == ( 55, 66, 88)
Inventory = ( 55, 66, 88, 99)
A dictionary
A numpy array
A pandas dataframe
a = "10.1"
Float
Integer
String
A class
A function definition
A function call
planet = ["Saturn", 100911.1, [1, 2, 3]]
3
5
6
print("anastasia".title())
ANASTASIA
Anastasia
"Anastasia"
print("anastasia".count(a))
4
2
Traceback (most recent call last): File "", line 1, in NameError: name 'a' is not defined
Tuples accept only numbers.
They are the same.
Immutability
chars = [1, 'a', 2, 'b']print("-".join(chars))
'1-a-2-b'
['1-a-2-b']
max(4, 5, 6) + min(4, 5, 6)
30
15
10
def foo(x): if x * 2
def foo(x): print x * 2
def foo(x): return x * 2
26. What is "==" in Python?
Assignment operator
Comparison operator
else
return
elif
int
len
print(10
a = [1, 2, 4)
c = 12
for item, value in d.items(): if '_' in item: sent_email(value)
for item in d: if '_' in item: sent_email(value)
if '_' in item: for item, value in d.items(): sent_email(value)
a = 10if a > 10: print("Positive number") else: print("Negative number")
a = 10if a > 10: print("Positive number") elif: print("Negative number")
a = 10if a > 10: print("Positive number") next: print("Negative number")
He is iterating over an int instead of a float.
He is applying a for loop with to the wrong object.
He has declared the int object as non-iterable.
Welcome Jesuela
username = "Jesuela"message = f"Welcome {username}"print(message)
username = "Jesuela"message = "Welcome" + " " + usernameprint(message)
username = "Jesuela"message = "Welcome "print(message.join(username))
usernames = ['low_66', 'berrets%', 'sunshade_001']
usernames = [username for username in usernames if '%' not in username]
usernames = [username for username in usernames if '%' in username]
usernames = [username for username in usernames when '%' ]
def foo( a, b=10) if b == 10: return a + bprint(foo(3))
13
TypeError: foo() missing 1 required default argument: 'b'
processors = {'stock': ['i345', 'i796'], 'sold': ['i114', 'i931']}print(processors['sold'][-1])
i345
i796
i931
molecules = [i.upper() for i in molecules]
molecules = [for i in molecules convert(i)]
molecules = [for i in molecules uppercase(i)]
data = [13, 145, 55, 88, 190, 98]data = float(x) for x in data
data = [13, 145, 55, 88, 190, 98]data = [float(x) for x in data]
data = [13, 145, 55, 88, 190, 98]data = (float(x) for x in data)
pandas.DataFrame([[2, 4, 6], [10, 20, 30]])
for i, j, k in [1, 2, 3]: print(i)
123
1
The code will produce an error.
define rectangle_area(a, b): print(a * b)area = rectangle_area(2, 4)print(area)
8
None
8None
list1 + list2
list1.merge(list2)
list1.append(list2)
for i in range(0, 5, 2): print(f"{i}_file.pdf")
0_file.pdf5_file.pdf2_file.pdf
0_file.pdf2_file.pdf4_file.pdf
0_file.pdf1_file.pdf2_file.pdf3_file.pdf4_file.pdf0_file.pdf1_file.pdf2_file.pdf3_file.pdf4_file.pdf
import cv2capture = cv2.VideoCapture(0)
The code starts recording a video from a Canon camera.
The code imports the OpenCV Python library and starts the camera.
The code captures a video using 0 colors.
output1 = cv2.cvtColor(input_variable, cv2.COLOR_BGR2GRAY)
import foliumm = folium.Map(location=[45.5236, -122.6750]) m.save("map.html")
team = []
team = [1, 2, 3]
team.append(1)
An integer
We cannnot tell given the information we have.
A string
x = y['z']
What would z most likely be?
A list item
A dictionary key
A dictionary value
for i in range(10): if i > 5: print(1)
7
9
0
a = [1, 2, 3] b = [ ] for i in a: b.append(str(i)) a = b
a = [1, 2, 3]for i, j in a: a.append(str(i)) a.remove(j)
a = [1, 2, 3]a = [str(i) for i in a]
a = [1, 2, 3]a = [str(i) if isinstance(i, int)]
value = input("Enter day temperature: ")print("At night is going to be ", value - 10)
At night is going to be 20
TypeError: unsupported operand type(s) for -: 'str' and 'int'
def foo(x=1, y=2, z): return x + y + zprint(foo(5, 6, 7))
18
names = ["John.Smith", "Merry.Smith"]names = [name.replace(".", "") for name in names]
names = ["John.Smith", "Merry.Smith"]names = [name.remove(".") for name in names]
names = ["John.Smith", "Merry.Smith"]names = [name.split(".") for name in names]
'wr'
'r+'
'w' AND 'r'
import string, randomx = ' 'for i in range(3): x = x + random.choice(string.ascii_lowercase)print(x)
The code prints the first three characters of ASCII
The code generates a list of three random letters
The code generates a random string
Tkinter
Beautiful Soup
Pandas
Expected output:JohnMerry
data = [{'name':'john', 'surname':'smith'}, {'name':'merry', 'surname':'koo'}]for i in data: print(i['name']title())
data = [{'name':'john', 'surname':'smith'}, {'name':'merry', 'surname':'koo'}]for i in data: print(i name.title())
data = [{'name':'john', 'surname':'smith'}, {'name':'merry', 'surname':'koo'}]for i in data: print(iName.title())
zip()
datetime()
lower()
secret_variable = "ce42qb"
for i in secret_variable:if i == int:secret_variable.remove(i)
for i in secret_variable:if i == int:secret_variable.replace(i, "")
None of them.
Loop with a for-loop through the video frames and show each video frame on the screen
Execute opencv with a loop() method and a show() method
Loop through the pixels of each video and show each show them on the screen
file = open("sample.txt", "w")file.write("Hi!\nIt's a beautiful day!")file.close()
Hi!It's a beautiful day!
Hi! It's a beautiful day!
Hi!\nIt's a beautiful day!
It imports the y integer from the x float.
It imports the y object from the x library.
It imports the x object from the y library.
data = [{'name':'john', 'surname':'smith'}, {'name':'merry', 'surname':'koo'}, {'name':'yash', 'surname':'sun'}]for i in data: if i['name'].startswith('j'):
Expected output:
smith
print(iSurname)
print(i(surname))
print(i['surname'])
filename = "aka.csv"
What code would change "aka.csv" to "aka.txt"?
filename = filename.replace(Filename.split(".")[1], "txt")
filename = filename.split(".")[0] + ".txt"
filename = filename.remove("csv").append("txt")
while True:foo()time.sleep()
loop()call()sleep()
for i in range(): foo()time.sleep()
What does the code below output?
(1, 2, 3) + (4, 5, 6)
(1, 2, 3, 4, 5, 6)
[1, 2, 3, 4, 5, 6]
21
[str(i) for i in mylist if isinstance(i, int)]
The code changes mylist by retaining only its integer items.
The code converts all the items of mylist items to strings.
The code does some sort of filtering of the mylist items.
file = open("sample.txt", "w")aka = file.read("Something beautiful")print(aka)
It would output Something beautiful.
We can't tell what the output will be since we don't know what the file has inside.
The code will output an error.
def foo(x): if x > 0: return 1 else: return 2
The function takes two arguments.
The function may return either 1 or 2, but not both.
The function returns 1 if x is a positive number.
Jim's programming skills are equivalent of a cat's programming skills.
Jim's function definition has too many parameters.
Jim's foo function call has too many arguments.
An executable integer
An executable float
An SQL expression as a string
Python can interact with database systems
Database systems are designed to internally execute Python code
Python can send SQL code which can then be executed internally by a database system
SQLite
PostGreSQL
MySQL
By putting the function call inside a print function
By adding a print inside the function definition
By replacing “return” with “print” inside the function definition
i = 6filename = f"{i}_file"print(filename)
i = 6filename = f"i_file"print(filename
i = 2 * 3filename = {i} + "_file"print(filename)
import cv2x = cv2.imread("galaxy.jpg")
An image file
A cv2 array
y = float({'a':(1,2,3)}['a'][1] + int(float('3.65')))
5.56
4.65
An argument
A decorator
An email domain
What would the Flask frontend created by the below code look like?
@app.route('/')def foo(): return "<h1>Hello world!</h1>"
app.route('/')def home(): return render_template("home.html")
It renders a function template
It renders a template in the Python shell
It produces an HTML page
import pandasdf = pandas.load("usernames.txt")df = df.filter(['logins'] >0])df.to_csv("usernames_filtered.txt", index=False)
import pandasdf = pandas.read_csv("usernames.txt")df = df[df['logins'] >0]df.to_csv("usernames_filtered.txt", index=False)
import pandasdf = pandas.read("usernames.txt")df = df.filter_less(['logins'] >0])df.to_csv("usernames_filtered.txt", index=False)
pandas
numpy
class
import requestsr = requests.get("https://pythonhow.com")x = r.content
Python code
HTML code
PHP code
Entry
Input
UserInput
What does the code below create?
tkinter.Label(window, "Ontohome")
A Label widget with label "Ontohome"
A tkinter window with label "Ontohome"
A Label widget in the "Ontohome" window
(7, 6)
(5, 6)
When is the "foo" function called by Python?
app.route('/')def foo(): return render_template("home.html")
When the user visits the homepage of the website
When a foo() call is found in the home.html code
When the user enters a slash ('/') symbol in the Python shell
con = sqlite3.connect("database.db")
con.download()
con.upload()
con.cursor()
app = Flask(__name__)
It creates a Flask app instance
df = pandas.DataFrame([[2, 4, 6], [10, 20, 30]])x = sum(df.loc[1])
24
60
df = pandas.DataFrame([[2, 4, 6], [10, 20, 30]])df.to_csv("test.csv", header=None, index=False)
value = input("Distance in miles : ")print(str(value) * 1.609344)
value = input("Distance in miles : ")print(float(value) * 1.609344)
value = input("Distance in miles : ")print(int(value) * 1.609344)
pandas.duplicate()
df.drop_duplicates()
pandas.drop_duplicates()
class Robot: def __init__(self, name, mood="quiet"): self.name = name self.mood = mood def set_mood(self, user_mood): self.mood = user_moodrobo = Robot("Robo", "agitated")robo.set_mood("playful")print(robo.mood)
quiet
agitated
playful