Python basic questions

Ashim Kc
7 Min Read

Basics- defining variables, data types, and simple operations

  • Defining Variables:
    • Define a variable name and assign it your name. Print the variable.
  • Data Types:
    • Create variables representing different data types: integer, float, string, and boolean. Print each variable and its data type.
  • Checking Data Types:
    • Define a variable value and assign it a value of your choice. Check its data type using the type() function. Print the result.
  • Arithmetic Operations:
    • Define variables num1 and num2 and assign them integer or float values. Perform addition, subtraction, multiplication, and division on them. Print the results.
  • String Concatenation:
    • Create variables first_name and last_name and assign them your first and last name, respectively. Concatenate them to form your full name and print it.

Control flow (If-else and loops)

  • If-Else Statements:
    • Create a variable age and assign it an integer value representing a person’s age. Write an if-else statement to check if the person is eligible to vote (age >= 18). Print “You are eligible to vote” if true, otherwise print “You are not eligible to vote”.
  • For Loops:
    • Write a for loop to print all even numbers between 1 and 100 (inclusive).
    • Write a for loop to print every character of your name separately.
  • While Loops:
    • Create a variable total and assign it an initial value of 0. Write a while loop to add numbers from 1 to 5 to total and print the total after each iteration.(iteration = repetition).

Functions:

  • Define a function called add_numbers that takes two numbers as input and returns their difference. Call the function with different pairs of numbers and print the results.
  • Define a function called find_avg that takes three numbers as input and returns their average. Call the function with different pairs of numbers and print the results.

Data structure:

List Exercise:

Define a list called shopping_list containing items you need to buy at the grocery store (e.g., “apples”, “milk”, “bread”). Print the shopping list.

  • Use the append() method to add an item to the shopping list. Print the updated list.
  • Use the remove() method to remove an item from the shopping list. Print the updated list.
  • Use the sort() method to sort the items in alphabetical order. Print the sorted list.
  • Use the len() function to print the length of the shopping list.
  • Write a for loop to iterate over the shopping list and print each item.

Tuple Exercise:

Define a tuple called student_info containing information about a student (e.g., name, age, grade). Print the student_info.

  • Access and print each element of the student_info tuple individually.
  • Use tuple unpacking to assign the elements of the student_info tuple to three variables: name, age, and grade. Print these variables.

(To unpack a tuple into separate variables, assign the tuple to the variables separated by commas.)

  • Write a for loop to iterate over the student_info tuple and print each element.

Dictionary Exercise:

Define a dictionary called student_info containing information about a student (e.g., “name”, “age”, “grade”). Print the student_info.

  • Access and print each item in the student_info dictionary individually.
  • Use the update() method to add a new key-value pair to the student_info dictionary (e.g., “city”: “New York”). Print the updated dictionary.
  • Use the pop() method to remove an item from the student_info dictionary. Print the updated dictionary.
  • Use a for loop to iterate over the keys of the student_info dictionary and print each key-value pair.

File handling:

File handling exercises:

  • Create and Open a file called “sample.txt” in read mode (‘r’). Read the contents of the file and print them.
  • Open the same file “sample.txt” in write mode (‘w’). Write some text to the file (e.g., “Hello, world!”). Close the file.
  • Open the file “sample.txt” again in append mode (‘a’). Append some additional text to the file (e.g., “Appending text to the file.”). Close the file.
  • Open the file “sample.txt” one more time in read mode (‘r’). Read the contents of the file again and print them to verify the changes.

Solutions:

Defining Variables:

name = "Your name"
print(name)

Data Types:

integer_var = 5
float_var = 3.14
string_var = "Hello, world!"
boolean_var = True

print(integer_var, type(integer_var))
print(float_var, type(float_var))
print(string_var, type(string_var))
print(boolean_var, type(boolean_var))

Checking Data Types:

value = 10
print(type(value))

Arithmetic Operations:

num1 = 10
num2 = 5
print("Addition:", num1 + num2)
print("Subtraction:", num1 - num2)
print("Multiplication:", num1 * num2)
print("Division:", num1 / num2)

String Concatenation:

first_name = "John"
last_name = "Doe"
full_name = first_name + " " + last_name
print(full_name)

If-Else Statements:

age = 20
if age >= 18:
    print("You are eligible to vote")
else:
    print("You are not eligible to vote")

For Loops:

# Print even numbers between 1 and 100
for num in range(1, 101):
    if num % 2 == 0:
        print(num)

# Print each character of the name separately
name = "John Doe"
for char in name:
    print(char)

While Loops:

total = 0
num = 1
while num <= 5:
    total += num
    print("Total:", total)
    num += 1

Functions:

def add_numbers(num1, num2):
    return num1 + num2

print(add_numbers(10, 5))

def find_avg(num1, num2, num3):
    return (num1 + num2 + num3) / 3

print(find_avg(10, 20, 30))

List Exercise:

shopping_list = ["apples", "milk", "bread"]
print(shopping_list)

shopping_list.append("eggs")
print(shopping_list)

shopping_list.remove("milk")
print(shopping_list)

shopping_list.sort()
print(shopping_list)

print("Length of shopping list:", len(shopping_list))

for item in shopping_list:
    print(item)

Tuple Exercise:

student_info = ("John Doe", 25, "A")
print(student_info)

print(student_info[0])
print(student_info[1])
print(student_info[2])

name, age, grade = student_info
print(name, age, grade)

for item in student_info:
    print(item)

Dictionary Exercise:

student_info = {"name": "John Doe", "age": 25, "grade": "A"}
print(student_info)

print(student_info["name"])
print(student_info["age"])
print(student_info["grade"])

student_info.update({"city": "New York"})
print(student_info)

student_info.pop("age")
print(student_info)

for key, value in student_info.items():
    print(key + ":", value)

File Handling Exercise:

# Read from the file
with open("sample.txt", "r") as file:
    print(file.read())

# Write to the file
with open("sample.txt", "w") as file:
    file.write("Hello, world!")

# Append to the file
with open("sample.txt", "a") as file:
    file.write("Appending text to the file.")

# Read from the file again
with open("sample.txt", "r") as file:
    print(file.read())
Share This Article
Leave a comment

Leave a Reply

Your email address will not be published. Required fields are marked *