✅ Python Project 2: Calculator (CLI) 🔢💻 📌 Problem Statement: Build a simple command-line calculator that performs basic arithmetic: addition, subtraction, multiplication, and division. 🧠 What You'll Learn: - Taking user input - Writing functions - Using if/else statements - Handling edge cases (like division by zero) ✅ Python Code: def add(x, y): return x + y def subtract(x, y): return x - y def multiply(x, y): return x * y def divide(x, y): if y == 0: return "Error: Division by zero" return x / y print("=== Simple Calculator ===") print("Choose operation:") print("1. Add (+)") print("2. Subtract (-)") print("3. Multiply (*)") print("4. Divide (/)") op = input("Enter your choice (+, -, *, /): ") a = float(input("Enter first number: ")) b = float(input("Enter second number: ")) if op == '+': result = add(a, b) elif op == '-': result = subtract(a, b) elif op == '*': result = multiply(a, b) elif op == '/': result = divide(a, b) else: result = "Invalid operator" print("Result:", result) 📥 Sample Input: Enter your choice (+, -, *, /): + Enter first number: 10 Enter second number: 5 📤 Output: Result: 15.0 React ❤️ if you're ready for the next project
"Building a Simple CLI Calculator in Python"
More Relevant Posts
-
🐍💡Mastering Python Operators — The Building Blocks of Every Code! 💻 When we write code in Python, operators silently do the heavy lifting — they help us calculate, compare, assign, and make logical decisions effortlessly. Whether you’re a beginner or a pro, understanding operators makes your code cleaner and smarter! ✨ 🔹 Let’s break it down 1️⃣ Arithmetic Operators ➕➖✖️➗ Used for mathematical operations. a = 10 b = 3 print(a + b) # 13 print(a ** b) # 1000 (Exponent) 2️⃣ Comparison Operators ⚖️ Used to compare two values and return True or False. print(a > b) # True print(a == b) # False 3️⃣ Logical Operators🔍 Used to combine conditional statements. print(a > 5 and b < 5) # True print(not(a == b)) # True 4️⃣ Assignment Operators📝 Used to assign values to variables efficiently. a += 2 # a = a + 2 b *= 3 # b = b * 3 5️⃣ Membership Operators 🔠 Used to check if a value is present in a sequence. fruits = ["apple", "banana"] print("apple" in fruits) # True 6️⃣ Identity Operators🧠 Used to check if two variables point to the same memory location. x = [1, 2, 3] y = x print(x is y) # True 🚀 Why it matters: Understanding operators makes debugging faster, logic clearer, and code more readable. Even complex programs are built on these simple foundations! 💪 Keep experimenting, keep learning — Python rewards curiosity. 🧩 #Python #Programming #LearningEveryday #Developers #TechCommunity #CodeNewbie #DataScience
To view or add a comment, sign in
-
Python | Reading contents of PDF using OCR (Optical Character Recognition) the implementation: Part #1 : Converting PDF to images """ if platform.system() == "Windows": pdf_pages = convert_from_path( poppler_path=path_to_poppler_exe ) else: pdf_pages = convert_from_path(PDF_file, 500) # Read in the PDF file at 500 DPI # Iterate through all the pages stored above for page_enumeration, page in enumerate(pdf_pages, start=1): # enumerate() "counts" the pages for us. # Create a file name to store the image filename = f"{tempdir}\page_{page_enumeration:03}.jpg" # Declaring filename for each page of PDF as JPG # For each page, filename will be: # PDF page 1 -> page_001.jpg # PDF page 2 -> page_002.jpg # PDF page 3 -> page_003.jpg # .... # PDF page n -> page_00n.jpg # Save the image of the page in system page.save(filename, "JPEG") image_file_list.append(filename) """ Part #2 - Recognizing text from the images using OCR """ with open(text_file, "a") as output_file: # Open the file in append mode so that # All contents of all images are added to the same file # Iterate from 1 to total number of pages for image_file in image_file_list: # Set filename to recognize text from # Again, these files will be: # page_1.jpg # page_2.jpg # .... # page_n.jpg # Recognize the text as string in image using pytesserct text = str(((pytesseract.image_to_string(Image.open(image_file))))) # The recognized text is stored in variable text # Any string processing may be applied on text # Here, basic formatting has been done: # In many PDFs, at line ending, if a word can't # be written fully, a 'hyphen' is added. # The rest of the word is written in the next line # Eg: This is a sample text this word here GeeksF- # orGeeks is half on first line, remaining on next. # To remove this, we replace every '-\n' to ''. text = text.replace("-\n", "") # Finally, write the processed text to the file. output_file.write(text) # At the end of the with .. output_file block # the file is closed after writing all the text. # At the end of the with .. tempdir block, the # TemporaryDirectory() we're using gets removed! # End of main function! if __name__ == "__main__": # We only want to run this if it's directly executed! main() Sreekala Andrews Citizen Digital Foundation
To view or add a comment, sign in
-
I just had my first experience with Claude creating and running a python script to respond to a prompt, workout me asking if to create a script. Every once in a while I step back and reflect on how I've been using my time, what my focus has been, what I've learned, and what adjustments I want to make to my use of time and direction. This morning I was curious about how long my days have been, as I've recently been feeling the need to slow it down a smidge and tweak my balance. So I asked Claude to analyze one of my calendars and calculate this, and share its findings in a table or chart. I was surprised when I saw that it started generating a python script to help it calculate the duration between my first and last activity each day, and then create a chart visualization with the data. It makes sense, and it was a smart approach. It was just unexpected since I hadn't seen it do this before. I figured it might just do its reasoning thing, meticulously, one by one. I can't help but wonder if this is new with Claude Code getting integrated into the Claude interface, so you can vibe code with natural language (like Replit, Bolt, etc). The overall methodology of what it did seems to make sense, and my spot check of its work seemed like it was calculating durations correctly. I still need to make some refinements to the approach to include evaluating my activities across all my calendars, but the chart it produced without any guidelines from me wasn't bad as a start, either (screenshot). Have any of you seen the LLMs you're working with create scripts on its own to respond to your prompt? What was your experience with it?
To view or add a comment, sign in
-
-
🧠 Deep Dive into Strings and Lists in Python 🐍 In today’s Python class, I explored two powerful and frequently used data types — Strings and Lists, along with their types and methods! 🔹 STRINGS A String is a sequence of characters enclosed within single, double, or triple quotes. Strings are immutable, meaning their content cannot be changed once created. 📘 Example: text = "Python Programming" 👉 Types of Strings: Single-line String: "Hello World" Multi-line String: '''This is a multi-line string''' ✨ Common String Methods: upper() – Converts to uppercase lower() – Converts to lowercase title() – Capitalizes each word replace(old, new) – Replaces text find(sub) – Finds substring position split() – Splits string into list join() – Joins list into string strip() – Removes spaces 📘 Example: msg = " hello python " print(msg.strip().title()) # Hello Python 🔹 LISTS A List is an ordered, mutable collection that can hold multiple data types. Lists allow insertion, deletion, and modification of elements. 📘 Example: fruits = ["apple", "banana", "cherry"] 👉 Types of Lists: Homogeneous List: Same type of data → [1, 2, 3] Heterogeneous List: Mixed data → [1, "apple", 3.5] Nested List: List inside another list → [1, [2, 3], 4] ✨ Common List Methods: append() – Adds element at end insert(index, value) – Adds at specific position remove(value) – Removes specific element pop(index) – Removes by position sort() – Sorts the list reverse() – Reverses the list extend(iterable) – Adds multiple elements clear() – Removes all elements 📘 Example: numbers = [3, 1, 4] numbers.sort() print(numbers) # [1, 3, 4] #Python #PythonProgramming #Programming #Coding #Developer #SoftwareDevelopment #Tech #Technology Codegnan
To view or add a comment, sign in
-
-
Python dataclass vs TypedDict — When to Use? Ever wondered whether to use a dataclass or TypedDict in Python? Both improve code readability & type safety — but they serve different purposes. ⚙️ dataclass → Real-world models with behavior Use when you want structured objects (with optional methods, defaults, or immutability). from dataclasses import dataclass @dataclass class Employee: name: str salary: float emp = Employee("Alice", "70000") # No error 😮 print(emp) 👉 No runtime type validation! only provides static type hints — not enforcement. 📦 TypedDict → JSON-like structured data Use for dictionary-style objects (e.g., API responses or configs). from typing import TypedDict class EmployeeDict(TypedDict): name: str salary: float emp: EmployeeDict = {"name": "Alice", "salary": "70000"} # Still allowed 😅 Again, no runtime validation, just static type safety. ✅ If You Need Runtime Validation Use Pydantic 👇 from pydantic import BaseModel class Employee(BaseModel): name: str salary: float Now "salary": "70000" → ❌ Raises a ValidationError 🔍 TLDR dataclass: for real models & logic TypedDict: for typed JSON/dicts Pydantic: for strict validation at runtime
To view or add a comment, sign in
-
Data learners & Python warriors — gather up! 💪🐍 Today we’re breaking down 10 tuple tricks to upgrade your Python game. Ready? Let’s go 🔥🚀 10 Python Tuple Tricks Every Data Pro Should Know 🐍🚀 If you're learning Python for data analytics, AI, or automation, these tuple operations are non-negotiable skills. Let’s master them in 60 seconds ⏱️👇 tup = (1, 2, 3, 4, 2) ✅ 1. len() — Count elements len(tup) → 5 ✅ 2. count() — Count specific item tup.count(2) → 2 ✅ 3. index() — Find position tup.index(3) → 2 ✅ 4. in — Check existence 2 in tup → True ✅ 5. Loop through elements for i in tup: print(i) ✅ 6. Slicing — Extract a portion tup[1:4] → (2, 3, 4) ✅ 7. + — Join tuples tup + (5, 6) → (1, 2, 3, 4, 2, 5, 6) ✅ 8. * — Repeat tuple tup * 2 → (1, 2, 3, 4, 2, 1, 2, 3, 4, 2) ✅ 9. tuple() — Convert to tuple tuple([7, 8]) → (7, 8) ✅ 10. min() & max() — Find range min(tup) → 1 max(tup) → 4 💡 Pro Tip: Tuples are immutable — once created, they cannot be modified.
To view or add a comment, sign in
-
🧾 Project: QR Code Generator (Python) Description: The QR Code Generator is a lightweight Python application that allows users to instantly create custom QR codes from text, URLs, or any input data. It supports both command-line and GUI (Tkinter) interfaces, giving users flexibility to generate QR codes effortlessly. The tool also includes an option to embed a logo at the center of the QR code for branding or personalization. Key Features: Generate QR codes from text, links, or data. Option to add a custom logo to the QR code. Supports adjustable QR code size, border, and error correction level. Two modes: CLI version: Fast, scriptable QR generation for developers. GUI version: Simple drag-and-drop interface for non-technical users. Saves output as high-quality PNG images (optionally SVG). Built using pure Python — no external heavy dependencies. Tech Stack: Language: Python Libraries: qrcode, Pillow (PIL), tkinter, argparse, os, pathlib Use Cases: Personal or business branding (add your logo to QR). Generating QR codes for websites, portfolios, Wi-Fi credentials, or payment links. Integrating QR generation into other Python applications or automation scripts. Outcome: This project demonstrates strong fundamentals in Python scripting, GUI development, and image manipulation. It’s practical, fast to build, and shows hands-on understanding of external library usage and user interface design.
To view or add a comment, sign in
-
More from this author
Explore content categories
- Career
- Productivity
- Finance
- Soft Skills & Emotional Intelligence
- Project Management
- Education
- Technology
- Leadership
- Ecommerce
- User Experience
- Recruitment & HR
- Customer Experience
- Real Estate
- Marketing
- Sales
- Retail & Merchandising
- Science
- Supply Chain Management
- Future Of Work
- Consulting
- Writing
- Economics
- Artificial Intelligence
- Employee Experience
- Workplace Trends
- Fundraising
- Networking
- Corporate Social Responsibility
- Negotiation
- Communication
- Engineering
- Hospitality & Tourism
- Business Strategy
- Change Management
- Organizational Culture
- Design
- Innovation
- Event Planning
- Training & Development