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:
- No starting with numbers
- No spaces → use
_ - Avoid special symbols: :
"<>/\|()!@&%...
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)
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:
- First letter of your first name
- Last 3 letters of your city
- Your age doubled
Example: Anna from Krakow, age 20 → A KOW 40 → AKOW40
Hint: .upper() => method and str() => function.
Think: Method vs Function?
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:
- Starts with letter or _
- No spaces
- Not a Python keyword
Print: "ACCEPTED" or "REJECTED: Invalid name"
Hint: isalpha() method of the string & kwlist of keyword module
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 |
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:
- Start as dragon = 3 (3 heads)
- Becomes dragon = "fire" (breathes fire)
- 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.
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:
- Start: log = 1364 → Year founded
- Jump: log = "Jagiellonian" → University name
- Jump: log = [50.0, 20.0] → Coordinates
- Final: log = {"status": "stable"}
- Print type and value at each jump
Then, intentionally cause a TypeError and explain.
3. Strings¶
- Enclosed in quotes: 'hello' or "hello"
- Immutable → cannot change individual characters
- Support indexing, slicing, concatenation
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:
- Take input word: word = "radar"
- Reverse it using slicing
- Compare with original
- Print "Yes!" or "No!"
Bonus: Try "Python" → should say "No!"
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
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, +, *
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].
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
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.
lis = [1,2,3,4]
len(set(lis)) == len(lis)
True
5. Tuples¶
- Immutable lists:
(1, 2, 3) - Allow duplicates, indexing, unpacking
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)
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:
- events = [(1364, "Founded", "Krakow"), (1543, "Copernicus", "Frombork")]
- Print event with highest year
- Try to modify → show TypeError
# Do it yourself
6. Dictionaries¶
- Key-value pairs:
{"name": "Anna", "age": 20} - Keys must be immutable
(strings, numbers, tuples)
student = {"name": "Jan", "age": 22}
student["major"] = "Physics"
student.pop("major")
'Physics'
Problem 6: Suppose you are given a string and you want to count how many times each letter appears.
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:
- Start: grades = {"Alice": 85, "Bob": 90}
- Add "Charlie": 78
- Update "Alice" → 88
- Remove "Bob"
- Print remaining students and scores
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:
- professors = {"Dr. A": "Mon", "Dr. B": "Tue"}
- Dr. A is now free on "Mon & Wed"
- Dr. C added: "Fri"
- Remove Dr. B
- Print: "Dr. A available on: Mon & Wed"
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
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?
year = 2100
check_leap = ((year % 4 == 0) and (year % 100 != 0)) or (year % 400 == 0)
check_leap
False
Bonus Problem: Given three numbers a, b, and c. You need to find which is the greatest of them all.
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".
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
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. . . .
n = 3
a,b = 0,1
for _ in range(2, n+1):
a,b = b,a+b
b
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 |
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
3.141592653589793