A quick guide to Python basics for programmers switching from other languages.
Variables and Data Types¶
x = 10 # Integer
y = 3.14 # Float
name = "Alice" # String
is_active = True # Boolean
print(x, y, name, is_active)10 3.14 Alice True
String Operations¶
text = " Hello, World! "
print(text.strip()) # Remove whitespace
print(text.count('l')) # count occurance
print(text.lower()) # Convert to lowercase
print(text.upper()) # Convert to uppercase
print(text.replace("World", "Python")) # Replace substring
print(text.split(",")) # Split string
print(len(text)) # String length
print("-"*50)
w = "I Love L i n u x !"
print(w[0])
print(w[2:6])
print(w[7::2])
print("-"*50)
# String formatting
name = "Alice"
age = 30
print(f"My name is \"{name}\" and I am {age} years old") # f-string
print("My name is {} and I am {} years old. Don't you get it?".format(name, age)) # format methodHello, World!
3
hello, world!
HELLO, WORLD!
Hello, Python!
[' Hello', ' World! ']
17
--------------------------------------------------
I
Love
Linux!
--------------------------------------------------
My name is "Alice" and I am 30 years old
My name is Alice and I am 30 years old. Don't you get it?
Lists¶
fruits = [1, 2, "apple", "banana", "cherry"]
print(fruits)
fruits.append("orange")
print(fruits)
print(fruits[-2:]) # Last 2
print(len(fruits)) # Length
print("-" * 50)
list_2 = ["orange", "mango"]
print(fruits + list_2)
del(list_2[1])
print(fruits + list_2)
print("mango" in list_2)
del(list_2)
print("-" * 50)
print(list("ArchLinux!"))[1, 2, 'apple', 'banana', 'cherry']
[1, 2, 'apple', 'banana', 'cherry', 'orange']
['cherry', 'orange']
6
--------------------------------------------------
[1, 2, 'apple', 'banana', 'cherry', 'orange', 'orange', 'mango']
[1, 2, 'apple', 'banana', 'cherry', 'orange', 'orange']
False
--------------------------------------------------
['A', 'r', 'c', 'h', 'L', 'i', 'n', 'u', 'x', '!']
Tuples¶
point = (2, 3)
print(point)
# Tuples are immutable(2, 3)
Dictionaries¶
person = {"name": "Bob", "age": 25}
print(person)
person["age"] = 26
print(person['age'])
print(person.keys())
print(person.values())
print(len(person))
print('-' * 50)
print(dict([("UC Berkeley", "USA"), ('Oxford', 'UK')]))
print('UC Berkeley' in dict([("UC Berkeley", "USA"), ('Oxford', 'UK')])){'name': 'Bob', 'age': 25}
26
dict_keys(['name', 'age'])
dict_values(['Bob', 26])
2
--------------------------------------------------
{'UC Berkeley': 'USA', 'Oxford': 'UK'}
True
Sets¶
numbers = {1, 2, 3, 2}
print(numbers) # Duplicates removed{1, 2, 3}
Conditional Statements¶
age = 18
if age >= 18:
print("Adult")
elif age < 5:
print("child")
else:
print("Minor")Adult
Loops¶
# For loop
fruits = [1, 2, "apple", "banana", "cherry"]
for fruit in fruits:
print(fruit)
print("-" * 50)
# While loop
count = 0
while count < 3:
print(count)
count += 11
2
apple
banana
cherry
--------------------------------------------------
0
1
2
Exception Handling¶
try:
result = 10 / 0
except ZeroDivisionError:
print("Cannot divide by zero!")Cannot divide by zero!
List Comprehensions¶
Efficient way to create lists - very useful for data processing.
# List comprehensions
squares = [x**2 for x in range(5)]
print(squares)
# List comprehension with condition
even_squares = [x**2 for x in range(10) if x % 2 == 0]
print(even_squares)
# Dictionary comprehension
square_dict = {x: x**2 for x in range(5)}
print(square_dict)
# Set comprehension
unique_squares = {x**2 for x in range(-3, 4)}
print(unique_squares)[0, 1, 4, 9, 16]
[0, 4, 16, 36, 64]
{0: 0, 1: 1, 2: 4, 3: 9, 4: 16}
{0, 9, 4, 1}
Regular Expressions¶
Pattern matching for text processing and data cleaning. To learn about regular expressions, refer to the Regular Expressions site, cause it’s awesome.
import re
text = "Contact us at john@example.com or call 123-456-7890"# Find email addresses
emails = re.findall(r'\w+@\w+\.\w+', text)
print('Emails:', emails)Emails: ['john@example.com']
# Find phone numbers
phones = re.findall(r'\d{3}-\d{3}-\d{4}', text)
print('Phones:', phones)Phones: ['123-456-7890']
# Replace phone numbers with a placeholder
clean_text = re.sub(r'\d{3}-\d{3}-\d{4}', '[PHONE]', text)
print('Cleaned text:', clean_text)Cleaned text: Contact us at john@example.com or call [PHONE]
# Split text into words
words = re.split(r'\s+', text)
print('Words:', words)Words: ['Contact', 'us', 'at', 'john@example.com', 'or', 'call', '123-456-7890']
# Extract username, domain, and extension from email
pattern = r'(\w+)@(\w+)\.(\w+)'
match = re.search(pattern, text)
if match:
print('Username:', match.group(1))
print('Domain:', match.group(2))
print('Extension:', match.group(3))Username: john
Domain: example
Extension: com