How to work on this?¶

https://tinyurl.com/pythhonn

Copy and Work

Source of Problems: GFG, Think Python

1. Variables, Keywords, and Identifiers¶

Variables: Hold data during program execution.

Identifiers: Names for variables, functions, etc.

Keywords: Reserved words (e.g., if, for) – cannot be used as variable names.

Rules:

  1. No starting with numbers
  2. No spaces → use _
  3. Avoid special symbols: :"<>/\|()!@&%...
In [ ]:
student_name = "Anna"
student_age = 20
print(student_name, student_age)

import keyword
print(keyword.iskeyword('for'))     # True
print(keyword.iskeyword('hello'))   # False

print(keyword.kwlist)
Anna 20
True
False
['False', 'None', 'True', 'and', 'as', 'assert', 'async', 'await', 'break', 'class', 'continue', 'def', 'del', 'elif', 'else', 'except', 'finally', 'for', 'from', 'global', 'if', 'import', 'in', 'is', 'lambda', 'nonlocal', 'not', 'or', 'pass', 'raise', 'return', 'try', 'while', 'with', 'yield']

Rule of Precedence => PEMDAS

result = 4 + 3 * 2 ** 2 - (6 / 3)
print(result)
In [ ]:
result = 4 + 3 * 2 ** 2 - (6 / 3)
print(result)
14.0

Problem 1: Secret Agent Code Name Generator

You're a spy. Create a code name using:

  1. First letter of your first name
  2. Last 3 letters of your city
  3. Your age doubled

Example: Anna from Krakow, age 20 → A KOW 40 → AKOW40

Hint: .upper() => method and str() => function.

Think: Method vs Function?

In [ ]:
name = "Satyam"

city = "Krakow"

age = 23

code = name[0] + city[-3:] + str(age*2)

print(code) #So we are all kows?
Skow46

Bonus Problem: Secret Agent Name Validator

A spy agency only accepts valid Python variable names as code names.

Tasks: Take input: agent_name = input("Enter code name: ")

Check:

  1. Starts with letter or _
  2. No spaces
  3. Not a Python keyword

Print: "ACCEPTED" or "REJECTED: Invalid name"

Hint: isalpha() method of the string & kwlist of keyword module

In [ ]:
name = input("Enter Code Name: ")

check_1 = name[0].isalpha() or name[0] == "_"
check_2 = " " not in name
check_3 = not keyword.iskeyword(name)

if check_1 and check_2 and check_3:
  print("ACCEPTED")
Enter Code Name: Skow23
ACCEPTED

2. Dynamic Typing: Feature or Flaw?¶

Python allows reassigning variables to any data type => Dynamic Typing

Pros Cons
Fast prototyping Risk of type bugs
Flexible Not allowed in C/Java
In [ ]:
value = 100
print(type(value))  # <class 'int'>

value = "hundred"
print(type(value))  # <class 'str'>

value = [1, 2, 3]
print(type(value))  # <class 'list'>

#value+3 #This would give error
<class 'int'>
<class 'str'>
<class 'list'>

Problem 2: Shape Shifter

A magical creature changes form every second:

  1. Start as dragon = 3 (3 heads)
  2. Becomes dragon = "fire" (breathes fire)
  3. Becomes dragon = [10, 20, 30] (gains 3 wings)

Print its type and identity at each stage.

Then, intentionally cause a bug by adding dragon + 5 — explain the error.

In [ ]:
dragon = 3
print(type(dragon), id(dragon))

dragon = "fire"
print(type(dragon), id(dragon))

dragon = [10,20,30]
print(type(dragon), id(dragon))

#dragon+5
<class 'int'> 11654440
<class 'str'> 136018637860432
<class 'list'> 136017696766016

Bonus Problem: Time Traveler’s Log [Home]

A time machine records data in different types each jump.

Tasks:

  1. Start: log = 1364 → Year founded
  2. Jump: log = "Jagiellonian" → University name
  3. Jump: log = [50.0, 20.0] → Coordinates
  4. Final: log = {"status": "stable"}
  5. Print type and value at each jump

Then, intentionally cause a TypeError and explain.

In [ ]:
 

3. Strings¶

  • Enclosed in quotes: 'hello' or "hello"
  • Immutable → cannot change individual characters
  • Support indexing, slicing, concatenation
In [ ]:
uni = "Jagiellonian University"
print(len(uni))
print(uni[0])           # 'J'
print(uni[::2])         # every 2nd char
print(uni[-10:])        # last 10 chars
23
J
Jgelna nvriy
University

Problem 3: Palindrome Detector

Check if a word is a palindrome (reads same forward and backward). Steps:

  1. Take input word: word = "radar"
  2. Reverse it using slicing
  3. Compare with original
  4. Print "Yes!" or "No!"

Bonus: Try "Python" → should say "No!"

In [ ]:
word = "radar"
reversed_word = word[::-1]
if word == reversed_word:
  print("Yes!")
Yes!

Bonus Problem: Input a character, and find the index of that character in some string. If not found, print None

In [ ]:
string = "Hello"
character = "l"

# if character in string:
#   index = string.index(character)
#   print(index)

found = False
for i in range(len(string)):
  if string[i] == character:
    found = True
    print(i)

if not found:
  print("None")
2
3

4. Lists¶

  • Mutable sequences: [1, "a", 3.14]
  • Support indexing, slicing, append, +, *
In [ ]:
fruits = ["apple", "banana"]
fruits = fruits + ["mango"]
print(fruits * 2)
['apple', 'banana', 'mango', 'apple', 'banana', 'mango']

Problem 4: Cumulative Sum

Write a piece of code that takes a list of numbers and returns the cumulative sum; that is, a new list where the ith element is the sum of the first i + 1 elements from the original list.

For example, the cumulative sum of [1, 2, 3] is [1, 3, 6].

In [ ]:
lis = [1,2,3]

cumulative = []

for i in range(len(lis)):
  cumulative.append(sum(lis[:i+1]))

print(cumulative)
[1, 3, 6]

Bonus Problem: Nested Sum

Write a piece of code that takes a nested list of integers and add up the elements from all of the nested lists.

Ex: nested = [[1, 2], [3, 4, 5], [6]] Answer = 25

In [ ]:
nested = [[1,2],[3,4,5],[6]]

total_sum = 0
for sublist in nested:
  total_sum += __builtins__.sum(sublist)

print(total_sum)
21

Bonus Problem: Duplicacy Check

Write a piece of code that takes a list and returns True if there is any element that appears more than once. It should not modify the original list.

In [ ]:
lis = [1,2,3,4]

len(set(lis)) == len(lis)
Out[ ]:
True

5. Tuples¶

  • Immutable lists: (1, 2, 3)
  • Allow duplicates, indexing, unpacking
In [ ]:
point = (10.5, 20.3)
x, y = point
print(x, y)
10.5 20.3

Problem 5: Remove Duplicates from Tuple

Write a code to create a new tuple with only unique elements.

Original tuple with duplicates: (1, 2, 2, 3, 4, 4, 5)

Tuple with unique elements: (1, 2, 3, 4, 5)

In [ ]:
orig = (1,2,2,3,4,4,5)

unique = tuple(set(orig))

print(unique)
(1, 2, 3, 4, 5)

Bonus Problem: Historical Event Logger [Home]

Store immutable events: (year, event, location)

Tasks:

  1. events = [(1364, "Founded", "Krakow"), (1543, "Copernicus", "Frombork")]
  2. Print event with highest year
  3. Try to modify → show TypeError
In [ ]:
# Do it yourself

6. Dictionaries¶

  • Key-value pairs: {"name": "Anna", "age": 20}
  • Keys must be immutable (strings, numbers, tuples)
In [ ]:
student = {"name": "Jan", "age": 22}
student["major"] = "Physics"
student.pop("major")
Out[ ]:
'Physics'

Problem 6: Suppose you are given a string and you want to count how many times each letter appears.

In [ ]:
string = "Hello there"

char_count = {}

for char in string:
  if char in char_count:
    char_count[char] += 1
  else:
    char_count[char] = 1

print(char_count)
{'H': 1, 'e': 3, 'l': 2, 'o': 1, ' ': 1, 't': 1, 'h': 1, 'r': 1}

Bonus Problem: Student Grade Book

Track student scores:

  1. Start: grades = {"Alice": 85, "Bob": 90}
  2. Add "Charlie": 78
  3. Update "Alice" → 88
  4. Remove "Bob"
  5. Print remaining students and scores
In [ ]:
grades = {"Alice": 85, "Bob": 90}

grades["Charlie"] = 78

grades["Alice"] = 88

grades.pop("Bob")

print(grades)
{'Alice': 88, 'Charlie': 78}

Bonus Problem: Professor Availability System

Track when professors are free.

Tasks:

  1. professors = {"Dr. A": "Mon", "Dr. B": "Tue"}
  2. Dr. A is now free on "Mon & Wed"
  3. Dr. C added: "Fri"
  4. Remove Dr. B
  5. Print: "Dr. A available on: Mon & Wed"
In [ ]:
professors = {"Dr. A": "Mon", "Dr. B": "Tue"}

professors["Dr. A"] = "Mon & Wed"

professors["Dr. C"] = "Fri"

professors.pop("Dr. B")

print(f"Dr. A available on: {professors["Dr. A"]}")
Dr. A available on: Mon & Wed

7. Program Flow Control: Loops & Conditionals¶

  • if/elif/else: decision making
  • for: iterate over sequences
  • while: repeat until condition false
In [ ]:
for i in range(1, 6):
    print(i)

count = 0
while count < 3:
    print("Hello")
    count += 1
1
2
3
4
5
Hello
Hello
Hello

Problem 7: Checking Leap Year

year = 2100

Check if year is a leap year or not?

image.png

In [ ]:
year = 2100

check_leap = ((year % 4 == 0) and (year % 100 != 0)) or (year % 400 == 0)

check_leap
Out[ ]:
False

Bonus Problem: Given three numbers a, b, and c. You need to find which is the greatest of them all.

In [ ]:
a, b, c = 1,2,3

if a>b and a>c:
  print("a is biggest")
elif b>a and b>c:
  print("b is biggest")
else:
  print("c is biggest")
c is biggest

Bonus Problem: Given an integer n check if n is prime or not. A prime number is a number that is divisible by 1 and itself only.

Note: Print "True" if n is prime, otherwise print "False".

In [ ]:
n = 213

is_prime = True
for i in range(2, n):
  if n % i == 0:
    is_prime = False
    break

is_prime #Try 1 => Solve the issue
Out[ ]:
False

Bonus Problem: Given an integer n. Write a program to find the nth Fibonacci number.

F(0)= 0, F(1)=1

The nth Fibonacci number is given by the forumla F(n) = F(n-1) + F(n-2). The first few fibonacci numbers are: 0 1 1 2 3 5. . . .

In [ ]:
n = 3

a,b = 0,1
for _ in range(2, n+1):
  a,b = b,a+b

b
Out[ ]:
2

For more awesome problems: https://www.geeksforgeeks.org/python/python-conditional-statement-and-loops-coding-problems/

Key Concepts Summary¶

Topic Key Point
Variables Use _, avoid keywords
Dynamic Typing Flexible, but risky
Strings Immutable, slicing
Lists Mutable, +, append
Tuples Immutable, unpacking
Dicts Key-value, mutable
Loops for (sequences), while (condition)
if Decision making

Home Assignment (Srinivisa Ramanunjan Formula)¶

Find pi using 10 terms.

image.png

In [ ]:
import math

sum = 0

for k in range(100):
    num = math.factorial(4*k)*(1103+26390*k)
    dem = (math.factorial(k)**4)*(396**(4*k))
    sum += num/dem

pi_approx = 1 / (sum * 2*math.sqrt(2)/9801)
pi_approx
Out[ ]:
3.141592653589793
In [ ]: