Python Code Flashcards

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
Q

Try to define a functions to print message from it

A

def print_msg(msg)
print(msg)

print_msg(“Good Morning”)

26
Q

How to read from file?

A

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
Q

How to write into file?

A

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
Q

How to count how many lines in a file?

A

count = 0
with open ( “staff.txt” , “r” ) as f:
for line in f:
count = count + 1
print(count)

29
Q

How to search through a file?

A

with open ( “staff.txt” , “r” ) as f:
for line in f:
if line.startswith(“Jill”)
print(line)

30
Q

How to read from a file without blank spaces of lines?

A

with open ( “staff.txt” , “r” ) as f:
for line in f:
staff_details = f.strip()
print(staff_details)

31
Q

How to skip a record? ( Skip printing Jack )

A

with open ( “staff.txt” , “r” ) as f:
for line in f:
line = line.rstrip()
if line.startswith(“Jack”):
continue
print(line)

32
Q

How to select Jack records using in?

A

with open ( “staff.txt” , “r” ) as f:
for line in f:
line = line.rstrip()
if “Jack” in line:
print(line)

33
Q

What error will be getting here?
zot = “abc”
print(zot[5])

A

Index Error

34
Q

How to know the lenfth of a banana?

A

fruits = “banana”
print(len(fruits)) # 6

35
Q

How to show
b
a
n
a
n
a

A

fruits = “banana”
k = 0
while k < len(fruits):
print(fruits[k])
k += 1

36
Q

How to find how many a’s is in the banana word?

A

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
Q

How to let python returns True is there is na in banana?

A

fruits = “banana”
print(“na” in fruits) # True
print(“ta” in fruits) # False

38
Q

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

A

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
Q

List out indexing method

A
  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
Q

List out the built in String Library Functions ( 3 )

A
  1. count
  2. endswith
  3. lower ( .lower() )
41
Q

How to search the character “na” from banana and change it to “z”?

A

fruit = “banana”
search = fruit.find(“na”)
print(search) # Returns the index
change = fruit.replace(“na”,”z”)
print(change) # bazz

42
Q

How to output the string from “ banana “ to below?
1. banana
2. banana
3. banana

A

fruit = “banana”
1. fruit.lstrip()
2. fruit.rstrip()
3. fruit.strip()

43
Q

How to split strings?

A

line = “John, john@mail.com”
name,email = line.strip.split(“,”)
print(f”Name : {name}”
print(f”Email : {email}”

44
Q

How to create a new list using range to generate from 0 to 10 and 2 to 6?

A
  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
Q

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

A

new_list = [1 , 2 , 3]
1. new_list.append(3) # [1 , 2 , 3 , 3]
2. new_list[1] = 3 # [1 , 3 , 3]

46
Q

How to scan through the list ? [ 3 , 4, 5, 6 ]

A

new_list = [ 3, 4 , 5, 6 ]
for i in new_list:
print(i)

47
Q

How to search 4 in the list ? [ 3 , 4, 5, 6 ]

A

new_list = [ 3 , 4 , 5 , 6 ]
for i in new_list:
if ( i == 4 ):
print( i , “found in the list” )

48
Q

List out the list functions for sum, len, pop , insert and remove

A
  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
Q

How to add items into dictionary?

A

newStudent = {}
newStudent[‘TP’] = “TP123456”
newStudent[‘Name’] = “John”

Output :
newStudent = {
‘TP’ : “TP123456”
‘Name’ : “John”
}

  • Access Dictionary Items
    print(newStudent.get(“Name”))
50
Q

How to write inside json file?

A

userDetails[f”user_{un}”] = {‘username’ : un , ‘password’ : pw , ‘email’ ; em }

with open( “users.json” , “w” ) as f:
json.dump(userDetails, f , indent = 2 )

51
Q

How to read from json file?

A

with open( “users.json” , “r” ) as f:
allUsers = json.load(f)

  for id, userData in allUsers.items():
          print("\n")
          print(f"Username = {userData['username']}"