Summary of Python Syntax
input()
and print()
, Type Conversion, len()
, in
, not in
, Ternary Operator, and
, or
, not
# Simple Interactive Python Program Demonstrating Various Concepts
# 1. Taking string input and printing output
name = input("Enter your name: ")
print("Hello,", name, "! Welcome to the demo program.")
print("The number {} is written as {}".format(number, string))
# 2. Taking integer input (type conversion) and printing
age = int(input("Enter your age: "))
print("You entered age as:", age)
# 3. Counting characters in a string using len()
word = input("Enter a word, and I'll tell you its length: ")
length = len(word)
print(f"The word '{word}' has {length} characters.")
# 4. Membership operators: check if a number is in a predefined list
# (Note: we’ll define a simple list of “favorite numbers”)
favorite_numbers = [3, 7, 21, 42]
num_to_check = int(input(f"Enter a number to see if it's in my favorites {favorite_numbers}: "))
if num_to_check in favorite_numbers:
print(f"{num_to_check} is one of my favorite numbers!")
else:
print(f"{num_to_check} is not in my favorites list.")
# 5. Ternary operator: compare two numbers to find the smaller one
a = int(input("Enter the first number (a): "))
b = int(input("Enter the second number (b): "))
min_val = a if a < b else b
print(f"The smaller of {a} and {b} is {min_val} (determined by a ternary operator).")
# 6. Logical operators: check if age is within a certain range
# (e.g., between 13 and 19 inclusive, meaning “teenager”)
is_teen = (age >= 13) and (age <= 19)
print(f"Is {name} a teenager (age 13–19)? {is_teen}")
# 7. Operator precedence example
# We’ll compute an expression: 5 + 2 * 3 == 11?
# Multiplication happens before addition
expr_result = 5 + 2 * 3 # 2 * 3 = 6, then 5 + 6 = 11
is_eleven = True if expr_result == 11 else False
print(f"Expression 5 + 2 * 3 evaluates to {expr_result}. Is it 11? {is_eleven}")
# 8. Combined logic with or / and
# Check if the user’s name is “Alice” or “Bob”, and age is at least 18
if (name == "Alice" or name == "Bob") and age >= 18:
print("You’re a named user (Alice/Bob) and you’re an adult (18+).")
else:
print("Either you’re not Alice/Bob, or you’re under 18 (or both).")
# 9. Demonstrating 'not in' membership operator
char_to_check = input("Enter a single character to check if it does NOT appear in your word: ")
if char_to_check not in word:
print(f"The character '{char_to_check}' is NOT in the word '{word}'.")
else:
print(f"The character '{char_to_check}' is in the word '{word}'.")
Loop, string concatention
# A Simple Python Program Demonstrating if-elif-else, while, for loops, and string-int concatenation
# 1. Prompt the user for an integer and use if-elif-else to categorize it
user_input = input("Enter an integer (can be positive, zero, or negative): ")
# First, check that the input is an integer string
if not user_input.lstrip('-').isdigit():
print("Error: You did not enter a valid integer.")
else:
x = int(user_input)
# if-elif-else block
if x > 0:
print("You entered a positive integer.")
elif x == 0:
print("You entered zero.")
else:
print("You entered a negative integer.")
# 2. Use a while loop to count down if x > 0
if x > 0:
print("\nCounting down with a while loop:")
count = x
while count > 0:
# String concatenation: combining a string and an int converted to string
print("Counting: " + str(count))
count -= 1
print("Blast off!\n")
else:
print("\nSkipping the countdown since you didn't enter a positive integer.\n")
# 3. Use a for loop to iterate a certain number of times
# Ask the user how many iterations they want
n = int(input("Now enter a non-negative integer for how many iterations the for-loop should run: "))
if n < 0:
print("Negative iteration count isn’t allowed. Exiting for-loop section.")
else:
print("\nRunning a for-loop for", n, "iterations:")
for i in range(n):
# Demonstrate string concatenation with int inside the loop
print("Iteration #" + str(i + 1) + " of " + str(n))
# 4. Demonstrate string concatenation with int one more time
# Sum the numbers from 1 to n (if n >= 1), then print the result
if n >= 1:
total = 0
for i in range(1, n + 1):
total += i
# Using an f-string instead of concatenation for variety
print(f"\nThe sum of integers from 1 to {n} is {total}.")
else:
print("\nNo sum to compute since iteration count was less than 1.")
Exception
# ### Easy Exception Handling Keywords Demo ###
# 1. try, except, finally
print("--- 1. Demo: try, except, finally ---")
try:
# Code that MIGHT cause an error
print("Trying to divide 10 by 0...")
result = 10 / 0
print(f"Result: {result}") # This line won't run
except ZeroDivisionError:
# Code that runs IF a ZeroDivisionError happens
print("Oops! You can't divide by zero. That's a ZeroDivisionError.")
finally:
# Code that ALWAYS runs, error or not
print("The 'finally' part always runs, no matter what.")
print("-" * 30) # Separator
# 2. assert
print("\n--- 2. Demo: assert ---")
print("Assert checks if something is True. If False, it raises an AssertionError.")
age = 10
try:
assert age >= 18, "You must be 18 or older." # This will fail
print("Assertion passed: Age is valid.") # This won't run
except AssertionError as e:
print(f"Assertion failed: {e}")
temperature = 25 # degrees Celsius
assert temperature < 100, "Temperature is too high for water to be liquid (at sea level)!"
print("Assertion passed: Temperature (25 C) is less than 100 C.")
print("-" * 30)
# 3. raise
print("\n--- 3. Demo: raise ---")
print("Raise lets you create your own error.")
def check_username(name):
if len(name) < 3:
# Manually create (raise) a ValueError
raise ValueError("Username is too short! Must be at least 3 characters.")
print(f"Username '{name}' is good!")
try:
check_username("Al") # This will cause an error
except ValueError as e:
print(f"Error checking username: {e}")
try:
check_username("Alice") # This will be fine
except ValueError as e:
print(f"Error checking username: {e}") # This won't run
print("\n### Easy Demo Finished! ###")
Def, String List Tuple Set Dictionary Data Type, str
# ==========================================
# 1. FUNCTION DEFINITION WITH 'def' KEYWORD
# ==========================================
def welcome_message():
"""Function to display welcome message"""
print("Welcome to Python Concepts Demo!")
print("=" * 40)
def demonstrate_concept(concept_name):
"""Function to print section headers"""
print(f"\n--- {concept_name} ---")
# ==========================================
# 2. STRING DATA TYPE
# ==========================================
def string_operations():
"""Demonstrate string operations and indexing"""
demonstrate_concept("STRING OPERATIONS")
# Creating strings
s = 'Welcome to the Geeks World'
print(f"String: {s}")
print(f"Type: {type(s)}")
# String indexing
print(f"First character s[0]: {s[0]}")
print(f"Second character s[1]: {s[1]}")
print(f"Third character s[2]: {s[2]}")
print(f"Last character s[-1]: {s[-1]}")
# String slicing
print(f"First 7 characters: {s[:7]}")
print(f"Last 5 characters: {s[-5:]}")
# ==========================================
# 3. LIST DATA TYPE
# ==========================================
def list_operations():
"""Demonstrate list operations"""
demonstrate_concept("LIST OPERATIONS")
# Creating lists
empty_list = []
print(f"Empty list: {empty_list}")
int_list = [1, 2, 3, 4, 5]
print(f"Integer list: {int_list}")
mixed_list = ["Geeks", "For", "Geeks", 4, 5]
print(f"Mixed list: {mixed_list}")
# Accessing elements
print(f"First element: {mixed_list[0]}")
print(f"Last element: {mixed_list[-1]}")
# Basic list operations (from Q1)
fruits = ["apple", "banana", "orange"]
print(f"Original fruits: {fruits}")
fruits.append("grape")
print(f"After adding grape: {fruits}")
fruits.remove("orange")
print(f"After removing orange: {fruits}")
# ==========================================
# 4. TUPLE DATA TYPE
# ==========================================
def tuple_operations():
"""Demonstrate tuple operations"""
demonstrate_concept("TUPLE OPERATIONS")
# Creating tuples
empty_tuple = ()
print(f"Empty tuple: {empty_tuple}")
string_tuple = ('Geeks', 'For')
print(f"String tuple: {string_tuple}")
# Creating tuple from list
number_tuple = tuple([1, 2, 3, 4, 5])
print(f"Number tuple: {number_tuple}")
# Accessing elements
print(f"First element: {number_tuple[0]}")
print(f"Last element: {number_tuple[-1]}")
print(f"Third from end: {number_tuple[-3]}")
# Coordinate example
coordinates = (3, 5)
print(f"Coordinates: {coordinates}")
print(f"X-coordinate: {coordinates[0]}")
print(f"Y-coordinate: {coordinates[1]}")
# ==========================================
# 5. SET DATA TYPE
# ==========================================
def set_operations():
"""Demonstrate set operations"""
demonstrate_concept("SET OPERATIONS")
# Creating sets
empty_set = set()
print(f"Empty set: {empty_set}")
string_set = set("GeeksForGeeks")
print(f"Set from string: {string_set}")
list_set = set(["Geeks", "For", "Geeks"])
print(f"Set from list: {list_set}")
# Accessing elements (looping)
print("Looping through set:")
for item in list_set:
print(f" {item}")
# Checking membership
print(f"'Geeks' in set: {'Geeks' in list_set}")
print(f"'Python' in set: {'Python' in list_set}")
# ==========================================
# 6. DICTIONARY DATA TYPE
# ==========================================
def dictionary_operations():
"""Demonstrate dictionary operations"""
demonstrate_concept("DICTIONARY OPERATIONS")
# Creating dictionaries
empty_dict = {}
print(f"Empty dictionary: {empty_dict}")
number_dict = {1: 'Geeks', 2: 'For', 3: 'Geeks'}
print(f"Number dictionary: {number_dict}")
# Using dict() constructor
constructor_dict = dict({1: 'Geeks', 2: 'For', 3: 'Geeks'})
print(f"Dict constructor: {constructor_dict}")
# Mixed key types
mixed_dict = {1: 'Geeks', 'name': 'For', 3: 'Geeks'}
# Accessing elements
print(f"Using key 'name': {mixed_dict['name']}")
print(f"Using get(3): {mixed_dict.get(3)}")
print(f"Using get('unknown'): {mixed_dict.get('unknown')}")
# ==========================================
# 7. CLASS WITH __str__ METHOD
# ==========================================
class StudentRecord:
"""Class to demonstrate __str__ method"""
def __init__(self, name, age, grade):
self.name = name
self.age = age
self.grade = grade
def __str__(self):
return f"Student: {self.name}, Age: {self.age}, Grade: {self.grade}"
class GeeksClass:
"""Another example class with __str__ method"""
def __init__(self, value):
self.value = value
def __str__(self):
return f"GeeksClass object with value: {self.value}"
def class_operations():
"""Demonstrate classes with __str__ method"""
demonstrate_concept("CLASSES WITH __str__ METHOD")
# Creating objects
student = StudentRecord("Alice", 20, "A")
print(f"Student object: {student}")
geeks_obj = GeeksClass(42)
print(f"GeeksClass object: {geeks_obj}")
# Using str() function
student_str = str(student)
print(f"Using str(): {student_str}")
# ==========================================
# 8. LIST COMPREHENSIONS (Arrays)
# ==========================================
def list_comprehension_examples():
"""Demonstrate list comprehensions"""
demonstrate_concept("LIST COMPREHENSIONS")
# Basic list comprehension
squares = [x**2 for x in range(1, 6)]
print(f"Squares: {squares}")
# List comprehension with condition (even numbers * 2)
even_doubled = [x * 2 for x in range(0, 21) if x % 2 == 0]
print(f"Even numbers doubled: {even_doubled}")
# String manipulation
words = ["hello", "world", "python", "geeks"]
uppercased = [word.upper() for word in words]
print(f"Uppercased words: {uppercased}")
# Filtering with condition
long_words = [word for word in words if len(word) > 4]
print(f"Words longer than 4 chars: {long_words}")
# Nested comprehension
matrix = [[i*j for j in range(1, 4)] for i in range(1, 4)]
print(f"3x3 multiplication matrix: {matrix}")
# ==========================================
# 9. MAIN PROGRAM EXECUTION
# ==========================================
def main():
"""Main function to run all demonstrations"""
welcome_message()
# Execute all concept demonstrations
string_operations()
list_operations()
tuple_operations()
set_operations()
dictionary_operations()
class_operations()
list_comprehension_examples()
print("\n" + "=" * 40)
print("Demo completed! All Python concepts covered.")
# ==========================================
# PROGRAM ENTRY POINT
# ==========================================
if __name__ == "__main__":
main()
Generic Types
Example(s):
from typing import TypeVar
T = TypeVar('T')
E = TypeVar('E')
def all_variations(l:list[T]) -> list[list[T]]:
assert l is not None
if len(l) <= 1:
return [l]
else:
return [[e] + rest for e in l for rest in all_variations([x for x in l if x is not e])]
def zip_lists_buggy(l_1: list[T], l_2: list[E]) -> list[(T, E)]:
assert l_1 is not None
assert l_2 is not None
assert len(l_1) == len(l_2)
return [(t, e) for t in l_1 for e in l_2]
def zip_lists(l_1: list[T], l_2: list[E]) -> list[(T, E)]:
assert l_1 is not None
assert l_2 is not None
assert len(l_1) == len(l_2)
return [(l_1[i], l_2[i]) for i in range(len(l_1))]
def main() -> None:
print(str(all_variations([1, 2, 3])))
numbers: list[int] = [1, 2, 3]
words: list[str] = ["One", "Two", "Three"]
zipped_lists_buggy: list[(int, str)] = zip_lists_buggy(numbers, words)
zipped_lists: list[(int, str)] = zip_lists(numbers, words)
print(zipped_lists)
print(zipped_lists_buggy)
if __name__ == "__main__":
main()
Python in
Keyword (Detailed Section)
s = "Geeks for geeks"
if "for" in s: # Checks if the substring "for" is in string s
print("found")
else:
print("not found")
a = ["php", "python", "java"]
if "php" in a:
print(True)
s = "GeeksforGeeks"
for char in s: # 'char' takes each character from 's' in turn
if char == 'f':
break # Stops the loop
print(char)
d = {"Alice": 90, "Bob": 85}
if "Alice" in d: # Checks if "Alice" is a key in dictionary d
print("Alice's marks are:", d["Alice"])
v = {'a', 'e', 'i', 'o', 'u'}
print('e' in v) # Checks if 'e' is an element in set v