Python Unit I - Question Bank

Python Basics: Easy Tutorial for Beginners

A simple, step-by-step guide to understanding Python programming fundamentals.

UNIT I (4 Marks Questions)

1. What is a variable? Write about types of variables.

Answer:

A variable is like a labeled storage box in your computer's memory. You use it to store data (like a player's score or a user's name) so you can use it later in your program. In Python, you don't have to tell the computer what type of data is going into the box; it figures it out automatically.

# We are creating two variables here
score = 100      
player_name = "John"  
        

Types of Variables:

  • Local Variables: These are created inside a specific block of code (like a function). They can only be used inside that specific block.
  • Global Variables: These are created outside of all functions at the top of your code. They can be seen and used anywhere in your entire program.

2. What are Keywords in Python?

Answer:

Keywords are reserved words that Python already uses for its own instructions. Because Python needs these words to understand how to run your program, you are not allowed to use them as names for your own variables.

There are about 35 keywords in Python. Here are some common examples:

  • For making decisions: if, else, elif
  • For creating loops: for, while
  • For True/False values: True, False

3. What is type conversion?

Answer:

Type conversion (also called Type Casting) means changing data from one format into another format. For example, changing a text version of a number into a real math number. There are two ways this happens:

  • Implicit Type Conversion: Python does this automatically. If you add a whole number and a decimal, Python automatically turns the final answer into a decimal so you don't lose any information.
  • Explicit Type Conversion: This is when the programmer forces the data to change using built-in commands like int() for integers or str() for text.
# Explicit Conversion Example
text_number = "50"
# We use int() to turn the text "50" into a real math number 50
real_number = int(text_number) 
        

4. Write about debugging.

Answer:

Debugging is the process of hunting down and fixing mistakes (called bugs) in your code so the program runs correctly. There are three main types of errors you will fix when debugging:

  • Syntax Errors: These are grammar mistakes in your code, like forgetting a bracket or spelling a command wrong. Python will stop immediately and tell you to fix it.
  • Runtime Errors: The code's grammar is fine, but it crashes while running because you asked it to do something impossible (like dividing a number by zero).
  • Logical Errors: The code runs perfectly without crashing, but it gives you the wrong answer because your math formula or reasoning was incorrect.

5. Write about break and continue statements in Python.

Answer:

Both break and continue are commands used inside loops to change how the loop behaves.

  • break: This acts as an emergency exit. It completely stops the loop immediately, even if the loop wasn't finished counting yet.
  • continue: This acts as a skip button. It skips the rest of the code for the current turn, and jumps right back to the top to start the next turn of the loop.
# Break Example
for i in range(1, 5):
    if i == 3:
        break # Stops completely when it hits 3
    print(i) 

# Continue Example
for i in range(1, 5):
    if i == 3:
        continue # Skips the number 3
    print(i) 
        

6. What is indentation in Python? Why is it important?

Answer:

Indentation refers to the empty spaces at the very beginning of a line of code (usually created by hitting the spacebar or Tab key).

Why is it important? In other languages, programmers use brackets `{ }` to group lines of code together. Python uses indentation instead. It is how Python knows which lines of code belong to a specific loop or an if statement. If your spacing is wrong, Python will throw an IndentationError and refuse to run the code.

if 5 > 2:
    # The spaces before "print" are the indentation.
    print("Five is bigger!") 
        

UNIT I (10 Marks Questions)

Python Basics: 10-Mark Questions in Detail

A step-by-step guide with practical code examples for every concept.

1. What is Python? Write the features of Python with an example.

Answer:

Python is a high-level programming language created in 1991. It is designed to be incredibly easy to read and write, meaning its code looks a lot like normal English rather than confusing computer symbols.

Important Features of Python:

  • Simple Syntax: You can write programs in fewer lines compared to other languages like C++ or Java.
  • Dynamically Typed: You do not have to announce if a variable is a number or text. Python figures it out instantly.
  • Interpreted: It runs your code line by line, which makes it very easy to find and fix mistakes.

Code Example: Notice how we don't have to declare what type of data player_name is. Python just knows it is text.

# Python is simple and dynamically typed
player_name = "Alex"
score = 50

# We can just print it out like plain English
print("Welcome", player_name)
print("Your starting score is:", score)
        

2. Write about the datatypes of Python with examples.

Answer:

A "datatype" tells the computer what kind of information it is dealing with so it knows how to handle it. You wouldn't do math on a word, and you wouldn't spell-check a number. Python has several built-in types:

  • int (Integer): Whole numbers with no decimals.
  • float: Numbers that have a decimal point.
  • str (String): Text data, always wrapped in quotes.
  • bool (Boolean): Only holds True or False.
  • list: A collection of items kept in order inside square brackets [].

Code Example: Here is how you create each datatype in Python.

# Creating different datatypes
age = 15                        # This is an int (Integer)
height = 5.8                    # This is a float
subject = "Computer Science"    # This is a str (String)
is_learning = True              # This is a bool (Boolean)

# This is a list containing strings
backpack = ["Laptop", "Notebook", "Pen"] 

print("My subject is:", subject)
        

3. Write about operators in Python with examples.

Answer:

Operators are special symbols used to do math calculations or ask logical questions about your data.

  • Arithmetic Operators: Do standard math (+, -, *, /).
  • Comparison Operators: Compare two things and answer True or False (== means equal to, > means greater than).
  • Logical Operators: Combine multiple questions together (and, or).

Code Example: Let's use all three types of operators to check if a student passed a test.

math_score = 40
science_score = 45

# 1. Arithmetic Operator (+)
total_score = math_score + science_score 

# 2. Comparison Operator (>)
passed_math = math_score > 35  # Gives True

# 3. Logical Operator (and)
# Checks if BOTH conditions are True
passed_class = (total_score > 80) and (passed_math == True)

print("Total Score:", total_score)
print("Did the student pass?", passed_class)
        

4. Write about Control statements with examples.

Answer:

Control statements let you change how your program runs. Instead of just reading top-to-bottom, the program can make choices (Conditional statements) or repeat tasks (Looping statements).

  • If / Else (Decisions): Runs code only if a condition is True. If it's False, it runs the backup plan.
  • For Loop (Repeating): Repeats a block of code a specific number of times.

Code Example: Here is an example of an if statement making a choice, and a for loop repeating a task.

--- Decision Making ---
temperature = 30

if temperature > 25:
    print("It is a hot day. Turn on the fan.")
else:
    print("The weather is nice.")

--- Looping ---
# This will repeat the print command 3 times (0, 1, 2)
for number in range(3):
    print("Repeating lap number:", number)
        

5. Write about Python string handling functions with examples.

Answer:

Strings are text. Python has built-in tools (functions) that allow you to edit, change, and check your text easily without having to write complex code yourself.

  • len(): Counts the number of characters in the text (including spaces).
  • upper(): Changes all letters to uppercase.
  • replace(): Swaps a specific word for a different word.
  • split(): Chops a sentence into separate words and puts them in a list.

Code Example: Let's take a regular sentence and use functions to change how it looks.

message = "Coding is fun"

# 1. Count the letters and spaces
length = len(message)
print("Total characters:", length) # Outputs 13

# 2. Make it all uppercase
print(message.upper()) # Outputs "CODING IS FUN"

# 3. Replace a word
new_message = message.replace("fun", "awesome")
print(new_message) # Outputs "Coding is awesome"

# 4. Split the sentence into a list of words
word_list = message.split()
print(word_list) # Outputs ['Coding', 'is', 'fun']
        

Post a Comment

0 Comments