0% found this document useful (0 votes)
6 views25 pages

Uff P

Python imp

Uploaded by

parkarnetraa
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
6 views25 pages

Uff P

Python imp

Uploaded by

parkarnetraa
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd

PYTHON CONTEST MASTER SHEET –

DEFINITIONS:-

1. Variable – A named location in memory to store data.

2. Data Type – Classification of data like int, float, str, etc.

3. Mutable – Values can be changed after creation (list, dict, set).

4. Immutable – Values cannot be changed after creation (int, str, tuple).

5. String – Sequence of characters in quotes.

6. List – Ordered, mutable collection.

7. Tuple – Ordered, immutable collection.

8. Dictionary – Unordered key-value pairs.

9. Set – Unordered collection of unique items.

10. Function – Reusable block of code, defined using def.

11. Indentation – Spaces at the start of a line that define code blocks.

12. Loop – Repeats code multiple times.

13. For Loop – Iterates over a sequence.

14. While Loop – Runs while condition is true.

15. Conditional Statement – Runs code if a condition is true (if, elif, else).

16. Operator – Symbol that performs an operation on values.

17. Arithmetic Operators – +, -, \*, /, %, //, \*\*.

18. Comparison Operators – ==, !=, <, >.

19. Logical Operators – and, or, not.

20. Membership Operators – in, not in.

21. Identity Operators – is, is not.

22. Indexing – Accessing elements via position number.

23. Slicing – Extracting part of a sequence (start\:end\:step).

24. Comment – Notes ignored by Python (# or ''' for multi-line).


25. Type Casting – Converting data types (int(), str()).

26. Syntax Error – Mistake in code that breaks Python rules.

27. Runtime Error – Error during execution.

28. Print Function – Displays output.

29. Input Function – Reads user input.

30. Range Function – Creates a sequence of numbers.

1. Python Basics

Case sensitive → Name ≠ name

Comments → # single line / ''' multi line '''

Variables → no need to declare type, e.g. x = 5

Keywords → if, else, for, while, def, return, True, False, None, and, or, not

2. Data Types

Type Example Mutable?

int 5 No

float 5.2 No

str "hello" No

list [1, 2, 3] Yes

tuple (1, 2, 3) No

dict {"a": 1, "b": 2} Yes

set {1, 2, 3} Yes


3. Operators

Arithmetic: + - * / // % **

Comparison: == != > < >= <=

Logical: and or not

Membership: in, not in

Identity: is, is not

4. Strings

s = "python"

s[0] # 'p'

s[-1] # 'n'

s[1:4] # 'yth'

len(s) #6

s.upper() # 'PYTHON'

s.lower() # 'python'

5. Lists

nums = [1, 2, 3]

nums.append(4) # [1, 2, 3, 4]

nums.remove(2) # [1, 3, 4]

nums[1] = 10 # [1, 10, 4]


6. Conditional Statements

if x > 0:

print("Positive")

elif x < 0:

print("Negative")

else:

print("Zero")

7. Loops

for i in range(5): #01234

print(i)

while x < 5:

print(x)

x += 1

8. Functions

def add(a, b):

return a + b

print(add(2, 3))

9. Input/Output

name = input("Enter name: ")

n = int(input("Enter number: "))


10. Common Short Programs

Reverse String → s[::-1]

Sum of List → sum(lst)

Max of List → max(lst)

Check Prime → loop till √n

Count Vowels → check in "aeiou"

11. Common Mistakes in Contests

Forgetting to convert input to int

Index errors (list index out of range)

Missing colon (:) after if, for, def

Case sensitivity errors


MCQs:-

1. Which of the following is a valid variable name?

A) 2name

B) name_2

C) name-2

D) name 2

✅ Answer: B

2. Output of:

print(type(5/2))

A) <class 'int'>

B) <class 'float'>

C) <class 'double'>

D) Error

✅ Answer: B

3. Output of:

print(3 * "Hi")

✅ Answer: HiHiHi

4. Which is not a data type in Python?

A) list

B) set

C) array

D) tuple

✅ Answer: C (array is in a module, not a built-in type)


5. Output of:

print("5" + "6")

✅ Answer: 56 (string concatenation)

6. What will bool(0) return?

✅ Answer: False

7. Output of:

print(2 ** 3 ** 2)

✅ Answer: 512 (right-to-left exponentiation)

8. Which of these is mutable?

✅ Answer: List

9. What will be printed?

x = [1, 2, 3]

x[1] = 10

print(x)

✅ Answer: [1, 10, 3]

10. Which function is used to find the largest value?

✅ Answer: max()

11. What is the index of the last element in a list of length 5?

✅ Answer: 4
12. Output of:

print("python"[1:4])

✅ Answer: yth (1 to 3)

13. Which keyword is used for a function in Python?

✅ Answer: def

14. Output of:

for i in range(2, 10, 3):

print(i, end=" ")

✅ Answer: 2 5 8

15. What will this print?

print(bool(" "))

✅ Answer: True (non-empty string is True, even if it’s just space)

16. Which function gives the length of a string?

✅ Answer: len()

17. Output of:

a=5

b=2

print(a % b)

✅ Answer: 1 (modulus)
18. What will happen?

x=5

print(x == 5 and x > 2)

✅ Answer: True

19. Which method adds an element to a list?

✅ Answer: .append()

20. Output of:

print("A" in "APPLE")

✅ Answer: True

21. Which statement is correct for comments in Python?

✅ Answer: Start with #

22. Output of:

for i in range(1, 4):

print(i * "*")

✅ Answer:

**

***

23. What will this print?

print(5 > 3 or 2 > 10)

✅ Answer: True
24. Which operator is used for floor division?

✅ Answer: //

25. Output of:

print(int("5") + 2)

✅ Answer: 7

26. Which one will cause an error?

A) len("Hi")

B) len(123)

✅ Answer: B (len() works only on sequences, not integers)

27. Output of:

x = [1, 2]

y=x

y.append(3)

print(x)

✅ Answer: [1, 2, 3] (same reference)

28. What is type( (5,) )?

✅ Answer: <class 'tuple'> (single-element tuple needs a comma)

29. Output of:

print("abc" * 0)

✅ Answer: "" (empty string)


30. Which function converts string to lowercase?

✅ Answer: .lower()

Q1. What will this code output?

print(5 // 2)

A) 2.5

B) 2

C) 3

D) 2.0

✅ Answer: B (integer division)

Q2. Which data type is ["apple", "banana"]?

A) Tuple

B) List

C) Dictionary

D) Set

✅ Answer: B

Q3. Output of:

print("python"[::-1])

A) python

B) nohtyp

C) pytho

D) Error

✅ Answer: B (string slicing reverse)

Q4. Which operator is used for exponent in Python?

A) ^
B) **

C) pow

D) ^^

✅ Answer: B

Q5. Which of these is immutable?

A) List

B) Set

C) Tuple

D) Dictionary

✅ Answer: C

Q6. What will this print?

x = 10

x += 5

print(x)

✅ Answer: 15

Q7. Which function returns the length of a list?

A) count()

B) size()

C) len()

D) length()

✅ Answer: C

Q8. Output of:

print(2 ** 3 ** 2)

✅ Answer: 512 (right-to-left exponentiation)


Q9. How do you take integer input?

✅ Answer: int(input())

Q10. Output of:

print(bool(""))

✅ Answer: False (empty string is false)

___________________________________________________________________________

IMP:-

Python Notes with Type Definitions

1. Comments

 Definition: Non-executable lines in code used for explanation or documentation.

 Types:

o Single-line comment: Starts with #. Example: # This is a comment

o Multi-line comment: Multiple # lines. Example:

o # Line 1

o # Line 2

o Docstring: Triple quotes ''' ''' or """ """. Used for documentation.
2. IDLE

 Definition: Python’s built-in Integrated Development Environment (IDE) for writing,


editing, and running Python code.

3. Variables

 Definition: Named storage locations for data.

 Properties: Dynamically typed, can change value/type, created using =.

4. Data Types

 Definition: Classification of data that tells Python what kind of value is stored.

 Types:

1. Numeric Types: Represent numbers.

 int – Whole numbers, e.g., 5, -10

 float – Decimal numbers, e.g., 3.14, -0.5

 complex – Numbers with real and imaginary parts, e.g., 2 + 3j

2. Text Type:

 str – Sequence of characters, e.g., "Hello"

3. Sequence Types: Ordered collections of items.

 list – Mutable sequence, e.g., [1, 2, 3]

 tuple – Immutable sequence, e.g., (1, 2, 3)

 range – Sequence of numbers, e.g., range(0, 5)

4. Mapping Type:

 dict – Key-value pairs, e.g., {"name":"Netra","age":20}

5. Set Types: Unordered collections with no duplicates.

 set – Mutable set, e.g., {1,2,3}

 frozenset – Immutable set, e.g., frozenset([1,2,3])

6. Boolean Type:

 bool – True or False


7. Binary Types: Represent binary data.

 bytes, bytearray, memoryview

8. None Type:

 NoneType – Represents no value, e.g., None

5. Variable Names

 Definition: Identifiers for storing values.

 Rules: Must start with letter/underscore, can contain letters/numbers/underscores,


case-sensitive, cannot be keyword.

 Assignments:

o Multiple variables: x, y = 1, 2

o One value to many: x = y = 0

o Unpacking: x, y, z = [1,2,3]

6. Numbers

 Definition: Numeric data used for calculations.

 Types: int, float, complex

 Operations: Arithmetic (+,-,*,/,//,%,**), type conversion (int(), float(), complex())

 Random: import random; random.randrange(1,10)

7. Strings

 Definition: Sequence of characters enclosed in quotes.

 Operations:

o Indexing/Slicing: s[0], s[0:3]

o Methods: .upper(), .lower(), .strip(), .replace(), .split(), .count()

o Concatenation: +
8. Booleans

 Definition: Represents truth values: True or False

 Evaluation: Most values are True; empty values, 0, None, False are False

 Operators: and, or, not

9. Sets

 Definition: Unordered, unindexed collection of unique items.

 Operations: Add/remove items with .add()/.remove(); duplicates ignored.

10. Input & Output

 Input: input() reads data as a string.

 Output: print() displays data; multiple items separated by ,.

11. Operators

 Arithmetic: +,-,*,/,//,%,**

 Comparison: ==,!=,<,>,<=,>=

 Logical: and,or,not

 Identity: is,is not

12. Conditional Statements

 if: Executes block if condition is True

 elif: Executes if previous if False and condition True

 else: Executes if all conditions False

13. Loops

 while loop: Repeats while condition True

 for loop: Iterates over sequence

 Controls: break (exit), continue (skip), pass (do nothing)


 Nested loops: Loop inside loop

 Infinite loop: Loop that never ends

14. Arrays (NumPy)

 Definition: Homogeneous collections for numerical operations

 Creation: np.array(), np.zeros(), np.ones(), np.arange(), np.linspace()

 Operations: Indexing, slicing, element-wise math, aggregation (sum, mean), alias vs


copy

15. String Functions

 Definition: Built-in methods for string manipulation

 Examples:

o .lower(), .upper(), .strip(), .replace(), .split(), .count()

o Checks: .isalpha(), .isdigit(), .isspace(), .startswith(), .endswith()

o Formatting: .capitalize(), .swapcase()

o Access: Indexing s[0], slicing s[0:3]


Python String Methods – Quick Reference

Method /
Use / Meaning Example
Operation

Convert all letters to


.lower() "Hello".lower() → "hello"
lowercase

Convert all letters to


.upper() "Hello".upper() → "HELLO"
uppercase

Remove leading & trailing


.strip() " Hi ".strip() → "Hi"
spaces

Replace a substring with "Hi There".replace("Hi","Hello") → "Hello


.replace(old,new)
another There"

Split string into list by


.split(separator) "a,b,c".split(",") → ['a','b','c']
separator

Count occurrences of
.count(substring) "Hello".count("l") → 2
substring

Checks (Return True/False):

Method Meaning Example

.isalpha() All letters "Hi".isalpha() → True

.isdigit() All digits "123".isdigit() → True

.isspace() All whitespace " ".isspace() → True

.startswith(sub) Starts with substring "Hello".startswith("He") → True

.endswith(sub) Ends with substring "Hello".endswith("lo") → True

Formatting:

Method Use Example

.capitalize() First letter uppercase, rest lowercase "hello".capitalize() → "Hello"

.swapcase() Swap uppercase ↔ lowercase "HeLLo".swapcase() → "hEllO"


Access:

Operation Use Example

Indexing Get single character by position "Hello"[0] → 'H'

Slicing Get substring "Hello"[0:3] → 'Hel'


Type Definition Example Key Methods / Notes

int Whole numbers 10, -5 Arithmetic ops: +,-,*,//,%,**

Decimal Arithmetic ops, type conversion:


float 3.14, -0.5
numbers float()

Numbers with Access real: .real, imaginary:


complex 2+3j
real + imaginary .imag

.lower(), .upper(), .strip(),


.replace(), .split(), .count(),
Sequence of .capitalize(), .swapcase(),
str "Hello"
characters .isalpha(), .isdigit(), .isspace(),
.startswith(), .endswith(),
indexing/slicing

Ordered,
Append: .append(), remove:
list mutable [1,2,3]
.remove(), slice, iterate
collection

Ordered,
tuple immutable (1,2,3) Indexing, slicing, iterate
collection

Sequence of
range range(0,5) → 0,1,2,3,4 Used in loops, can convert to list
numbers

Access: dict[key], .keys(),


dict Key-value pairs {"name":"Netra","age":20}
.values(), .items()

Unordered, Add: .add(), remove: .remove(),


set {1,2,3}
unique items no duplicates

frozenset Immutable set frozenset([1,2,3]) Cannot add/remove

bool True or False True, False Used in conditions, comparisons

Immutable Index, slice; often for


bytes b"hello"
binary data files/network

Mutable binary
bytearray bytearray(b"hi") Like bytes but mutable
data
Type Definition Example Key Methods / Notes

Access memory
memoryview of binary data memoryview(b"hi") Advanced, for efficiency
without copying

Represents no Often used as placeholder or


NoneType None
value default

🎤 Python Practicals Viva Q&A (1–13)

Practical 1 – Grade Program (If-Else, Validation)

Q1. What is the difference between if, elif, and else?


A: if checks first condition, elif checks more conditions, else runs if none match.

Q2. Why do we use while True with break here?


A: To keep asking input until valid score is entered.

Q3. What happens if the user enters a negative score?


A: Program prints “Invalid score” and asks again.

Q4. Difference between try-except and if-else?


A: try-except handles errors, if-else handles conditions.

Practical 2 – Loops & Control Statements

Q1. Difference between break and continue?


A: break exits loop, continue skips current iteration.

Q2. What is the output of countdown from 5?


A: 5, 4, 3, 2, 1

Q3. Why do we use i += 2 in even number loop?


A: To increase by 2 and print only even numbers.

Q4. What is the purpose of pass?


A: It does nothing, used as a placeholder.

Practical 3 – NumPy Arrays


Q1. What is NumPy used for?
A: For fast mathematical operations on arrays.

Q2. Difference between shape, size, and ndim?


A: Shape = rows×columns, Size = total elements, ndim = dimensions.

Q3. How to access all English scores?


A: scores[:, 1]

Q4. What is aliasing in NumPy?


A: When two variables point to same array, changes affect both.

Q5. What is broadcasting?


A: Performing operation on whole array at once (like adding 5 to column).

Q6. What will scores[scores > 85] return?


A: All elements greater than 85.

Practical 4 – String Operations

Q1. Are strings mutable or immutable?


A: Immutable (cannot be changed).

Q2. How do you count words in a string?


A: Using len(sentence.split()).

Q3. What is the difference between + and join()?


A: + concatenates strings, join() joins from a list/iterable.

Q4. What does len() return for a string?


A: Total characters including spaces.

Practical 5 – Tuples (Basics)

Q1. What is a tuple?


A: An immutable ordered collection inside ().

Q2. How do you access the last element of a tuple?


A: Using index [-1].

Q3. Difference between list and tuple?


A: List is mutable, tuple is immutable.

Q4. Can you change elements of a tuple directly?


A: No, because tuples are immutable.
Practical 6 – Tuples (Modification)

Q1. Why convert tuple to list for modification?


A: Because lists are mutable.

Q2. How to add new element to tuple?


A: Convert to list → append → convert back to tuple.

Q3. What happens if you try colors[1] = "yellow"?


A: Error: tuples don’t support item assignment.

Practical 7 – Dictionaries (Basics)

Q1. What is a dictionary?


A: Collection of key-value pairs inside {}.

Q2. How to access all keys?


A: Using dict.keys().

Q3. How to check if key exists?


A: Using in operator.

Q4. Difference between del and pop()?


A: del deletes by key, pop() deletes and returns value.

Practical 8 – Dictionary Operations

Q1. Difference between get() and dict[key]?


A: get() returns None if key missing, dict[key] gives error.

Q2. How to update value in dictionary?


A: Using update() or direct assignment.

Q3. What does car.update({"year": 2024}) do?


A: Changes year to 2024.

Q4. How do you remove a key safely?


A: Using pop().

Practical 9 – File Handling

Q1. File modes in Python?


A: "r" read, "w" write, "a" append, "rb" read binary, "wb" write binary.
Q2. What does seek(0) do?
A: Moves pointer to start of file.

Q3. What does tell() return?


A: Current position of file pointer.

Q4. Difference between text file and binary file?


A: Text stores human-readable, binary stores raw data.

Q5. Why use with open()?


A: It closes file automatically.

Practical 10 – Pickle & Zip

Q1. What is pickling?


A: Converting Python object into binary format.

Q2. Which module is used for pickling?


A: pickle

Q3. Why use wb and rb in pickle?


A: To write/read in binary mode.

Q4. What is the use of zipfile module?


A: To compress and extract files.

Q5. Can we pickle any object?


A: Yes, almost any Python object (lists, dicts, etc.).

Practical 11 – Regular Expressions

Q1. What is a regex?


A: A pattern used for matching strings.

Q2. What does \d{10} mean?


A: Exactly 10 digits.

Q3. Difference between findall() and search()?


A: findall() returns all matches, search() returns first match.

Q4. How to replace digits with X?


A: re.sub(r"\d", "X", text)

Practical 12 – Date & Time


Q1. Which module is used for date and time?
A: datetime

Q2. Difference between datetime.now() and date.today()?


A: now() gives full date-time, today() gives only date.

Q3. What does strftime("%d-%m-%Y") return?


A: Date in Day-Month-Year format.

Q4. How to compare two dates?


A: Using <, >, or == operators.

Practical 13 – Time & Calendar

Q1. Which module measures execution time?


A: time

Q2. What does time.time() return?


A: Current time in seconds since epoch.

Q3. How to print a full calendar of 2025?


A: calendar.calendar(2025)

Q4. How to check weekday of 15-08-2025?


A: strftime("%A")

Q5. Default first weekday in calendar module?


A: Monday.

You might also like