Book a Demo!
CoCalc Logo Icon
StoreFeaturesDocsShareSupportNewsAboutPoliciesSign UpSign In
suyashi29
GitHub Repository: suyashi29/python-su
Path: blob/master/Python Essentials/Python_basics 3.ipynb
3603 views
Kernel: Python 3 (ipykernel)

Python Basics -

In this notebook, we will continue learning Python fundamentals: conditions, loops, functions, and lists.

Conditional Statements

Python uses if, elif, and else to make decisions based on conditions.

9+8 print(9+8)
#only if age = int(input("Enter your age:")) if age >= 18: print("You are eligible to vote.")
# Example: ifelse marks=int(input("Enter your marks")) if marks >= 50: print("You passed the exam.") else: print("You failed the exam.")
#if-elif-else temperature = 32 if temperature > 35: print("It's very hot outside.") elif temperature >= 20: print("Weather is pleasant.") else: print("It's cold outside.")
#Nested If age=int(input("Enter your age:")) citizen = True if age >= 18: if citizen: print("You are eligible to vote.") else: print("You must be a citizen to vote.") else: print("You are too young to vote.")

Case Study: Online Shopping Discount System

Scenario: An e-commerce platform wants to apply discounts based on the customer’s cart value and membership status.

Rules:

  • If the cart value is above ₹5000:

  • If the customer is a Premium Member, apply 20% discount.

  • If the customer is a Regular Member, apply 10% discount.

  • If the cart value is between ₹2000 and ₹5000, apply 5% discount for everyone.

  • Otherwise, no discount.

# Online Shopping Discount System print("Welcome to the E-Commerce Discount Calculator!\n") # Get user input try: cart_value = float(input("Enter your cart value (in ₹): ")) membership = input("Enter your membership type (Premium/Regular/None): ").strip().lower() discount = 0 # Apply discount rules if cart_value > 5000: if membership == "premium": discount = 0.20 elif membership == "regular": discount = 0.10 else: discount = 0 elif 2000 <= cart_value <= 5000: discount = 0.05 else: discount = 0 # Calculate final price discount_amount = cart_value * discount final_price = cart_value - discount_amount # Display results print("\n--- Discount Summary ---") print(f"Original Cart Value: ₹{cart_value:.2f}") print(f"Discount Applied: ₹{discount_amount:.2f}") print(f"Final Price to Pay: ₹{final_price:.2f}") except ValueError: print("end")
cart_value = int(input("Enter the Cart value:")) membership = "Premium" # Options: "Premium" or "Regular" if cart_value > 5000: if membership == "Premium": discount = 0.20 * cart_value print("Premium member discount applied: ₹", discount) else: discount = 0.10 * cart_value print("Regular member discount applied: ₹", discount) elif cart_value >= 2000: discount = 0.05 * cart_value print("5% discount applied: ₹", discount) else: discount = 0 print("No discount available.") print("Final Price: ₹", cart_value - discount)

Loops

Python has two main types of loops:

  • for loop (used to iterate over a sequence)

  • while loop (used to repeat as long as a condition is true)

# Example: While loop count = 0 while count < 5: print("Count:", count) count += 1
a=list(range(20,10,-2)) a
# Example: For loop for i in range(5): print("Iteration:", i)
## Iteraing through a list fruits = ["apple", "banana", "cherry"] for fruit in fruits: name=input("Enter your name: ")
## Using Range function for i in range(5): print("Number:", i)
## Looping through Strings word = "Python" for letter in word: print(letter)
##Nested for loop for i in range(1, 4): for j in range(1, 4): print(f"{i} x {j} = {i*j}")
##Using for with if (conditional inside loop) numbers = [1, 5, 10, 12, 15] for num in numbers: if num % 2 == 0: print(num, "is even") else: print(num, "is odd")

Expanded & Interactive Case Study: Online Shopping Discount System

Scenario:

  • An e-commerce platform applies discounts based on cart value, membership, and promo codes.

  • Users can also buy multiple items, and the program calculates the total price per item and overall bill summary.

# Sample item catalog items = { "Laptop": 45000, "Headphones": 1500, "Mouse": 800, "Keyboard": 1200, "Smartphone": 25000 } # User inputs membership = input("Enter membership type (Premium/Regular): ") cart = {} # item_name: quantity print("\nAvailable items:") for item, price in items.items(): print(f"{item}: ₹{price}") # Let user choose multiple items while True: chosen_item = input("\nEnter item name to add to cart (or 'done' to finish): ") if chosen_item.lower() == "done": break if chosen_item in items: quantity = int(input(f"Enter quantity for {chosen_item}: ")) cart[chosen_item] = quantity else: print("Item not available!") # Calculate total total = 0 print("\nCart Summary:") for item, quantity in cart.items(): item_total = items[item] * quantity print(f"{item} x {quantity} = ₹{item_total}") total += item_total # Apply discount rules if total > 5000: if membership.lower() == "premium": discount = 0.20 * total print("\nPremium member discount applied: ₹", discount) else: discount = 0.10 * total print("\nRegular member discount applied: ₹", discount) elif total >= 2000: discount = 0.05 * total print("\n5% discount applied: ₹", discount) else: discount = 0 print("\nNo discount available.") final_price = total - discount print("\nTotal Bill: ₹", total) print("Discount: ₹", discount) print("Amount to Pay: ₹", final_price)
## USER INPOUT lists # Create an empty list user_list = [] # Ask how many items the user wants to add n = int(input("How many items do you want to add to the list? ")) # Loop to take input for i in range(n): item = input(f"Enter item {i+1}: ") user_list.append(item) print("Your list:", user_list)
d={"A":1,"B": 2} d["C"]=7
## User Input dictionary # Create an empty dictionary user_dict = {} # Ask how many key-value pairs n = int(input("\nHow many key-value pairs do you want to add? ")) # Loop to take input for i in range(n): key = input(f"Enter key {i+1}: ") value = input(f"Enter value for '{key}': ") user_dict[key] = value print("Your dictionary:", user_dict)

Functions

Functions are reusable blocks of code defined using the def keyword.

1. Functions Without Variables

These functions don’t take any input and may or may not return something.

# Example 1: Simple function with no input and no output def greet(): print("Hello, welcome to Python!") greet() # Output: Hello, welcome to Python! # Example 2: Function with no input but returns a value def get_pi(): return 3.14159 print(get_pi()) # Output: 3.14159
Hello, welcome to Python! 3.14159

2. Functions With Variables (Parameters)

These allow reusability by passing arguments.

# Example 1: Function with one variable def square(num): return num ** 2 square(12)
144
# Example 2: Function with multiple variables def EUI(a, b): return 2*a + b print(EUI(3, 7)) print(EUI(13, 27))
13 53

3. Functions With Default Parameters

Parameters can have default values.

def greet(name="Guest"): print(f"Hello, {name}!") greet() greet("Suyashi")
Hello, Guest! Hello, Suyashi!
greet("Aman")
Hello, Aman!

4. Functions With Variable-Length Arguments

When the number of arguments is not fixed.

# *args (positional arguments) def add_all(*numbers): return sum(numbers) print(add_all(2, 3, 5, 7,8,9,80))
114
# **kwargs (keyword arguments) def show_info(**details): for key, value in details.items(): print(f"{key}: {value}") show_info(name="Riya", age=25, city="Delhi")
name: Riya age: 25 city: Delhi

5. Lambda (Anonymous) Functions

Small, one-line functions.

# With Single Variable power_4 = lambda x:x**4 power_4(8)
4096
# With three variable s equi = lambda x,y,z:(2**x+3*y+z) equi(2,2,3)
13
# Without variables hello = lambda: "Hello World" print(hello())

Case Study: Simple Student Grading System

Create different functions to handle student grades System

Interactive Extension

  • Createa Grading Interface

  • Add all subject marks

  • Take avaearge of it

  • Classify learners as Excellent, Good, Average , Poor

  • Print their score sheet

# Function without variables def welcome(): print("Welcome to Student Grading System") # Function with variables def calculate_percentage(marks_obtained, total_marks): return (marks_obtained / total_marks) * 100 # Function with default parameter def assign_grade(percentage, pass_mark=40): if percentage >= 90: return "A+" elif percentage >= 75: return "A" elif percentage >= 60: return "B" elif percentage >= pass_mark: return "C" else: return "Fail" # Function with *args def average_marks(*marks): return sum(marks) / len(marks) # Lambda function status = lambda grade: "Pass" if grade != "Fail" else "Fail" # -------------------- # Running the case study welcome() avg = average_marks(78, 85, 69, 92) percentage = calculate_percentage(avg, 100) grade = assign_grade(percentage) print(f"Average Marks: {avg}") print(f"Percentage: {percentage:.2f}%") print(f"Grade: {grade}") print(f"Status: {status(grade)}")

Hands-on Quick Practice

Try solving the following problems:

  1. Write a program that checks whether a number entered by the user is even or odd.

  2. Use a loop to print the first 10 natural numbers.

  3. Write a function that takes two numbers and returns their sum.

  4. Write a Python program to take n items from the user and store them in a list. Then Print the list Print the number of items that start with the letter 'a'

  5. Write a Python program to create a dictionary from user input. The user should enter n key-value pairs, where the value is an integer. Then:

    • Print the dictionary

    • Print the sum of all values in the dictionar

# Write your practice code here