# Input
name = input("Enter your name: ")
age = int(input("Enter your age: ")) # Convert input to integer
height = float(input("Enter your height in meters: ")) # Convert input to float
# Output
print("Hello, World!") # Basic print
print(f"Your name is {name} and you are {age} years old.") # printing variable in string
print("Hello ", name) # Use a comma or a + to print a string and variable in the same line
# For loops
# range(stop)
for i in range(5):
print(i) # Prints 0, 1, 2, 3, 4
# range(start, stop)
for i in range(2, 6):
print(i) # Prints 2, 3, 4, 5
# range(start, stop, step)
for i in range(0, 10, 2):
print(i) # Prints 0, 2, 4, 6, 8
# Looping through a list
fruits = ["apple", "banana", "cherry"]
for fruit in fruits:
print(fruit)
# While loop
count = 0
while count < 5:
print(count)
count += 1
x = 10
y = 5
# If-elif-else statement
if x > y:
print("x is greater than y")
elif x == y:
print("x is equal to y")
else:
print("x is less than y")
# Nested if statements
if x > 0:
if y > 0:
print("Both x and y are positive")
else:
print("x is positive, but y is not")
import random
random_int = random.randint(1, 10) # Random integer between 1 and 10 (inclusive)
random_float = random.random() # Random float between 0 and 1 (exclusive)
random_fruit = random.choice(fruits)
random.shuffle(fruits)
sample = random.sample(range(100), 5) # 5 unique random numbers from 0-99
# Basic function
def greet(name):
return f"Hello, {name}!"
# Function with default parameter
def power(base, exponent=2):
return base ** exponent
# Function with multiple returns
def divide(a, b):
if b == 0:
return None, "Error: Division by zero"
return a / b, "Success"
text = "Mr. Cadamuro is awesome"
# String methods
print(len(text)) # Length of string
print(text.upper()) # Convert to uppercase
print(text.lower()) # Convert to lowercase
print(text.title()) # Title case
print(text.strip()) # Remove leading/trailing whitespace
print(text.replace("awesome", "great")) # Replace substring
print(text.split()) # Split string into list
# String slicing
print(text[0]) # First character
print(text[-1]) # Last character
print(text[7:9]) # Slice from index 7 to 8
print(text[:6]) # Slice from start to index 5
print(text[7:]) # Slice from index 7 to end
print(text[::-1]) # Reverse string
# String concatenation
new_text = text + " and fun"
fruits = ["apple", "banana", "cherry", "date"]
# Accessing elements
print(fruits[0]) # First element
print(fruits[-1]) # Last element
# Modifying lists
fruits.append("elderberry") # Add to end
fruits.insert(1, "blueberry") # Insert at index 1
fruits.remove("cherry") # Remove by value
popped_fruit = fruits.pop() # Remove and return last item
del fruits[0] # Remove by index
# List operations
print(len(fruits)) # Length of list
print(sorted(fruits)) # Return sorted list (doesn't modify original)
fruits.sort() # Sort list in place
fruits.reverse() # Reverse list in place
# List slicing (similar to string slicing)
print(fruits[1:3]) # Slice from index 1 to 2
print(fruits[::-1]) # Reverse list
# Nested lists
matrix = [[1, 2, 3], [4, 5, 6], [7, 8, 9]]
print(matrix[1][1]) # Access element in nested list
# Creating a dictionary
person = {
"name": "Alice",
"age": 30,
"city": "New York"
}
# Accessing values
print(person["name"])
print(person.get("age")) # Safer method if key might not exist
# Modifying dictionaries
person["job"] = "Engineer" # Add new key-value pair
person["age"] = 31 # Modify existing value
del person["city"] # Remove a key-value pair
# Dictionary methods
print(person.keys()) # Get all keys
print(person.values()) # Get all values
print(person.items()) # Get all key-value pairs
# Looping through dictionaries
for key in person:
print(f"{key}: {person[key]}")
for key, value in person.items():
print(f"{key}: {value}")
import math
# Basic arithmetic
a, b = 10, 3
print(a + b) # Addition
print(a - b) # Subtraction
print(a * b) # Multiplication
print(a / b) # Division (float result)
print(a // b) # Floor division (integer result)
print(a % b) # Modulus (remainder)
print(a ** b) # Exponentiation
# Math functions
print(abs(-5)) # Absolute value
print(round(3.7)) # Rounding
print(math.ceil(3.2)) # Ceiling
print(math.floor(3.8)) # Floor
print(math.sqrt(16)) # Square root
print(math.pi) # Pi constant
print(math.e) # Euler's number
# Trigonometry
print(math.sin(math.pi/2)) # Sine
print(math.cos(0)) # Cosine
print(math.tan(math.pi/4)) # Tangent
# Importing an entire module
import math
print(math.pi)
# Importing specific functions
from random import randint, choice
print(randint(1, 10))
# Importing with an alias
import numpy as np
arr = np.array([1, 2, 3])
# Importing all functions (not recommended)
from math import *
print(sqrt(16))