Python Code Flashcards

(51 cards)

1
Q

How to print Hello to terminal?

A

print(“Hello”)

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
2
Q

How to create variable x and then assign value 10 or maybe Hello?

A

x = 10
x = “Hello”

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
3
Q

What symbol is called the assignment operator?

A
  1. =
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
4
Q

What is the difference between :
1. d = 1 + 4
2. d = “Hello” + “ World”

A
  1. 5
  2. Hello World
    • in string is called concatenation
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
5
Q

How to know what type value is it in python?

A

e = 1
y = “Hello”
z = 42.0

type(e)
<type ‘str’>

type(y)
<type ‘int’>

type(z)
<type ‘float’>

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
6
Q

How to change string 123 toint?

A

e = “123”
e_int = int(e)

  • Using int() , str() or float()
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
7
Q

How to input from user?

A

name = input(“Name : “)
print(name)

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
8
Q

List out 2 methods for commenting

A
  1. # ( Single-line Comment )
  2. ”””””” ( Multi-line Comment )
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
9
Q

How to print Hi using multiple 5?

A

print ( “Hi” * 5 )

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
10
Q

What code do we need to put semicolons ?

A
  1. if, elif , else
  2. for, while
  3. try, except
  4. def ( functions )
  5. File Handling ( with open (“g.txt” , “r”) as f : )
  6. Class Definitions
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
11
Q

List out all relational operators

A
  1. < Less than
  2. > Greater than
  3. == Equal to
  4. <= Less than or equal to
  5. > = Greater than or equal to
  6. != or <> Not equal to
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
12
Q

List out all logical operators

A
  1. && ( And )
  2. || ( Or )
  3. ! ( Not )
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
13
Q

Write a program to display the below conditions
1. Below 18 - Not Ok
2. Above 18 & Below 60 - OK
3. Above 60 - Old

A

age = int(input(“Age : “))
if ( age < 18 ):
print(“Not Ok”)
elif ( age >= 18 ) and ( age < 60 ):
print(“Ok”)
else:
print(“Old”)

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
14
Q

How to receive only int input and print out error message when entering wrong values?

A

try:
age = int(input(“Age : “)
print(“Your age : “ , age )
except ValueError:
print(“Please enter integer values only!”)

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
15
Q

List out all the loops type ( 2 )

A
  1. While Loops
  2. For Loops
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
16
Q

How to use loop to display integers from 10 to 30?

A

i = 10
while i <= 30:
print(i)
i += 1
print(“End”)

for i in range(10,31):
print(i)

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
17
Q

How to loop using Lists?

A

pokemon = [“Pikachu”,”Zacian”,”Gengar”]
for i in pokemon:
print( i , “had been registered to pokedex”)

  • If it was print( pokemon , “had been registered to pokedex”), it will have below input for 3 times

[‘Pikachu’, ‘Zacian’, ‘Gengar’] had been registered to pokedex

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
18
Q

How to sum inside a loop?

A

total = 0
for i in [9 , 41, 12, 3, 74, 15]:
print(f”Total = {total} + {i}”)
total = total + i
print(total)

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
19
Q

How to find the average in the loop?

A

total = 0
count = 0

for i in [9 , 41, 12, 3, 74, 15]:
total = total + i
count += 1
print(f”Average = {total} / {count}”)
average = total / count
print(f”Average = {average}”)

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
20
Q

How to filter the loop, given a list [9 , 41, 12, 3, 74, 15] which requires to print values that is greater than 20?

A

for i in [9 , 41, 12, 3, 74, 15]:
if i > 20:
print(i)

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
21
Q

How to search using the Boolean Variable? ( Given list [9 , 41, 12, 3, 74, 15] find value 3 )

A

found = False
for i in [9 , 41, 12, 3, 74, 15]:
if i == 3:
print(“3 is in the list”)
found = True
print(“Found : “ , found )

22
Q

How to find the smallest value? ( Given list [9 , 41, 12, 3, 74, 15] find the smallest value )

A

small = 0
for i in [9 , 41, 12, 3, 74, 15]:
if small == 0:
small = i
elif i < small:
small = i
print(“Smallest : “, small)
print(“Most Smallest Value : “ , small)

23
Q

Which is Parameter of Arguments?
1. def print_msg(msg_text):
2. print_msg(“Good Morning”)

A
  1. Parameter
  2. Arguments
24
Q

What is the difference between Non-Fruitful and Fruitful Function?

A
  1. Fruitful functions will produce a result ( return value ) while Non-Fruitful Function will won’t return a value
25
Try to define a functions to print message from it
def print_msg(msg) print(msg) print_msg("Good Morning")
26
How to read from file?
with open ( "user.txt" , "r" ) as f: for line in f: print(f) f = open( "user.txt", "r" ) for line in f: print(line)
27
How to write into file?
user_name = input("Username : ") f = open ( "user.txt" , "a" ) f.write(f"{name}) f.close() print("Record added") with open ( "user.txt" , "a") as f: f.write(user_name) print("Record Added")
28
How to count how many lines in a file?
count = 0 with open ( "staff.txt" , "r" ) as f: for line in f: count = count + 1 print(count)
29
How to search through a file?
with open ( "staff.txt" , "r" ) as f: for line in f: if line.startswith("Jill") print(line)
30
How to read from a file without blank spaces of lines?
with open ( "staff.txt" , "r" ) as f: for line in f: staff_details = f.strip() print(staff_details)
31
How to skip a record? ( Skip printing Jack )
with open ( "staff.txt" , "r" ) as f: for line in f: line = line.rstrip() if line.startswith("Jack"): continue print(line)
32
How to select Jack records using in?
with open ( "staff.txt" , "r" ) as f: for line in f: line = line.rstrip() if "Jack" in line: print(line)
33
What error will be getting here? zot = "abc" print(zot[5])
Index Error
34
How to know the lenfth of a banana?
fruits = "banana" print(len(fruits)) # 6
35
How to show b a n a n a
fruits = "banana" k = 0 while k < len(fruits): print(fruits[k]) k += 1
36
How to find how many a's is in the banana word?
fruits = "banana" count_a = 0 for letter in fruits: if letter =="a" count_a = count_a + 1 print(count_a) * letter in for letter in fruits is just like for i in fruits
37
How to let python returns True is there is na in banana?
fruits = "banana" print("na" in fruits) # True print("ta" in fruits) # False
38
Create a variable with the value Monty Python on it, then print out the following condition using Slicing Strings: 1. Mont 2. P 3. Python 4. Mo 5. thon 6. Monty Python
s = "Monty Python" 1. print(s[0:4]) 2. print(s[6:7]) 3. print(s[6:]) / print(s[6:20]) 4. print(s[:2]) / print(s[0:2]) 5. print(s:[8:]) / print(s[8:12]) 6. print(s[:])
39
List out indexing method
1. Basic Indexing - [1] Return character at index 1 - [ -1 ] Return the last character 2. Slicing Notation - [ start : end ] - [ : ] Returns the entire sequence - [ 2 : ] Returns from index 2 to end - [ : 2 ] Returns from the beginning to the end index ( not include the end character ) - [ 1 : 3 ] Returns from index 1 to 2 3. Slicing with Step - [ start : end : step ] - [ :: 2 ] Return every second character from start to end - [ 1: : 2 ] Return every second character starting from index 1 - [ :: -1 ] Return the reversed value ( banana to ananab
40
List out the built in String Library Functions ( 3 )
1. count 2. endswith 3. lower ( .lower() )
41
How to search the character "na" from banana and change it to "z"?
fruit = "banana" search = fruit.find("na") print(search) # Returns the index change = fruit.replace("na","z") print(change) # bazz
42
How to output the string from " banana " to below? 1. banana 2. banana 3. banana
fruit = "banana" 1. fruit.lstrip() 2. fruit.rstrip() 3. fruit.strip()
43
How to split strings?
line = "John, john@mail.com" name,email = line.strip.split(",") print(f"Name : {name}" print(f"Email : {email}"
44
How to create a new list using range to generate from 0 to 10 and 2 to 6?
1. new_list = list(range(10)) 2. new_list = list(range(2,7)) * Or we can manually add new_list = [ 2 , 3 , 4 , 5 , 6 ]
45
How to add new data to list with the condition below: 1. Add 3 to the last of the list 2. Add 3 to the first index
new_list = [1 , 2 , 3] 1. new_list.append(3) # [1 , 2 , 3 , 3] 2. new_list[1] = 3 # [1 , 3 , 3]
46
How to scan through the list ? [ 3 , 4, 5, 6 ]
new_list = [ 3, 4 , 5, 6 ] for i in new_list: print(i)
47
How to search 4 in the list ? [ 3 , 4, 5, 6 ]
new_list = [ 3 , 4 , 5 , 6 ] for i in new_list: if ( i == 4 ): print( i , "found in the list" )
48
List out the list functions for sum, len, pop , insert and remove
1. sum(new_list) # Returns the sum of integers 2. len(new_list) # Return the length of the list 3. pop(2) # Removes element at index 2 4. insert ( 0, 200 ) Insert at position 0 the element 200 5. remove(20) # removes element 20 from the list
49
How to add items into dictionary?
newStudent = {} newStudent['TP'] = "TP123456" newStudent['Name'] = "John" Output : newStudent = { 'TP' : "TP123456" 'Name' : "John" } * Access Dictionary Items print(newStudent.get("Name"))
50
How to write inside json file?
userDetails[f"user_{un}"] = {'username' : un , 'password' : pw , 'email' ; em } with open( "users.json" , "w" ) as f: json.dump(userDetails, f , indent = 2 )
51
How to read from json file?
with open( "users.json" , "r" ) as f: allUsers = json.load(f) for id, userData in allUsers.items(): print("\n") print(f"Username = {userData['username']}"