Hello World
A sample Python program is shown here.
def greet(name):
return f"Hello, {name}!"
if __name__ == "__main__":
message = greet("world")
print(message)
Run the program as below:
$ python hello.py
Strings
str_single = "Hello"
str_multiline = """Multiline
string"""
print(str_multiline.upper())
Useful string methods:
name = "John Doe"
print(name.lower()) # john doe
print(name.split()) # ['John', 'Doe']
Numbers
integer = 42
floating_point = 3.14
complex_number = 2 + 3j
# Converting between types
float_to_int = int(3.7) # 3
Working with NumPy for advanced number manipulation:
import numpy as np
array = np.array([1, 2, 3])
print(array.mean()) # 2.0
Condition
day = "sunday"
if day in ["sunday", "saturday"]:
print("Rest!")
elif day == "monday" and is_tired():
print("Groan!")
else:
print("Work!")
Example with try/except:
try:
result = 10 / 0
except ZeroDivisionError:
print("Cannot divide by zero!")
finally:
print("Cleanup complete.")
Loops
For loop example:
for i in range(5):
print(f"Iteration {i}")
While loop example:
count = 0
while count < 5:
print(f"Count is {count}")
count += 1
File Operations
Reading and writing text files:
with open("example.txt", "w") as file:
file.write("Hello, File!")
with open("example.txt", "r") as file:
content = file.read()
print(content)
Handling CSV files with pandas:
import pandas as pd
# Reading a CSV file
data = pd.read_csv("data.csv")
print(data.head())
# Writing a CSV file
data.to_csv("output.csv", index=False)