1: lo: <LOOPBACK,UP,LOWER_UP> mtu 65536 ...
inet 127.0.0.1/8 scope host lo
2: eth0: <BROADCAST,MULTICAST,UP,LOWER_UP> mtu 1500 ...
inet 192.168.1.100/24 brd 192.168.1.255 scope global dynamic eth0
---
#CyberSecurity #WebSecurity #Vulnerability
#11.
curlA tool to transfer data from or to a server, using various protocols. Essential for interacting with web APIs and inspecting HTTP headers.
curl -I http://example.com
HTTP/1.1 200 OK
Content-Encoding: gzip
Accept-Ranges: bytes
Cache-Control: max-age=604800
Content-Type: text/html; charset=UTF-8
Date: Fri, 27 Oct 2023 10:00:00 GMT
Server: ECS (dcb/7F83)
Content-Length: 648
#12.
gobusterA fast tool used to brute-force URIs (directories and files), DNS subdomains, and virtual host names.
gobuster dir -u http://example.com -w /usr/share/wordlists/dirb/common.txt
===============================================================
Gobuster v3.5
===============================================================
[+] Url: http://example.com
[+] Threads: 10
[+] Wordlist: /usr/share/wordlists/dirb/common.txt
===============================================================
/index.html (Status: 200) [Size: 1256]
/images (Status: 301) [Size: 178] -> http://example.com/images/
/javascript (Status: 301) [Size: 178] -> http://example.com/javascript/
#13.
niktoA web server scanner which performs comprehensive tests against web servers for multiple items, including over 6700 potentially dangerous files/CGIs.
nikto -h http://scanme.nmap.org
- Nikto v2.1.6
---------------------------------------------------------------------------
+ Target IP: 45.33.32.156
+ Target Hostname: scanme.nmap.org
+ Target Port: 80
+ Start Time: ...
---------------------------------------------------------------------------
+ Server: Apache/2.4.7 (Ubuntu)
+ The anti-clickjacking X-Frame-Options header is not present.
+ OSVDB-3233: /icons/README: Apache default file found.
#14.
sqlmapAn open-source penetration testing tool that automates the process of detecting and exploiting SQL injection flaws.
sqlmap -u "http://testphp.vulnweb.com/listproducts.php?cat=1" --dbs
...
available databases [2]:
[*] information_schema
[*] acuart
#15.
whatwebIdentifies different web technologies including content management systems (CMS), blogging platforms, statistic/analytics packages, JavaScript libraries, web servers, and embedded devices.
whatweb scanme.nmap.org
http://scanme.nmap.org [200 OK] Apache[2.4.7], Country[UNITED STATES], HTTPServer[Ubuntu Linux][Apache/2.4.7 ((Ubuntu))], IP[45.33.32.156], Script, Title[Go ahead and ScanMe!], Ubuntu
---
#CyberSecurity #PasswordCracking #Exploitation
#16.
John the Ripper (john)A fast password cracker, currently available for many flavors of Unix, Windows, DOS, and OpenVMS.
# Assume 'hashes.txt' contains 'user:$apr1$A.B.C...$...'
john --wordlist=/usr/share/wordlists/rockyou.txt hashes.txt
Using default input encoding: UTF-8
Loaded 1 password hash (md5crypt, 32/64 OpenSSL)
Press 'q' or Ctrl-C to abort, almost any other key for status
password123 (user)
1g 0:00:00:01 DONE (2023-10-27 10:15) 0.9803g/s 1234p/s 1234c/s
Session completed
#17.
hashcatAn advanced password recovery utility that can crack a wide variety of hash types using multiple attack modes (dictionary, brute-force, mask).
# -m 0 = MD5 hash type
hashcat -m 0 -a 0 hashes.md5 /usr/share/wordlists/rockyou.txt
...
Session..........: hashcat
Status...........: Cracked
Hash.Name........: MD5
Hash.Target......: 5f4dcc3b5aa765d61d8327deb882cf99
Guess.Base.......: File (/usr/share/wordlists/rockyou.txt)
...
Recovered........: 1/1 (100.00%) Digests
#18.
hydraA parallelized login cracker which supports numerous protocols to attack. It is very fast and flexible.
hydra -l user -P /path/to/passwords.txt ftp://192.168.1.101
Hydra v9.1 (c) 2020 by van Hauser/THC - Please do not use in military projects
...
[21][ftp] host: 192.168.1.101 login: user password: password
1 of 1 target successfully completed, 1 valid password found
#19.
Metasploit Framework (msfconsole)An exploitation framework for developing, testing, and executing exploit code against a remote target machine.
msfconsole
=[ metasploit v6.3.3-dev ]
+ -- --=[ 2289 exploits - 1184 auxiliary - 406 post ]
+ -- --=[ 953 payloads - 45 encoders - 11 nops ]
+ -- --=[ 9 evasion ]
msf6 >
#20.
searchsploitA command-line search tool for Exploit-DB that also allows you to take a copy of exploits to your working directory.
searchsploit apache 2.4.7
-------------------------------------------------- ---------------------------------
Exploit Title | Path
-------------------------------------------------- ---------------------------------
Apache 2.4.7 (Ubuntu) - 'mod_cgi' Bash Env | linux/remote/34900.py
Apache mod_authz_svn < 1.8.10 / < 1.7.18 - | multiple/remote/34101.txt
-------------------------------------------------- ---------------------------------
---
#CyberSecurity #Forensics #Utilities
#21.
stringsPrints the sequences of printable characters in files. Useful for finding plaintext credentials or other information in binary files.
strings /bin/bash
/lib64/ld-linux-x86-64.so.2
_ITM_deregisterTMCloneTable
__gmon_start__
...
echo
read
printf
#22.
grepSearches for patterns in each file. An indispensable tool for parsing log files and command output.
grep "Failed password" /var/log/auth.log
Oct 27 10:20:05 server sshd[1234]: Failed password for invalid user admin from 203.0.113.5 port 54321 ssh2
Oct 27 10:20:10 server sshd[1236]: Failed password for root from 203.0.113.5 port 12345 ssh2
#23.
chmodChanges the permissions of files and directories. Critical for hardening a system.
# Before
ls -l script.sh
-rwxrwxr-x 1 user user 50 Oct 27 10:25 script.sh
# Command
chmod 700 script.sh
# After
ls -l script.sh
-rwx------ 1 user user 50 Oct 27 10:25 script.sh
#24.
xxdCreates a hex dump of a given file or standard input. It can also convert a hex dump back to its original binary form.
echo -n "Hi" | xxd
00000000: 4869 Hi
#25.
base64Encodes and decodes data in Base64 format. Commonly used in web applications and email attachments.
echo -n "security" | base64
c2VjdXJpdHk=
---
#CyberSecurity #Crypto #Hashing
#26.
opensslA robust, commercial-grade, and full-featured toolkit for the Transport Layer Security (TLS) and Secure Sockets Layer (SSL) protocols. Also a general-purpose cryptography library.
# Generate a self-signed certificate
openssl req -x509 -newkey rsa:2048 -keyout key.pem -out cert.pem -days 365 -nodes
Generating a RSA private key
...........................................................................+++++
......................................................................+++++
writing new private key to 'key.pem'
-----
You are about to be asked to enter information that will be incorporated
into your certificate request.
...
(Files key.pem and cert.pem are created)
#27.
sha256sumComputes and checks a SHA256 message digest. Used to verify file integrity.
echo -n "hello world" > file.txt
sha256sum file.txt
b94d27b9934d3e08a52e52d7da7dabfac484efe37a5380ee9088f7ace2efcde9 file.txt
#28.
gpg(GNU Privacy Guard) A complete and free implementation of the OpenPGP standard, allowing you to encrypt and sign your data and communications.
# Encrypt a file
echo "secret message" > secret.txt
gpg -c secret.txt
(A file named secret.txt.gpg is created after prompting for a passphrase)
#29.
aircrack-ngA complete suite of tools to assess Wi-Fi network security. It focuses on monitoring, attacking, testing, and cracking.
# Put interface in monitor mode
airmon-ng start wlan0
PHY Interface Driver Chipset
phy0 wlan0 ath9k Atheros Communications Inc. AR9271 802.11n
(mac80211 monitor mode vif enabled for [phy0]wlan0 on [phy0]wlan0mon)
(mac80211 station mode vif disabled for [phy0]wlan0)
#30.
theHarvesterA tool for gathering open-source intelligence (OSINT) to help determine a company's external threat landscape.
theharvester -d google.com -l 100 -b google
[*] Target: google.com
[*] Searching Google for 100 results...
[*] Found 2 emails:
- some-email@google.com
- another-email@google.com
[*] Found 15 hosts:
- host1.google.com
- host2.google.com
...
━━━━━━━━━━━━━━━
By: @DataScience4 ✨
❤2
Please open Telegram to view this post
VIEW IN TELEGRAM
100 Python Examples: A Step-by-Step Guide
#Python #Programming #Tutorial #LearnPython
Part 1: The Basics (Examples 1-15)
#1. Print "Hello, World!"
The classic first program.
#2. Variables and Strings
Store text in a variable and print it.
#3. Integer Variable
Store a whole number.
#4. Float Variable
Store a number with a decimal point.
#5. Boolean Variable
Store a value that is either
#6. Get User Input
Use the
#7. Simple Calculation
Perform a basic arithmetic operation.
#8. Comments
Use
#9. Type Conversion (String to Integer)
Convert a user's input (which is a string) to an integer to perform math.
#10. String Concatenation
Combine multiple strings using the
#11. Multiple Assignment
Assign values to multiple variables in one line.
#12. The
Check the data type of a variable.
#13. Basic Arithmetic Operators
Demonstrates addition, subtraction, multiplication, and division.
#14. Floor Division and Modulus
#15. Exponentiation
Use
---
Part 2: String Manipulation (Examples 16-25)
#16. String Length
Use
#Python #Programming #Tutorial #LearnPython
Part 1: The Basics (Examples 1-15)
#1. Print "Hello, World!"
The classic first program.
print() is a function that outputs text to the console.print("Hello, World!")Hello, World!
#2. Variables and Strings
Store text in a variable and print it.
message = "I am learning Python."
print(message)
I am learning Python.
#3. Integer Variable
Store a whole number.
age = 30
print("My age is:", age)
My age is: 30
#4. Float Variable
Store a number with a decimal point.
price = 19.99
print("The price is:", price)
The price is: 19.99
#5. Boolean Variable
Store a value that is either
True or False.is_learning = True
print("Am I learning?", is_learning)
Am I learning? True
#6. Get User Input
Use the
input() function to get information from the user.name = input("What is your name? ")
print("Hello, " + name)What is your name? Alice
Hello, Alice
#7. Simple Calculation
Perform a basic arithmetic operation.
a = 10
b = 5
print(a + b)
15
#8. Comments
Use
# to add comments that Python will ignore.# This line calculates the area of a rectangle
length = 10
width = 5
area = length * width
print("Area is:", area)
Area is: 50
#9. Type Conversion (String to Integer)
Convert a user's input (which is a string) to an integer to perform math.
age_str = input("Enter your age: ")
age_int = int(age_str)
next_year_age = age_int + 1
print("Next year you will be:", next_year_age)Enter your age: 25
Next year you will be: 26
#10. String Concatenation
Combine multiple strings using the
+ operator.first_name = "John"
last_name = "Doe"
full_name = first_name + " " + last_name
print(full_name)
John Doe
#11. Multiple Assignment
Assign values to multiple variables in one line.
x, y, z = 10, 20, 30
print(x, y, z)
10 20 30
#12. The
type() FunctionCheck the data type of a variable.
num = 123
text = "hello"
pi = 3.14
print(type(num))
print(type(text))
print(type(pi))
<class 'int'>
<class 'str'>
<class 'float'>
#13. Basic Arithmetic Operators
Demonstrates addition, subtraction, multiplication, and division.
a = 15
b = 4
print("Addition:", a + b)
print("Subtraction:", a - b)
print("Multiplication:", a * b)
print("Division:", a / b)
Addition: 19
Subtraction: 11
Multiplication: 60
Division: 3.75
#14. Floor Division and Modulus
// for division that rounds down, and % for the remainder.a = 15
b = 4
print("Floor Division:", a // b)
print("Modulus (Remainder):", a % b)
Floor Division: 3
Modulus (Remainder): 3
#15. Exponentiation
Use
** to raise a number to a power.power = 3 ** 4 # 3 to the power of 4
print(power)
81
---
Part 2: String Manipulation (Examples 16-25)
#16. String Length
Use
len() to get the number of characters in a string.my_string = "Python is fun"
print(len(my_string))
13
❤1
#17. Uppercase and Lowercase
Use
#18. Find Substring
Use the
#19. Replace Substring
Use the
#20. String Slicing (Basic)
Extract a part of a string using
#21. String Slicing (From Start)
Omit the start index to slice from the beginning.
#22. String Slicing (To End)
Omit the end index to slice to the end.
#23. f-Strings (Formatted String Literals)
A modern way to embed expressions inside string literals.
#24. Check if String is in a String
Use the
#25. Split a String into a List
Use the
---
Part 3: Conditional Logic (Examples 26-30)
#26.
Execute code only if a condition is true.
#27.
Execute one block of code if true, and another if false.
#28.
Check multiple conditions.
#29. Comparison Operators
#30. Logical Operators (
Combine conditional statements.
---
Part 4: Loops (Examples 31-40)
#31.
Repeat a block of code a specific number of times.
#32.
Iterate through each character of a string.
Use
.upper() and .lower() methods.my_string = "Python"
print(my_string.upper())
print(my_string.lower())
PYTHON
python
#18. Find Substring
Use the
.find() method to get the starting index of a substring.sentence = "The quick brown fox"
print(sentence.find("quick"))
4
#19. Replace Substring
Use the
.replace() method.sentence = "I like cats."
new_sentence = sentence.replace("cats", "dogs")
print(new_sentence)
I like dogs.
#20. String Slicing (Basic)
Extract a part of a string using
[start:end].word = "Programming"
# Get characters from index 3 up to (but not including) index 7
print(word[3:7])
gram
#21. String Slicing (From Start)
Omit the start index to slice from the beginning.
word = "Programming"
print(word[:4])
Prog
#22. String Slicing (To End)
Omit the end index to slice to the end.
word = "Programming"
print(word[7:])
ming
#23. f-Strings (Formatted String Literals)
A modern way to embed expressions inside string literals.
name = "Bob"
age = 40
print(f"His name is {name} and he is {age} years old.")
His name is Bob and he is 40 years old.
#24. Check if String is in a String
Use the
in keyword.sentence = "Hello world, welcome to Python."
print("welcome" in sentence)
True
#25. Split a String into a List
Use the
.split() method to break a string into a list of smaller strings.csv_data = "John,Doe,45"
items = csv_data.split(',')
print(items)
['John', 'Doe', '45']
---
Part 3: Conditional Logic (Examples 26-30)
#26.
if StatementExecute code only if a condition is true.
temperature = 35
if temperature > 30:
print("It's a hot day!")
It's a hot day!
#27.
if-else StatementExecute one block of code if true, and another if false.
age = 17
if age >= 18:
print("You are an adult.")
else:
print("You are a minor.")
You are a minor.
#28.
if-elif-else StatementCheck multiple conditions.
score = 85
if score >= 90:
print("Grade: A")
elif score >= 80:
print("Grade: B")
else:
print("Grade: C")
Grade: B
#29. Comparison Operators
== (equal), != (not equal), > (greater than), < (less than).x = 10
y = 10
if x == y:
print("x is equal to y")
if x != 5:
print("x is not equal to 5")
x is equal to y
x is not equal to 5
#30. Logical Operators (
and, or)Combine conditional statements.
age = 25
has_license = True
if age >= 18 and has_license:
print("You can drive.")
You can drive.
---
Part 4: Loops (Examples 31-40)
#31.
for Loop with range()Repeat a block of code a specific number of times.
for i in range(5): # from 0 to 4
print(f"Number: {i}")
Number: 0
Number: 1
Number: 2
Number: 3
Number: 4
#32.
for Loop over a StringIterate through each character of a string.
for char in "Python":
print(char)
P
y
t
h
o
n
#33.
Iterate through each item in a list.
#34.
Repeat a block of code as long as a condition is true.
#35. The
Exit a loop prematurely.
#36. The
Skip the current iteration and move to the next.
#37. Sum Numbers in a Range
A practical example of a for loop.
#38. Nested Loops
A loop inside another loop.
#39. Guessing Game with
A simple interactive loop.
#40.
The
---
Part 5: Lists (Examples 41-55)
#41. Create a List
A list is an ordered collection of items.
#42. Access List Items by Index
Get an item by its position (index starts at 0).
#43. Negative Indexing
Access items from the end of the list.
#44. Change an Item's Value
Lists are mutable, meaning you can change their items.
#45. Add an Item with
Add an item to the end of the list.
#46. Insert an Item with
Insert an item at a specific position.
#47. Remove an Item with
Remove the first occurrence of a specific value.
for Loop over a ListIterate through each item in a list.
fruits = ["apple", "banana", "cherry"]
for fruit in fruits:
print(fruit)
apple
banana
cherry
#34.
while LoopRepeat a block of code as long as a condition is true.
count = 1
while count <= 5:
print(f"Count is: {count}")
count += 1
Count is: 1
Count is: 2
Count is: 3
Count is: 4
Count is: 5
#35. The
break StatementExit a loop prematurely.
for i in range(10):
if i == 5:
break
print(i)
0
1
2
3
4
#36. The
continue StatementSkip the current iteration and move to the next.
for i in range(5):
if i == 2:
continue
print(i)
0
1
3
4
#37. Sum Numbers in a Range
A practical example of a for loop.
total = 0
for number in range(1, 6): # 1, 2, 3, 4, 5
total += number
print(f"The sum is: {total}")
The sum is: 15
#38. Nested Loops
A loop inside another loop.
for i in range(3):
for j in range(2):
print(f"({i}, {j})")
(0, 0)
(0, 1)
(1, 0)
(1, 1)
(2, 0)
(2, 1)
#39. Guessing Game with
whileA simple interactive loop.
# In a real script, this would work. Output is simulated.
secret_number = 7
guess = 0
while guess != secret_number:
guess = int(input("Guess the number: "))
print("You guessed it!")
Guess the number: 3
Guess the number: 8
Guess the number: 7
You guessed it!
#40.
else Clause in for LoopThe
else block executes when the loop finishes normally (not with break).for i in range(5):
print(i)
else:
print("Loop finished without break.")
0
1
2
3
4
Loop finished without break.
---
Part 5: Lists (Examples 41-55)
#41. Create a List
A list is an ordered collection of items.
numbers = [1, 2, 3, 4, 5]
fruits = ["apple", "banana", "cherry"]
print(numbers)
print(fruits)
[1, 2, 3, 4, 5]
['apple', 'banana', 'cherry']
#42. Access List Items by Index
Get an item by its position (index starts at 0).
fruits = ["apple", "banana", "cherry"]
print(fruits[1]) # Get the second item
banana
#43. Negative Indexing
Access items from the end of the list.
fruits = ["apple", "banana", "cherry"]
print(fruits[-1]) # Get the last item
cherry
#44. Change an Item's Value
Lists are mutable, meaning you can change their items.
fruits = ["apple", "banana", "cherry"]
fruits[0] = "orange"
print(fruits)
['orange', 'banana', 'cherry']
#45. Add an Item with
.append()Add an item to the end of the list.
fruits = ["apple", "banana"]
fruits.append("cherry")
print(fruits)
['apple', 'banana', 'cherry']
#46. Insert an Item with
.insert()Insert an item at a specific position.
fruits = ["apple", "cherry"]
fruits.insert(1, "banana")
print(fruits)
['apple', 'banana', 'cherry']
#47. Remove an Item with
.remove()Remove the first occurrence of a specific value.
fruits = ["apple", "banana", "cherry"]
fruits.remove("banana")
print(fruits)
['apple', 'cherry']
#48. Remove an Item with
.pop()Remove an item at a specific index (or the last item if no index is given).
fruits = ["apple", "banana", "cherry"]
fruits.pop(1)
print(fruits)
['apple', 'cherry']
#49. Get List Length
Use
len() to get the number of items.numbers = [10, 20, 30, 40]
print(len(numbers))
4
#50. Slicing a List
Get a range of items from a list.
numbers = [0, 1, 2, 3, 4, 5, 6]
print(numbers[2:5]) # Items from index 2 to 4
[2, 3, 4]
#51. Check if an Item Exists
Use the
in keyword.fruits = ["apple", "banana", "cherry"]
if "banana" in fruits:
print("Yes, banana is in the list.")
Yes, banana is in the list.
#52. Sort a List with
.sort()Sorts the list in place (modifies the original list).
numbers = [3, 1, 4, 1, 5, 9]
numbers.sort()
print(numbers)
[1, 1, 3, 4, 5, 9]
#53. Copy a List
Use the
.copy() method to avoid modifying the original.original = [1, 2, 3]
copied = original.copy()
copied.append(4)
print(f"Original: {original}")
print(f"Copied: {copied}")
Original: [1, 2, 3]
Copied: [1, 2, 3, 4]
#54. Join Two Lists
Combine two lists using the
+ operator.list1 = ["a", "b"]
list2 = [1, 2]
list3 = list1 + list2
print(list3)
['a', 'b', 1, 2]
#55. List of Lists (2D List)
A list that contains other lists.
matrix = [
[1, 2, 3],
[4, 5, 6],
[7, 8, 9]
]
print(matrix[1][1]) # Get the item at row 1, column 1
5
---
Part 6: Dictionaries, Tuples, Sets (Examples 56-70)
#56. Create a Dictionary
An unordered collection of key-value pairs.
person = {
"name": "Alice",
"age": 25,
"city": "New York"
}
print(person){'name': 'Alice', 'age': 25, 'city': 'New York'}#57. Access Dictionary Values
Use the key in square brackets.
person = {"name": "Alice", "age": 25}
print(person["name"])Alice
#58. Add or Change a Dictionary Item
Assign a value to a key.
person = {"name": "Alice", "age": 25}
person["age"] = 26 # Change value
person["country"] = "USA" # Add new item
print(person){'name': 'Alice', 'age': 26, 'country': 'USA'}#59. Get Dictionary Keys
Use the
.keys() method.person = {"name": "Alice", "age": 25}
print(person.keys())dict_keys(['name', 'age'])
#60. Get Dictionary Values
Use the
.values() method.person = {"name": "Alice", "age": 25}
print(person.values())dict_values(['Alice', 25])
#61. Loop Through a Dictionary
Iterate over the keys.
person = {"name": "Alice", "age": 25}
for key in person:
print(f"{key}: {person[key]}")name: Alice
age: 25
#62. Loop Through Dictionary Items
Use
.items() to get both keys and values.❤1
person = {"name": "Alice", "age": 25}
for key, value in person.items():
print(f"{key} -> {value}")name -> Alice
age -> 25
#63. Check if a Key Exists
Use the
in keyword.person = {"name": "Alice", "age": 25}
if "age" in person:
print("Age key exists.")Age key exists.
#64. Create a Tuple
A tuple is an ordered collection that is unchangeable (immutable).
coordinates = (10, 20)
print(coordinates)
(10, 20)
#65. Access Tuple Items
Same as lists, using index.
coordinates = (10, 20, 30)
print(coordinates[0])
10
#66. Tuple Immutability
You cannot change a tuple's items after it is created.
# This code will produce an error
coordinates = (10, 20)
# coordinates[0] = 5 # This would raise a TypeError
print("Tuples cannot be changed.")
Tuples cannot be changed.
#67. Create a Set
A set is an unordered collection with no duplicate items.
numbers = {1, 2, 3, 2, 4} # The duplicate '2' is ignored
print(numbers){1, 2, 3, 4}#68. Add Item to a Set
Use the
.add() method.fruits = {"apple", "banana"}
fruits.add("cherry")
print(fruits){'banana', 'apple', 'cherry'}
(Note: Order is not guaranteed)#69. Set Union
Combine two sets using
| or .union().set1 = {1, 2, 3}
set2 = {3, 4, 5}
print(set1 | set2){1, 2, 3, 4, 5}#70. Set Intersection
Get items that are in both sets using
& or .intersection().set1 = {1, 2, 3}
set2 = {3, 4, 5}
print(set1 & set2){3}---
Part 7: Functions (Examples 71-80)
#71. Define a Simple Function
Use the
def keyword to create a function.def greet():
print("Hello from a function!")
greet() # Call the function
Hello from a function!
#72. Function with a Parameter
Pass information into a function.
def greet(name):
print(f"Hello, {name}!")
greet("Alice")
greet("Bob")
Hello, Alice!
Hello, Bob!
#73. Function with Multiple Parameters
def add_numbers(x, y):
print(x + y)
add_numbers(5, 3)
8
#74. Function with a
return ValueReturn a value from a function to be used elsewhere.
def multiply(x, y):
return x * y
result = multiply(4, 5)
print(result)
20
#75. Function with a Default Parameter Value
def greet(name="World"):
print(f"Hello, {name}!")
greet()
greet("Python")
Hello, World!
Hello, Python!
#76. Keyword Arguments
Call a function by specifying the parameter names.
def show_info(name, age):
print(f"Name: {name}, Age: {age}")
show_info(age=30, name="Charlie")
Name: Charlie, Age: 30
#77. A Function that Returns a Boolean
def is_even(number):
return number % 2 == 0
print(is_even(10))
print(is_even(7))
True
False
#78. Arbitrary Arguments (
*args)Allow a function to accept a variable number of arguments.
def sum_all(*numbers):
total = 0
for num in numbers:
total += num
return total
print(sum_all(1, 2, 3, 4))
10
#79. Lambda Function (Anonymous Function)
A small, one-line function.
# A lambda function that adds 10 to the number passed in
x = lambda a : a + 10
print(x(5))
15
#80. Scope (Local vs. Global Variables)
A variable created inside a function is only available inside that function.
def my_function():
local_var = "I am local"
print(local_var)
my_function()
# print(local_var) # This would cause a NameError
I am local
---
Part 8: Modules & File I/O (Examples 81-90)
#81. Import a Module
Use code from another file or library.
import math
print(math.sqrt(16))
4.0
#82. Import a Specific Function
Use
from ... import ... to import only what you need.from datetime import date
today = date.today()
print(today)
(Current date will be printed, e.g., 2023-10-27)
#83. The
random ModuleGenerate random numbers.
import random
# Random integer between 1 and 10 (inclusive)
print(random.randint(1, 10))
(A random number between 1 and 10, e.g., 7)
#84. Write to a Text File (
w)Create a new file and write content to it. Overwrites existing files.
# This creates a file named "greeting.txt"
with open("greeting.txt", "w") as file:
file.write("Hello, File!")
print("File written successfully.")
File written successfully.
#85. Read from a Text File (
r)Open a file and read its contents.
# Assumes "greeting.txt" from the previous example exists
with open("greeting.txt", "r") as file:
content = file.read()
print(content)
Hello, File!
#86. Append to a Text File (
a)Add content to the end of an existing file.
with open("greeting.txt", "a") as file:
file.write("\nHave a nice day.")
print("File appended successfully.")File appended successfully.
#87. Reading a File Line by Line
# Assumes "greeting.txt" now has two lines
with open("greeting.txt", "r") as file:
for line in file:
print(line.strip()) # .strip() removes newline characters
Hello, File!
Have a nice day.
#88. Create a Class (OOP Basics)
A blueprint for creating objects.
class Dog:
def bark(self):
print("Woof!")
my_dog = Dog() # Create an object (instance) of the Dog class
my_dog.bark()
Woof!
#89. The
__init__() Method (Constructor)A special method that runs when an object is created.
class Dog:
def __init__(self, name):
self.name = name
def speak(self):
print(f"{self.name} says Woof!")
dog1 = Dog("Rex")
dog1.speak()
Rex says Woof!
#90. Class Inheritance
Create a new class that inherits properties from an existing class.
class Animal:
def speak(self):
print("Animal speaks")
class Cat(Animal): # Cat inherits from Animal
def speak(self): # Override the method
print("Meow")
my_cat = Cat()
my_cat.speak()
Meow
---
Part 9: Error Handling & Advanced Topics (Examples 91-100)
#91.
try...except BlockHandle errors gracefully without crashing the program.
try:
result = 10 / 0
except ZeroDivisionError:
print("Error: Cannot divide by zero.")
Error: Cannot divide by zero.
#92. Handling
ValueErrortry:
number = int("abc")
except ValueError:
print("Invalid number format.")
Invalid number format.
❤1
#93. The
The
#94. List Comprehension
A concise way to create lists.
#95. List Comprehension with a Condition
#96. Dictionary Comprehension
A concise way to create dictionaries.
#97. The
Get both the index and the value when looping.
#98. The
Combine two lists element-wise.
#99.
#100. A Simple Command-Line App
━━━━━━━━━━━━━━━
By: @DataScience4 ✨
finally ClauseThe
finally block executes regardless of whether an error occurred.try:
print("Hello")
except:
print("Something went wrong")
finally:
print("The 'try except' is finished")
Hello
The 'try except' is finished
#94. List Comprehension
A concise way to create lists.
# Create a list of squares for numbers 0 through 9
squares = [x**2 for x in range(10)]
print(squares)
[0, 1, 4, 9, 16, 25, 36, 49, 64, 81]
#95. List Comprehension with a Condition
# Create a list of even numbers from 0 to 19
evens = [x for x in range(20) if x % 2 == 0]
print(evens)
[0, 2, 4, 6, 8, 10, 12, 14, 16, 18]
#96. Dictionary Comprehension
A concise way to create dictionaries.
# Create a dictionary of numbers and their squares
squares_dict = {x: x**2 for x in range(5)}
print(squares_dict)
{0: 0, 1: 1, 2: 4, 3: 9, 4: 16}#97. The
enumerate() FunctionGet both the index and the value when looping.
fruits = ["apple", "banana", "cherry"]
for index, fruit in enumerate(fruits):
print(index, fruit)
0 apple
1 banana
2 cherry
#98. The
zip() FunctionCombine two lists element-wise.
names = ["Alice", "Bob", "Charlie"]
ages = [25, 30, 35]
for name, age in zip(names, ages):
print(f"{name} is {age} years old.")
Alice is 25 years old.
Bob is 30 years old.
Charlie is 35 years old.
#99.
*args and **kwargs in a Function Definition*args for non-keyword arguments, **kwargs for keyword arguments.def my_func(*args, **kwargs):
print("Args:", args)
print("Kwargs:", kwargs)
my_func(1, 2, 3, name="Alice", city="New York")
Args: (1, 2, 3)
Kwargs: {'name': 'Alice', 'city': 'New York'}
#100. A Simple Command-Line App
import sys
# To run: python your_script_name.py YourName
# The output is simulated.
# name = sys.argv[1] # Gets the first argument after the script name
name = "World" # Simulating for demonstration
print(f"Hello, {name}!")
Hello, World!
━━━━━━━━━━━━━━━
By: @DataScience4 ✨
❤2
Top 100 Python Interview Questions & Answers
#Python #InterviewQuestions #CodingInterview #Programming #PythonDeveloper
👇 👇 👇 👇
#Python #InterviewQuestions #CodingInterview #Programming #PythonDeveloper
Please open Telegram to view this post
VIEW IN TELEGRAM
❤1
Top 100 Python Interview Questions & Answers
#Python #InterviewQuestions #CodingInterview #Programming #PythonDeveloper
Part 1: Core Python Fundamentals (Q1-20)
#1. Is Python a compiled or an interpreted language?
A: Python is an interpreted language. The Python interpreter reads and executes the source code line by line, without requiring a separate compilation step. This makes development faster but can result in slower execution compared to compiled languages like C++.
#2. What is the GIL (Global Interpreter Lock)?
A: The GIL is a mutex (a lock) that allows only one thread to execute Python bytecode at a time within a single process. This means even on a multi-core processor, a single Python process cannot run threads in parallel. It simplifies memory management but is a performance bottleneck for CPU-bound multithreaded programs.
#3. What is the difference between Python 2 and Python 3?
A: Key differences include:
•
• Integer Division: In Python 2,
• Unicode: In Python 3, strings are Unicode (UTF-8) by default. In Python 2, you had to explicitly use
#4. What are mutable and immutable data types in Python?
A:
• Mutable: Objects whose state or contents can be changed after creation. Examples:
• Immutable: Objects whose state cannot be changed after creation. Examples:
#5. How is memory managed in Python?
A: Python uses a private heap to manage memory. A built-in garbage collector automatically reclaims memory from objects that are no longer in use. The primary mechanism is reference counting, where each object tracks the number of references to it. When the count drops to zero, the object is deallocated.
#6. What is the difference between
A:
•
•
#7. What is PEP 8?
A: PEP 8 (Python Enhancement Proposal 8) is the official style guide for Python code. It provides conventions for writing readable and consistent Python code, covering aspects like naming conventions, code layout, and comments.
#8. What is the difference between a
A:
•
•
#9. What are namespaces in Python?
A: A namespace is a system that ensures all names in a program are unique and can be used without conflict. It's a mapping from names to objects. Python has different namespaces: built-in, global, and local.
#Python #InterviewQuestions #CodingInterview #Programming #PythonDeveloper
Part 1: Core Python Fundamentals (Q1-20)
#1. Is Python a compiled or an interpreted language?
A: Python is an interpreted language. The Python interpreter reads and executes the source code line by line, without requiring a separate compilation step. This makes development faster but can result in slower execution compared to compiled languages like C++.
#2. What is the GIL (Global Interpreter Lock)?
A: The GIL is a mutex (a lock) that allows only one thread to execute Python bytecode at a time within a single process. This means even on a multi-core processor, a single Python process cannot run threads in parallel. It simplifies memory management but is a performance bottleneck for CPU-bound multithreaded programs.
#3. What is the difference between Python 2 and Python 3?
A: Key differences include:
•
print: In Python 2, print is a statement (print "hello"). In Python 3, it's a function (print("hello")).• Integer Division: In Python 2,
5 / 2 results in 2 (floor division). In Python 3, it results in 2.5 (true division).• Unicode: In Python 3, strings are Unicode (UTF-8) by default. In Python 2, you had to explicitly use
u"unicode string".#4. What are mutable and immutable data types in Python?
A:
• Mutable: Objects whose state or contents can be changed after creation. Examples:
list, dict, set.• Immutable: Objects whose state cannot be changed after creation. Examples:
int, float, str, tuple, frozenset.# Mutable example
my_list = [1, 2, 3]
my_list[0] = 99
print(my_list)
[99, 2, 3]
#5. How is memory managed in Python?
A: Python uses a private heap to manage memory. A built-in garbage collector automatically reclaims memory from objects that are no longer in use. The primary mechanism is reference counting, where each object tracks the number of references to it. When the count drops to zero, the object is deallocated.
#6. What is the difference between
is and ==?A:
•
== (Equality): Checks if the values of two operands are equal.•
is (Identity): Checks if two variables point to the exact same object in memory.list_a = [1, 2, 3]
list_b = [1, 2, 3]
list_c = list_a
print(list_a == list_b) # True, values are the same
print(list_a is list_b) # False, different objects in memory
print(list_a is list_c) # True, same object in memory
True
False
True
#7. What is PEP 8?
A: PEP 8 (Python Enhancement Proposal 8) is the official style guide for Python code. It provides conventions for writing readable and consistent Python code, covering aspects like naming conventions, code layout, and comments.
#8. What is the difference between a
.py and a .pyc file?A:
•
.py: This is the source code file you write.•
.pyc: This is the compiled bytecode. When you run a Python script, the interpreter compiles it into bytecode (a lower-level, platform-independent representation) and saves it as a .pyc file to speed up subsequent executions.#9. What are namespaces in Python?
A: A namespace is a system that ensures all names in a program are unique and can be used without conflict. It's a mapping from names to objects. Python has different namespaces: built-in, global, and local.
#10. Explain scope in Python.
A: Scope refers to the region of a program where a namespace is directly accessible. The scopes are searched in this order:
• Local: Inside the current function.
• Enclosing: In the enclosing functions (for nested functions).
• Global: At the top level of the module.
• Built-in: Names pre-assigned in Python (e.g.,
---
#11. What is the ternary operator in Python?
A: It's a concise way to write a simple if-else statement in a single line. The syntax is
#12. What are negative indexes?
A: Negative indexes are used to access elements from the end of a sequence (like a list or string).
#13. What is pickling and unpickling?
A: Pickling is the process of converting a Python object hierarchy into a byte stream (serialization). Unpickling is the inverse operation, converting a byte stream back into an object hierarchy (deserialization). The
#14. How do you copy an object in Python?
A:
• Shallow Copy: Creates a new object but inserts references to the objects found in the original.
• Deep Copy: Creates a new object and recursively copies all objects found in the original. Changes to the copied object will not affect the original. Use the
#15. What does the
A:
---
#16. What does
A: This is a common idiom in Python. The code inside this block will only run when the script is executed directly (not when it is imported as a module into another script). It's the entry point of the program.
#17. How do you concatenate strings in Python?
A:
• Use the
• Use an f-string (formatted string literal) for embedding expressions (most readable).
• Use the
A: Scope refers to the region of a program where a namespace is directly accessible. The scopes are searched in this order:
• Local: Inside the current function.
• Enclosing: In the enclosing functions (for nested functions).
• Global: At the top level of the module.
• Built-in: Names pre-assigned in Python (e.g.,
print, len). This is known as the LEGB rule.---
#11. What is the ternary operator in Python?
A: It's a concise way to write a simple if-else statement in a single line. The syntax is
[value_if_true] if [condition] else [value_if_false].age = 20
status = "Adult" if age >= 18 else "Minor"
print(status)
Adult
#12. What are negative indexes?
A: Negative indexes are used to access elements from the end of a sequence (like a list or string).
-1 refers to the last element, -2 to the second-to-last, and so on.my_list = ['a', 'b', 'c', 'd']
print(my_list[-1])
print(my_list[-2])
d
c
#13. What is pickling and unpickling?
A: Pickling is the process of converting a Python object hierarchy into a byte stream (serialization). Unpickling is the inverse operation, converting a byte stream back into an object hierarchy (deserialization). The
pickle module is used for this.import pickle
my_dict = {'name': 'Alice'}
# Pickling
with open('data.pkl', 'wb') as f:
pickle.dump(my_dict, f)
# Unpickling
with open('data.pkl', 'rb') as f:
loaded_dict = pickle.load(f)
print(loaded_dict)
{'name': 'Alice'}#14. How do you copy an object in Python?
A:
• Shallow Copy: Creates a new object but inserts references to the objects found in the original.
• Deep Copy: Creates a new object and recursively copies all objects found in the original. Changes to the copied object will not affect the original. Use the
copy module.import copy
original_list = [[1, 2], [3, 4]]
shallow = copy.copy(original_list)
deep = copy.deepcopy(original_list)
# Modify a nested object
shallow[0][0] = 99
print(f"Original: {original_list}") # Modified!
print(f"Shallow Copy: {shallow}")
print(f"Deep Copy: {deep}") # Not modified
Original: [[99, 2], [3, 4]]
Shallow Copy: [[99, 2], [3, 4]]
Deep Copy: [[1, 2], [3, 4]]
#15. What does the
pass statement do?A:
pass is a null statement. It's used as a placeholder where a statement is syntactically required but you don't want any code to execute. It's often used in empty functions or classes.def my_empty_function():
pass # No error, does nothing
my_empty_function()
print("Function executed.")
Function executed.
---
#16. What does
if __name__ == "__main__:" mean?A: This is a common idiom in Python. The code inside this block will only run when the script is executed directly (not when it is imported as a module into another script). It's the entry point of the program.
#17. How do you concatenate strings in Python?
A:
• Use the
+ operator for simple cases.• Use an f-string (formatted string literal) for embedding expressions (most readable).
• Use the
.join() method for concatenating a list of strings (most efficient).words = ["Python", "is", "awesome"]
sentence = " ".join(words)
print(sentence)
Python is awesome
❤1
#18. What is type casting?
A: Type casting (or type conversion) is the process of converting a variable from one data type to another. Functions like
#19. What are Python literals?
A: A literal is a notation for representing a fixed value in source code. Examples include:
• String literals:
• Numeric literals:
• Boolean literals:
• Special literal:
#20. How do you create a multi-line string?
A: Use triple quotes, either
---
Part 2: Data Structures (Q21-40)
#21. What is the main difference between a List and a Tuple?
A: The primary difference is that Lists are mutable, meaning their elements can be changed, added, or removed. Tuples are immutable, meaning once they are created, their elements cannot be changed. Tuples are generally faster than lists.
#22. What are list comprehensions? Provide an example.
A: A list comprehension is a concise and readable way to create a list. It consists of brackets containing an expression followed by a
#23. How do you remove duplicates from a list?
A: The simplest way is to convert the list to a set and then back to a list. Sets automatically discard duplicate elements. This method does not preserve the original order.
#24. What is the difference between
A:
•
•
#25. Explain slicing in Python.
A: Slicing is a feature that allows you to access a range of elements from a sequence (like a list, string, or tuple). The syntax is
•
•
•
---
#26. Can a dictionary key be a list? Why or why not?
A: No. Dictionary keys must be of an immutable type. Since lists are mutable, they cannot be used as dictionary keys. You can use immutable types like strings, numbers, or tuples as keys.
A: Type casting (or type conversion) is the process of converting a variable from one data type to another. Functions like
int(), float(), str(), and list() are used for this.string_num = "123"
integer_num = int(string_num)
print(integer_num + 7)
130
#19. What are Python literals?
A: A literal is a notation for representing a fixed value in source code. Examples include:
• String literals:
"hello", 'world'• Numeric literals:
100, 3.14• Boolean literals:
True, False• Special literal:
None#20. How do you create a multi-line string?
A: Use triple quotes, either
""" or '''.multi_line = """This is a string
that spans across
multiple lines."""
print(multi_line)
This is a string
that spans across
multiple lines.
---
Part 2: Data Structures (Q21-40)
#21. What is the main difference between a List and a Tuple?
A: The primary difference is that Lists are mutable, meaning their elements can be changed, added, or removed. Tuples are immutable, meaning once they are created, their elements cannot be changed. Tuples are generally faster than lists.
#22. What are list comprehensions? Provide an example.
A: A list comprehension is a concise and readable way to create a list. It consists of brackets containing an expression followed by a
for clause, then zero or more for or if clauses.# Create a list of squares for numbers 0 through 9
squares = [x**2 for x in range(10)]
print(squares)
[0, 1, 4, 9, 16, 25, 36, 49, 64, 81]
#23. How do you remove duplicates from a list?
A: The simplest way is to convert the list to a set and then back to a list. Sets automatically discard duplicate elements. This method does not preserve the original order.
my_list = [1, 2, 3, 2, 4, 1, 5]
unique_list = list(set(my_list))
print(unique_list)
[1, 2, 3, 4, 5]
#24. What is the difference between
.sort() and sorted()?A:
•
.sort() is a list method that sorts the list in-place (modifies the original list) and returns None.•
sorted() is a built-in function that takes an iterable as an argument and returns a new sorted list, leaving the original iterable unchanged.my_list = [3, 1, 2]
sorted_list = sorted(my_list)
print(f"Original list after sorted(): {my_list}")
print(f"New list from sorted(): {sorted_list}")
my_list.sort()
print(f"Original list after .sort(): {my_list}")
Original list after sorted(): [3, 1, 2]
New list from sorted(): [1, 2, 3]
Original list after .sort(): [1, 2, 3]
#25. Explain slicing in Python.
A: Slicing is a feature that allows you to access a range of elements from a sequence (like a list, string, or tuple). The syntax is
sequence[start:stop:step].•
start: The index of the first element to include.•
stop: The index of the first element to exclude.•
step: The amount to increment by.my_list = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
# Elements from index 2 up to (not including) 5
print(my_list[2:5])
# Every second element
print(my_list[::2])
# Reverse the list
print(my_list[::-1])
[2, 3, 4]
[0, 2, 4, 6, 8]
[9, 8, 7, 6, 5, 4, 3, 2, 1, 0]
---
#26. Can a dictionary key be a list? Why or why not?
A: No. Dictionary keys must be of an immutable type. Since lists are mutable, they cannot be used as dictionary keys. You can use immutable types like strings, numbers, or tuples as keys.
#27. How do you merge two dictionaries?
A: In Python 3.9+, you can use the
#28. How do you iterate over the keys, values, and items of a dictionary?
A: Use the
#29. What is a set? What are its main properties?
A: A set is an unordered collection of unique elements.
• Unique: Sets cannot have duplicate members.
• Unordered: The elements are not stored in any specific order.
• Mutable: You can add or remove elements from a set.
#30. What is a
A: A
---
#31. How do you find the intersection of two sets?
A: Use the
#32. What is the difference between
A:
•
•
#33. How do you reverse a list?
A:
• Use the
• Use slicing
#34. What is
A:
#35. What is the time complexity of a key lookup in a list vs. a dictionary?
A:
• List: O(n), because in the worst case, you may have to scan the entire list to find an element.
• Dictionary/Set: O(1) on average. Dictionaries use a hash table, which allows for direct lookup of a key's location without scanning.
#36. How do you create an empty set?
A: You must use the
A: In Python 3.9+, you can use the
| (union) operator. For earlier versions, you can use the ** unpacking operator or the .update() method.dict1 = {'a': 1, 'b': 2}
dict2 = {'b': 3, 'c': 4}
# Using the | operator (Python 3.9+)
merged_dict = dict1 | dict2
print(merged_dict){'a': 1, 'b': 3, 'c': 4}#28. How do you iterate over the keys, values, and items of a dictionary?
A: Use the
.keys(), .values(), and .items() methods.my_dict = {'name': 'Alice', 'age': 25}
for key, value in my_dict.items():
print(f"{key}: {value}")name: Alice
age: 25
#29. What is a set? What are its main properties?
A: A set is an unordered collection of unique elements.
• Unique: Sets cannot have duplicate members.
• Unordered: The elements are not stored in any specific order.
• Mutable: You can add or remove elements from a set.
#30. What is a
frozenset?A: A
frozenset is an immutable version of a set. Once created, you cannot add or remove elements. Because they are immutable and hashable, they can be used as dictionary keys or as elements of another set.---
#31. How do you find the intersection of two sets?
A: Use the
& operator or the .intersection() method.set1 = {1, 2, 3, 4}
set2 = {3, 4, 5, 6}
print(set1 & set2){3, 4}#32. What is the difference between
.append() and .extend() for lists?A:
•
.append(element): Adds its argument as a single element to the end of a list.•
.extend(iterable): Iterates over its argument and adds each element to the list, extending the list.list_a = [1, 2, 3]
list_b = [1, 2, 3]
list_a.append([4, 5])
list_b.extend([4, 5])
print(f"After append: {list_a}")
print(f"After extend: {list_b}")
After append: [1, 2, 3, [4, 5]]
After extend: [1, 2, 3, 4, 5]
#33. How do you reverse a list?
A:
• Use the
.reverse() method to reverse the list in-place.• Use slicing
[::-1] to create a new, reversed copy of the list.my_list = [1, 2, 3, 4]
reversed_copy = my_list[::-1]
print(reversed_copy)
[4, 3, 2, 1]
#34. What is
defaultdict?A:
defaultdict is a subclass of the standard dict that is found in the collections module. It overrides one method and adds one writable instance variable. Its main advantage is that it does not raise a KeyError if you try to access a key that does not exist. Instead, it provides a default value for that key.from collections import defaultdict
d = defaultdict(int) # Default value for non-existent keys will be int(), which is 0
d['a'] += 1
print(d['a'])
print(d['b']) # Accessing a non-existent key
1
0
#35. What is the time complexity of a key lookup in a list vs. a dictionary?
A:
• List: O(n), because in the worst case, you may have to scan the entire list to find an element.
• Dictionary/Set: O(1) on average. Dictionaries use a hash table, which allows for direct lookup of a key's location without scanning.
#36. How do you create an empty set?
A: You must use the
set() constructor. Using {} creates an empty dictionary, not an empty set.empty_dict = {}
empty_set = set()
print(type(empty_dict))
print(type(empty_set))<class 'dict'>
<class 'set'>
❤1
#37. How can you get a value from a dictionary without raising a
A: Use the
#38. What is a hashable object?
A: An object is hashable if it has a hash value that never changes during its lifetime. This means it must be immutable. Hashable objects can be used as dictionary keys and set members. Examples:
#39. What is dictionary comprehension?
A: It is a concise and readable way to create a dictionary.
#40. Explain how to use
A: The
---
Part 3: Functions & Functional Programming (Q41-55)
#41. What are
A: They are used to pass a variable number of arguments to a function.
•
•
#42. What is a lambda function?
A: A lambda function is a small, anonymous function defined with the
#43. What is a decorator?
A: A decorator is a design pattern in Python that allows a user to add new functionality to an existing object (like a function) without modifying its structure. Decorators are usually called before the definition of a function you want to decorate.
#44. What is a generator? What is the
A: A generator is a special type of iterator that is simpler to create. Instead of returning a value and terminating, a generator function uses the
KeyError?A: Use the
.get(key, default_value) method. It returns the value for the key if it exists, otherwise it returns the default_value (which is None if not specified).my_dict = {'a': 1}
print(my_dict.get('a'))
print(my_dict.get('b', 'Not Found'))1
Not Found
#38. What is a hashable object?
A: An object is hashable if it has a hash value that never changes during its lifetime. This means it must be immutable. Hashable objects can be used as dictionary keys and set members. Examples:
int, str, tuple.#39. What is dictionary comprehension?
A: It is a concise and readable way to create a dictionary.
# Create a dictionary of numbers and their squares
squares_dict = {x: x**2 for x in range(5)}
print(squares_dict)
{0: 0, 1: 1, 2: 4, 3: 9, 4: 16}#40. Explain how to use
zip() to combine two lists.A: The
zip() function takes two or more iterables and returns an iterator of tuples, where the i-th tuple contains the i-th element from each of the argument iterables. It stops when the shortest input iterable is exhausted.names = ["Alice", "Bob", "Charlie"]
ages = [25, 30, 35]
combined = list(zip(names, ages))
print(combined)
[('Alice', 25), ('Bob', 30), ('Charlie', 35)]---
Part 3: Functions & Functional Programming (Q41-55)
#41. What are
*args and **kwargs?A: They are used to pass a variable number of arguments to a function.
•
*args (Non-Keyword Arguments): Gathers extra positional arguments into a tuple.•
**kwargs (Keyword Arguments): Gathers extra keyword arguments into a dictionary.def my_func(a, b, *args, **kwargs):
print(f"a: {a}, b: {b}")
print(f"args: {args}")
print(f"kwargs: {kwargs}")
my_func(1, 2, 3, 4, name="Alice", city="NY")
a: 1, b: 2
args: (3, 4)
kwargs: {'name': 'Alice', 'city': 'NY'}
#42. What is a lambda function?
A: A lambda function is a small, anonymous function defined with the
lambda keyword. It can take any number of arguments but can only have one expression. They are often used when a simple function is needed for a short period.# A lambda function that doubles its input
double = lambda x: x * 2
print(double(5))
10
#43. What is a decorator?
A: A decorator is a design pattern in Python that allows a user to add new functionality to an existing object (like a function) without modifying its structure. Decorators are usually called before the definition of a function you want to decorate.
def my_decorator(func):
def wrapper():
print("Something is happening before the function is called.")
func()
print("Something is happening after the function is called.")
return wrapper
@my_decorator
def say_hello():
print("Hello!")
say_hello()
Something is happening before the function is called.
Hello!
Something is happening after the function is called.
#44. What is a generator? What is the
yield keyword?A: A generator is a special type of iterator that is simpler to create. Instead of returning a value and terminating, a generator function uses the
yield keyword. When yield is called, it "pauses" the function, returns the value, and saves its state. On the next call, it resumes execution from where it left off. Generators are memory efficient for working with large data sequences.def count_up_to(max):
count = 1
while count <= max:
yield count
count += 1
counter = count_up_to(3)
print(next(counter))
print(next(counter))
print(next(counter))
1
2
3
#45. What is the difference between an iterator and a generator?
A:
• Iterator: An object that implements the iterator protocol (
__iter__() and __next__() methods). It's more complex to create as you have to write a class.• Generator: A simpler way to create an iterator using a function with the
yield keyword. All generators are iterators, but not all iterators are generators.---
#46. Explain the
map() function.A: The
map(function, iterable) function applies the given function to every item of the iterable and returns a map object (an iterator) with the results.numbers = [1, 2, 3, 4]
squared_numbers = map(lambda x: x**2, numbers)
print(list(squared_numbers))
[1, 4, 9, 16]
#47. Explain the
filter() function.A: The
filter(function, iterable) function constructs an iterator from elements of the iterable for which the function returns True.numbers = [1, 2, 3, 4, 5, 6]
even_numbers = filter(lambda x: x % 2 == 0, numbers)
print(list(even_numbers))
[2, 4, 6]
#48. What does the
global keyword do?A: The
global keyword is used to modify a global variable from inside a function. Without it, assigning a value to a variable inside a function creates a new local variable.count = 0
def increment():
global count
count += 1
increment()
print(count)
1
#49. Can a function return multiple values?
A: Yes. A Python function can return multiple values by separating them with commas. Internally, Python packs these values into a single tuple and returns that tuple.
def get_name_and_age():
return "Alice", 25
name, age = get_name_and_age()
print(f"Name: {name}, Age: {age}")
Name: Alice, Age: 25
#50. What are docstrings?
A: A docstring is a string literal that occurs as the first statement in a module, function, class, or method definition. It is used to document what the code does. It is accessible via the
__doc__ attribute.def add(a, b):
"""This function adds two numbers and returns the result."""
return a + b
print(add.__doc__)
This function adds two numbers and returns the result.
---
#51. What are closures in Python?
A: A closure is a function object that remembers values in the enclosing scope even if they are not present in memory. It's a function that is defined inside another function (the enclosing function) and references variables from that enclosing function.
def outer_function(text):
def inner_function():
print(text) # inner_function "closes over" the text variable
return inner_function
my_func = outer_function("Hello")
my_func()
Hello
#52. What is recursion? Provide a simple example.
A: Recursion is a programming technique where a function calls itself in order to solve a problem. A recursive function must have a base case that stops the recursion.
# Calculate factorial using recursion
def factorial(n):
if n == 1:
return 1 # Base case
else:
return n * factorial(n - 1) # Recursive call
print(factorial(5))
120
#53. What is the difference between a function and a method?
A:
• A method is a function that "belongs to" an object. It is called on an object (
• A function is not associated with any object. It is called by its name (
#54. What does the
A: The
#55. What is a first-class function?
A: In Python, functions are "first-class citizens". This means they can be treated like any other object: they can be assigned to variables, stored in data structures (like lists), passed as arguments to other functions, and returned from functions.
---
Part 4: Object-Oriented Programming (OOP) (Q56-70)
#56. What are the four main principles of OOP?
A:
• Encapsulation: Bundling data (attributes) and methods that operate on the data into a single unit (a class).
• Inheritance: A mechanism where a new class (subclass) inherits attributes and methods from an existing class (superclass).
• Polymorphism: The ability of an object to take on many forms. For example, different classes can have methods with the same name that perform different actions.
• Abstraction: Hiding complex implementation details and showing only the essential features of the object.
#57. What is the difference between a class and an object?
A:
• A Class is a blueprint or template for creating objects. It defines a set of attributes and methods.
• An Object is an instance of a class. It is a concrete entity created from the class blueprint, with actual values for its attributes.
#58. What is
A:
#59. What is the
A:
#60. What is inheritance?
A: Inheritance allows us to define a class that inherits all the methods and properties from another class. The parent class is the class being inherited from, and the child class is the class that inherits.
---
#61. What is multiple inheritance?
A: Multiple inheritance is a feature where a class can inherit attributes and methods from more than one parent class. Python supports multiple inheritance.
A:
• A method is a function that "belongs to" an object. It is called on an object (
object.method()) and can access and modify the object's data (its attributes).• A function is not associated with any object. It is called by its name (
function()).#54. What does the
nonlocal keyword do?A: The
nonlocal keyword is used in nested functions to refer to a variable in the nearest enclosing scope (but not the global scope). It's used to modify variables in an outer (but not global) function.def outer():
x = "local"
def inner():
nonlocal x
x = "nonlocal"
print("inner:", x)
inner()
print("outer:", x)
outer()
inner: nonlocal
outer: nonlocal
#55. What is a first-class function?
A: In Python, functions are "first-class citizens". This means they can be treated like any other object: they can be assigned to variables, stored in data structures (like lists), passed as arguments to other functions, and returned from functions.
---
Part 4: Object-Oriented Programming (OOP) (Q56-70)
#56. What are the four main principles of OOP?
A:
• Encapsulation: Bundling data (attributes) and methods that operate on the data into a single unit (a class).
• Inheritance: A mechanism where a new class (subclass) inherits attributes and methods from an existing class (superclass).
• Polymorphism: The ability of an object to take on many forms. For example, different classes can have methods with the same name that perform different actions.
• Abstraction: Hiding complex implementation details and showing only the essential features of the object.
#57. What is the difference between a class and an object?
A:
• A Class is a blueprint or template for creating objects. It defines a set of attributes and methods.
• An Object is an instance of a class. It is a concrete entity created from the class blueprint, with actual values for its attributes.
#58. What is
self?A:
self represents the instance of the class. By using the self keyword, we can access the attributes and methods of the class in Python. It is the first argument passed to instance methods.#59. What is the
__init__ method?A:
__init__ is a special method in Python classes, also known as the constructor. It is automatically called when a new object of the class is created. It is used to initialize the object's attributes.class Dog:
def __init__(self, name):
self.name = name # Initialize the name attribute
print(f"{self.name} was born!")
my_dog = Dog("Rex")
Rex was born!
#60. What is inheritance?
A: Inheritance allows us to define a class that inherits all the methods and properties from another class. The parent class is the class being inherited from, and the child class is the class that inherits.
class Animal:
def speak(self):
print("Animal speaks")
class Dog(Animal): # Dog inherits from Animal
def bark(self):
print("Woof!")
d = Dog()
d.speak() # Inherited from Animal
d.bark()
Animal speaks
Woof!
---
#61. What is multiple inheritance?
A: Multiple inheritance is a feature where a class can inherit attributes and methods from more than one parent class. Python supports multiple inheritance.
class A:
def method(self):
print("Method from A")
class B:
def method(self):
print("Method from B")
class C(B, A): # Inherits from B, then A
pass
c = C()
c.method() # Calls method from B due to MRO
Method from B
#62. What is MRO (Method Resolution Order)?
A: MRO is the order in which Python looks for a method in a hierarchy of classes. In the case of multiple inheritance, it determines which parent class's method is called. You can view the MRO of a class using
#63. What is polymorphism?
A: Polymorphism means "many forms". In programming, it refers to methods/functions/operators with the same name that can be executed on many objects or classes.
#64. What is the difference between a class method and a static method?
A:
• Instance Method: Takes
•
•
#65. What is
A:
---
#66. What are public, protected, and private members?
A: These are conventions for encapsulation.
• Public: Accessible from anywhere. (e.g.,
• Protected: Conventionally treated as non-public; accessible within the class and its subclasses. Denoted by a single underscore prefix. (e.g.,
• Private: Accessible only from within the class. Python enforces this through name mangling. Denoted by a double underscore prefix. (e.g.,
#67. What is name mangling?
A: When an identifier starts with two underscores (like
#68. What are magic methods (or dunder methods)?
A: Magic methods are special methods with double underscores at the beginning and end of their names (e.g.,
#69. Explain the difference between
A:
•
•
A: MRO is the order in which Python looks for a method in a hierarchy of classes. In the case of multiple inheritance, it determines which parent class's method is called. You can view the MRO of a class using
ClassName.mro().#63. What is polymorphism?
A: Polymorphism means "many forms". In programming, it refers to methods/functions/operators with the same name that can be executed on many objects or classes.
class Cat:
def speak(self):
return "Meow"
class Dog:
def speak(self):
return "Woof"
def make_sound(animal):
print(animal.speak())
make_sound(Cat())
make_sound(Dog())
Meow
Woof
#64. What is the difference between a class method and a static method?
A:
• Instance Method: Takes
self as the first argument. It can access and modify instance attributes.•
@classmethod: Takes cls (the class itself) as the first argument. It can access and modify class attributes but not instance attributes. Often used as alternative constructors.•
@staticmethod: Does not take self or cls as an implicit first argument. It's essentially a regular function namespaced within the class. It cannot access or modify class or instance state.#65. What is
super()?A:
super() is a built-in function that returns a proxy object that allows you to refer to the parent class. It's commonly used in __init__ methods of child classes to call the parent class's __init__ method, ensuring that parent initializations are not missed.class Parent:
def __init__(self):
print("Parent init")
class Child(Parent):
def __init__(self):
super().__init__() # Call the Parent's init method
print("Child init")
c = Child()
Parent init
Child init
---
#66. What are public, protected, and private members?
A: These are conventions for encapsulation.
• Public: Accessible from anywhere. (e.g.,
member)• Protected: Conventionally treated as non-public; accessible within the class and its subclasses. Denoted by a single underscore prefix. (e.g.,
_member)• Private: Accessible only from within the class. Python enforces this through name mangling. Denoted by a double underscore prefix. (e.g.,
__member)#67. What is name mangling?
A: When an identifier starts with two underscores (like
__spam), it is textually replaced with _classname__spam. This is done to avoid naming conflicts with subclasses.#68. What are magic methods (or dunder methods)?
A: Magic methods are special methods with double underscores at the beginning and end of their names (e.g.,
__init__, __len__, __str__). They are not meant to be called directly but are invoked internally by Python in response to certain operations. For example, len(my_object) calls my_object.__len__().#69. Explain the difference between
__str__ and __repr__.A:
•
__str__(): Called by str(object) and print(object). It should return a user-friendly, readable string representation of the object.•
__repr__(): Called by repr(object). It should return an unambiguous, official string representation of the object, which can ideally be used to recreate the object (e.g., eval(repr(object)) == object). If __str__ is not defined, __repr__ is used as a fallback.#70. What is operator overloading?
A: Operator overloading allows you to redefine the behavior of built-in operators (like
---
Part 5: Advanced Concepts & Libraries (Q71-85)
#71. Explain exception handling in Python.
A: Exception handling is a mechanism for responding to runtime errors.
•
•
•
•
#72. How do you raise a custom exception?
A: You can define a custom exception by creating a new class that inherits from the built-in
#73. What is the purpose of the
A: The
#74. What is the difference between multithreading and multiprocessing?
A:
• Multithreading: Multiple threads run within the same process, sharing the same memory space. Due to the GIL, it's best for I/O-bound tasks (like network requests or file operations) where threads can wait without blocking the entire program.
• Multiprocessing: Multiple processes run, each with its own memory space and Python interpreter. This allows for true parallelism and is ideal for CPU-bound tasks (like heavy calculations) as it bypasses the GIL.
#75. What is the difference between a module and a package?
A:
• Module: A single Python file (
• Package: A way of organizing related modules into a directory hierarchy. A directory must contain a file named
---
#76. What are virtual environments? Why are they important?
A: A virtual environment is an isolated Python environment that allows you to manage dependencies for a specific project separately. They are important because they prevent package version conflicts between different projects on the same machine.
#77. What is
A:
A: Operator overloading allows you to redefine the behavior of built-in operators (like
+, -, *) for your custom classes. This is done by implementing the corresponding magic methods (e.g., __add__ for +, __mul__ for *).---
Part 5: Advanced Concepts & Libraries (Q71-85)
#71. Explain exception handling in Python.
A: Exception handling is a mechanism for responding to runtime errors.
•
try: The block of code to be attempted, which may cause an error.•
except: This block is executed if an error occurs in the try block. You can specify the type of exception to catch.•
else: This block is executed if no exceptions are raised in the try block.•
finally: This block is always executed, whether an exception occurred or not. It's often used for cleanup operations.try:
result = 10 / 2
except ZeroDivisionError:
print("Cannot divide by zero!")
else:
print(f"Result is {result}")
finally:
print("Execution finished.")
Result is 5.0
Execution finished.
#72. How do you raise a custom exception?
A: You can define a custom exception by creating a new class that inherits from the built-in
Exception class. Then, use the raise keyword to throw it.class MyCustomError(Exception):
pass
raise MyCustomError("Something went wrong!")
#73. What is the purpose of the
with statement?A: The
with statement simplifies exception handling by encapsulating common try...finally cleanup patterns. It is used with objects that support the context management protocol (which have __enter__ and __exit__ methods). It's most commonly used for managing file streams, ensuring the file is closed automatically.# The file is automatically closed after this block
with open('file.txt', 'w') as f:
f.write('hello')
#74. What is the difference between multithreading and multiprocessing?
A:
• Multithreading: Multiple threads run within the same process, sharing the same memory space. Due to the GIL, it's best for I/O-bound tasks (like network requests or file operations) where threads can wait without blocking the entire program.
• Multiprocessing: Multiple processes run, each with its own memory space and Python interpreter. This allows for true parallelism and is ideal for CPU-bound tasks (like heavy calculations) as it bypasses the GIL.
#75. What is the difference between a module and a package?
A:
• Module: A single Python file (
.py) containing statements and definitions.• Package: A way of organizing related modules into a directory hierarchy. A directory must contain a file named
__init__.py (which can be empty) to be considered a package.---
#76. What are virtual environments? Why are they important?
A: A virtual environment is an isolated Python environment that allows you to manage dependencies for a specific project separately. They are important because they prevent package version conflicts between different projects on the same machine.
#77. What is
pip?A:
pip is the standard package manager for Python. It allows you to install and manage third-party libraries and packages from the Python Package Index (PyPI).