Python Cheat Sheet

 Python cheat sheet with some commonly used syntax and concepts. This cheat sheet is not exhaustive but covers essential Python elements that can help you get started with Python programming:

# Comments (Single-line comment)
# This is a comment in Python.

# Variables and Data Types
age = 25
name = "John"
is_student = True
pi = 3.14159

# Basic Input and Output
print("Hello, World!")
user_input = input("Enter your name: ")
print("Hello,", user_input)

# Conditionals (if-elif-else)
if age < 18:
    print("You are a minor.")
elif age >= 18 and age < 60:
    print("You are an adult.")
else:
    print("You are a senior citizen.")

# Loops
for i in range(1, 6):  # Loop from 1 to 5 (inclusive)
    print(i)

while age < 30:
    print("Age is", age)
    age += 1

# Lists
numbers = [1, 2, 3, 4, 5]
fruits = ["apple", "banana", "orange"]
mixed_list = [1, "hello", True, 3.14]

# List Operations
print(len(numbers))        # Length of the list
print(numbers[0])          # Access element at index 0
print(fruits.index("banana"))  # Find index of "banana"
numbers.append(6)          # Add element to the end of the list
numbers.pop()              # Remove the last element

# Strings
message = "Hello, Python!"

# String Operations
print(len(message))        # Length of the string
print(message[0])          # Access character at index 0
print(message.upper())     # Convert to uppercase
print(message.lower())     # Convert to lowercase
print(message.replace("Python", "World"))  # Replace "Python" with "World"

# Functions
def greet(name):
    return "Hello, " + name

print(greet("Alice"))

# File Handling
file = open("data.txt", "w")  # Open file in write mode
file.write("Hello, Python!")  # Write data to the file
file.close()                 # Close the file

# Exception Handling
try:
    result = 10 / 0
except ZeroDivisionError:
    print("Error: Cannot divide by zero.")
else:
    print("Result:", result)
finally:
    print("This will be executed no matter what.")
 

Comments

Popular posts from this blog

Learn (Gujarati Typing) Terafont-Varun Keyboard Layout by Sama Soyab

Loops Example in Python

Tally Shortcut key and Video Tutorial Link by Sama Soyab (ACI BHUJ)