#Python #Top60 #BuiltInFunctions
#1.
Prints the specified message to the screen.
#2.
Returns the number of items in an object.
#3.
Returns the type of an object.
#4.
Allows user input.
#5.
Converts a value to an integer number.
---
#Python #DataTypes #Conversion
#6.
Converts a value to a string.
#7.
Converts a value to a floating-point number.
#8.
Converts a value to a Boolean (True or False).
#9.
Converts an iterable (like a tuple or string) to a list.
#10.
Converts an iterable to a tuple.
---
#Python #Math #Functions
#11.
Returns the sum of all items in an iterable.
#12.
Returns the largest item in an iterable.
#13.
Returns the smallest item in an iterable.
#14.
Returns the absolute (positive) value of a number.
#15.
Rounds a number to a specified number of decimals.
---
#Python #Iterables #Functions
#16.
Returns a sequence of numbers, starting from 0 by default, and increments by 1.
#17.
Returns a new sorted list from the items in an iterable.
#18.
Returns an enumerate object, which contains pairs of index and value.
#19.
Returns an iterator that aggregates elements from two or more iterables.
#20.
Applies a given function to each item of an iterable and returns a map object.
#1.
print()Prints the specified message to the screen.
print("Hello, World!")Hello, World!
#2.
len()Returns the number of items in an object.
my_list = [1, 2, 3, 4]
print(len(my_list))
4
#3.
type()Returns the type of an object.
name = "Python"
print(type(name))
<class 'str'>
#4.
input()Allows user input.
username = input("Enter your name: ")
print("Hello, " + username)Enter your name: Alex
Hello, Alex
#5.
int()Converts a value to an integer number.
string_number = "101"
number = int(string_number)
print(number + 9)
110
---
#Python #DataTypes #Conversion
#6.
str()Converts a value to a string.
age = 25
print("My age is " + str(age))
My age is 25
#7.
float()Converts a value to a floating-point number.
integer_value = 5
print(float(integer_value))
5.0
#8.
bool()Converts a value to a Boolean (True or False).
print(bool(1))
print(bool(0))
print(bool("Hello"))
print(bool(""))
True
False
True
False
#9.
list()Converts an iterable (like a tuple or string) to a list.
my_tuple = (1, 2, 3)
my_list = list(my_tuple)
print(my_list)
[1, 2, 3]
#10.
tuple()Converts an iterable to a tuple.
my_list = [4, 5, 6]
my_tuple = tuple(my_list)
print(my_tuple)
(4, 5, 6)
---
#Python #Math #Functions
#11.
sum()Returns the sum of all items in an iterable.
numbers = [10, 20, 30]
print(sum(numbers))
60
#12.
max()Returns the largest item in an iterable.
numbers = [5, 29, 12, 99]
print(max(numbers))
99
#13.
min()Returns the smallest item in an iterable.
numbers = [5, 29, 12, 99]
print(min(numbers))
5
#14.
abs()Returns the absolute (positive) value of a number.
negative_number = -15
print(abs(negative_number))
15
#15.
round()Rounds a number to a specified number of decimals.
pi = 3.14159
print(round(pi, 2))
3.14
---
#Python #Iterables #Functions
#16.
range()Returns a sequence of numbers, starting from 0 by default, and increments by 1.
for i in range(5):
print(i)
0
1
2
3
4
#17.
sorted()Returns a new sorted list from the items in an iterable.
unsorted_list = [3, 1, 4, 1, 5, 9]
sorted_list = sorted(unsorted_list)
print(sorted_list)
[1, 1, 3, 4, 5, 9]
#18.
enumerate()Returns an enumerate object, which contains pairs of index and value.
fruits = ['apple', 'banana', 'cherry']
for index, fruit in enumerate(fruits):
print(index, fruit)
0 apple
1 banana
2 cherry
#19.
zip()Returns an iterator that aggregates elements from two or more iterables.
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.
#20.
map()Applies a given function to each item of an iterable and returns a map object.
❤1
def square(n):
return n * n
numbers = [1, 2, 3, 4]
squared_numbers = map(square, numbers)
print(list(squared_numbers))
[1, 4, 9, 16]
---
#Python #FunctionalProgramming #Keywords
#21.
filter()Constructs an iterator from elements of an iterable for which a function returns true.
def is_even(n):
return n % 2 == 0
numbers = [1, 2, 3, 4, 5, 6]
even_numbers = filter(is_even, numbers)
print(list(even_numbers))
[2, 4, 6]
#22.
lambdaCreates a small anonymous function.
multiply = lambda a, b: a * b
print(multiply(5, 6))
30
#23.
defKeyword used to define a function.
def greet(name):
return f"Hello, {name}!"
print(greet("World"))
Hello, World!
#24.
returnKeyword used to exit a function and return a value.
def add(a, b):
return a + b
result = add(7, 8)
print(result)
15
#25.
isinstance()Checks if an object is an instance of a specified class.
number = 10
print(isinstance(number, int))
print(isinstance(number, str))
True
False
---
#Python #ControlFlow #Keywords
#26.
if, elif, elseUsed for conditional execution.
score = 85
if score >= 90:
print("Grade A")
elif score >= 80:
print("Grade B")
else:
print("Grade C")
Grade B
#27.
forUsed to iterate over a sequence (like a list, tuple, or string).
colors = ["red", "green", "blue"]
for color in colors:
print(color)
red
green
blue
#28.
whileCreates a loop that executes as long as a condition is true.
count = 0
while count < 3:
print(f"Count is {count}")
count += 1
Count is 0
Count is 1
Count is 2
#29.
breakExits the current loop.
for i in range(10):
if i == 5:
break
print(i)
0
1
2
3
4
#30.
continueSkips the rest of the code inside the current loop iteration and proceeds to the next one.
for i in range(5):
if i == 2:
continue
print(i)
0
1
3
4
---
#Python #StringMethods #TextManipulation
#31.
.upper()Converts a string into upper case.
message = "hello python"
print(message.upper())
HELLO PYTHON
#32.
.lower()Converts a string into lower case.
message = "HELLO PYTHON"
print(message.lower())
hello python
#33.
.strip()Removes any leading and trailing whitespace.
text = " some space "
print(text.strip())
some space
#34.
.split()Splits the string at the specified separator and returns a list.
sentence = "Python is fun"
words = sentence.split(' ')
print(words)
['Python', 'is', 'fun']
#35.
.join()Joins the elements of an iterable to the end of the string.
words = ['Python', 'is', 'awesome']
sentence = " ".join(words)
print(sentence)
Python is awesome
---
#Python #MoreStringMethods #Text
#36.
.replace()Returns a string where a specified value is replaced with another value.
text = "I like cats."
new_text = text.replace("cats", "dogs")
print(new_text)
I like dogs.
#37.
Returns
#38.
Returns
#39.
Searches the string for a specified value and returns the position of where it was found. Returns -1 if not found.
#40.
A way to embed expressions inside string literals.
---
#Python #ListMethods #DataStructures
#41.
Adds an element at the end of the list.
#42.
Removes the element at the specified position.
#43.
Removes the first item with the specified value.
#44.
Adds an element at the specified position.
#45.
Sorts the list in place.
---
#Python #DictionaryMethods #DataStructures
#46.
Creates a dictionary.
#47.
Returns a view object displaying a list of all the keys in the dictionary.
#48.
Returns a view object displaying a list of all the values in the dictionary.
#49.
Returns a view object displaying a list of a given dictionary's key-value tuple pairs.
#50.
Returns the value of the specified key. Provides a default value if the key does not exist.
---
#Python #ErrorHandling #FileIO
#51.
Used to handle errors and exceptions.
.startswith()Returns
True if the string starts with the specified value.filename = "document.pdf"
print(filename.startswith("doc"))
True
#38.
.endswith()Returns
True if the string ends with the specified value.filename = "image.jpg"
print(filename.endswith(".jpg"))
True
#39.
.find()Searches the string for a specified value and returns the position of where it was found. Returns -1 if not found.
text = "hello world"
print(text.find("world"))
6
#40.
f-string (Formatted String Literal)A way to embed expressions inside string literals.
name = "Alice"
age = 30
print(f"{name} is {age} years old.")
Alice is 30 years old.
---
#Python #ListMethods #DataStructures
#41.
.append()Adds an element at the end of the list.
fruits = ['apple', 'banana']
fruits.append('cherry')
print(fruits)
['apple', 'banana', 'cherry']
#42.
.pop()Removes the element at the specified position.
fruits = ['apple', 'banana', 'cherry']
fruits.pop(1) # Removes 'banana'
print(fruits)
['apple', 'cherry']
#43.
.remove()Removes the first item with the specified value.
fruits = ['apple', 'banana', 'cherry', 'banana']
fruits.remove('banana')
print(fruits)
['apple', 'cherry', 'banana']
#44.
.insert()Adds an element at the specified position.
fruits = ['apple', 'cherry']
fruits.insert(1, 'banana')
print(fruits)
['apple', 'banana', 'cherry']
#45.
.sort()Sorts the list in place.
numbers = [3, 1, 5, 2]
numbers.sort()
print(numbers)
[1, 2, 3, 5]
---
#Python #DictionaryMethods #DataStructures
#46.
dict()Creates a dictionary.
my_dict = dict(name="John", age=36)
print(my_dict)
{'name': 'John', 'age': 36}#47.
.keys()Returns a view object displaying a list of all the keys in the dictionary.
person = {'name': 'Alice', 'age': 25}
print(person.keys())dict_keys(['name', 'age'])
#48.
.values()Returns a view object displaying a list of all the values in the dictionary.
person = {'name': 'Alice', 'age': 25}
print(person.values())dict_values(['Alice', 25])
#49.
.items()Returns a view object displaying a list of a given dictionary's key-value tuple pairs.
person = {'name': 'Alice', 'age': 25}
print(person.items())dict_items([('name', 'Alice'), ('age', 25)])#50.
.get()Returns the value of the specified key. Provides a default value if the key does not exist.
person = {'name': 'Alice', 'age': 25}
print(person.get('city', 'Unknown'))Unknown
---
#Python #ErrorHandling #FileIO
#51.
try, exceptUsed to handle errors and exceptions.
try:
result = 10 / 0
except ZeroDivisionError:
result = "You can't divide by zero!"
print(result)
You can't divide by zero!
#52.
open()Opens a file and returns a file object.
# This code creates a file named "myfile.txt"
# No direct output, but a file is created.
file = open("myfile.txt", "w")
file.close()
print("File created and closed.")
File created and closed.
#53.
.write()Writes the specified string to the file.
file = open("myfile.txt", "w")
file.write("Hello, File!")
file.close()
# No direct output, but content is written to myfile.txt
print("Content written to file.")Content written to file.
#54.
.read()Reads the content of the file.
# Assuming "myfile.txt" contains "Hello, File!"
file = open("myfile.txt", "r")
content = file.read()
print(content)
file.close()
Hello, File!
#55.
withA context manager, often used with
open() to automatically handle file closing.with open("myfile.txt", "w") as f:
f.write("This is safer!")
# The file is automatically closed here.
print("File written and closed safely.")File written and closed safely.
---
#Python #Keywords #Advanced
#56.
importUsed to import modules.
import math
print(math.sqrt(16))
4.0
#57.
from ... importImports specific parts of a module.
from datetime import date
today = date.today()
print(today)
2023-10-27
(Note: Output date will be the current date)
#58.
inMembership operator. Checks if a value is present in a sequence.
my_list = [1, 2, 3, 4, 5]
print(3 in my_list)
print(10 in my_list)
True
False
#59.
delDeletes an object (variable, list item, dictionary entry, etc.).
my_list = [10, 20, 30]
del my_list[1] # delete item at index 1
print(my_list)
[10, 30]
#60.
passA null statement. It's used when a statement is required syntactically but you do not want any command or code to execute.
def my_empty_function():
pass # To be implemented later
my_empty_function() # This does nothing and produces no error
print("Function executed without error.")
Function executed without error.
━━━━━━━━━━━━━━━
By: @DataScience4 ✨
❤1
Top 30 Cyber Security Commands & Tools
#CyberSecurity #Reconnaissance #InfoGathering
#1.
Tests reachability of a host on an IP network and measures round-trip time.
#2.
Retrieves registration information for a domain name or IP address.
#3.
(Domain Information Groper) A tool for querying DNS servers.
#4.
Network Mapper. A powerful tool for network discovery, port scanning, and security auditing.
#5.
The "Swiss army knife" of networking. Can be used for port scanning, file transfer, and creating backdoors.
---
#CyberSecurity #Networking #Analysis
#6.
Displays active network connections, routing tables, and interface statistics.
#7.
Traces the network path (hops) to a remote host.
#8.
A powerful command-line packet analyzer that allows you to capture and display network traffic.
#9.
Displays and modifies the Address Resolution Protocol (ARP) cache, which maps IP addresses to MAC addresses.
#10.
A modern tool to show and manipulate routing, devices, policy routing, and tunnels. (Replaces
#CyberSecurity #Reconnaissance #InfoGathering
#1.
pingTests reachability of a host on an IP network and measures round-trip time.
ping -c 4 google.com
PING google.com (142.250.72.14) 56(84) bytes of data.
64 bytes from lhr48s23-in-f14.1e100.net (142.250.72.14): icmp_seq=1 ttl=118 time=8.53 ms
...
--- google.com ping statistics ---
4 packets transmitted, 4 received, 0% packet loss, time 3005ms
#2.
whoisRetrieves registration information for a domain name or IP address.
whois google.com
Domain Name: GOOGLE.COM
Registry Domain ID: 2138514_DOMAIN_COM-VRSN
Registrar WHOIS Server: whois.markmonitor.com
...
Registrant Organization: Google LLC
Registrant State/Province: CA
Registrant Country: US
#3.
dig(Domain Information Groper) A tool for querying DNS servers.
dig google.com
; <<>> DiG 9.18.1-1-Debian <<>> google.com
;; ANSWER SECTION:
google.com. 156 IN A 142.250.187.238
...
;; Query time: 12 msec
;; SERVER: 8.8.8.8#53(8.8.8.8)
#4.
nmapNetwork Mapper. A powerful tool for network discovery, port scanning, and security auditing.
nmap -sV -p 80,443 scanme.nmap.org
Starting Nmap 7.92 ( https://nmap.org ) at ...
Nmap scan report for scanme.nmap.org (45.33.32.156)
Host is up (0.16s latency).
PORT STATE SERVICE VERSION
80/tcp open http Apache httpd 2.4.7 ((Ubuntu))
443/tcp open ssl/http Apache httpd 2.4.7 ((Ubuntu))
#5.
netcat (nc)The "Swiss army knife" of networking. Can be used for port scanning, file transfer, and creating backdoors.
nc -zv scanme.nmap.org 80
Connection to scanme.nmap.org (45.33.32.156) 80 port [tcp/http] succeeded!
---
#CyberSecurity #Networking #Analysis
#6.
netstatDisplays active network connections, routing tables, and interface statistics.
netstat -tulpn
Active Internet connections (only servers)
Proto Recv-Q Send-Q Local Address Foreign Address State PID/Program name
tcp 0 0 127.0.0.1:5432 0.0.0.0:* LISTEN 675/postgres
tcp 0 0 0.0.0.0:22 0.0.0.0:* LISTEN 789/sshd
udp 0 0 0.0.0.0:68 0.0.0.0:* 654/dhclient
#7.
tracerouteTraces the network path (hops) to a remote host.
traceroute 8.8.8.8
traceroute to 8.8.8.8 (8.8.8.8), 30 hops max, 60 byte packets
1 gateway (192.168.1.1) 1.234 ms 1.567 ms 1.890 ms
2 isp-router.net (10.0.0.1) 5.432 ms 5.678 ms 5.901 ms
...
10 142.251.52.221 (142.251.52.221) 10.112 ms 10.345 ms 10.578 ms
11 dns.google (8.8.8.8) 10.801 ms 10.923 ms 11.045 ms
#8.
tcpdumpA powerful command-line packet analyzer that allows you to capture and display network traffic.
sudo tcpdump -i eth0 -c 5 port 80
tcpdump: verbose output suppressed, use -v or -vv for full protocol decode
listening on eth0, link-type EN10MB (Ethernet), capture size 262144 bytes
14:30:01.123456 IP my-pc.54321 > example.com.80: Flags [S], seq 123456789, win 64240, options [mss 1460,sackOK,TS val 10,ecr 0], length 0
... (4 more packets) ...
5 packets captured
#9.
arpDisplays and modifies the Address Resolution Protocol (ARP) cache, which maps IP addresses to MAC addresses.
arp -a
? (192.168.1.1) at 00:1a:2b:3c:4d:5e [ether] on eth0
? (192.168.1.105) at 98:76:54:32:10:fe [ether] on eth0
#10.
ipA modern tool to show and manipulate routing, devices, policy routing, and tunnels. (Replaces
ifconfig).ip addr show
❤1
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