PYnative

Python Programming

  • Learn Python
    • Python Tutorials
    • Python Basics
    • Python Interview Q&As
  • Exercises
    • Python Exercises
    • C Programming Exercises
    • C++ Exercises
  • Quizzes
  • Code Editor
    • Online Python Code Editor
    • Online C Compiler
    • Online C++ Compiler
Home » Python Exercises » Python Input and Output Exercise: 20+ Coding Problems with Solutions

Python Input and Output Exercise: 20+ Coding Problems with Solutions

Updated on: March 26, 2026 | 111 Comments

Whether you’re building interactive command-line applications, processing data, or working with files, a solid understanding of Python’s input and output (I/O) mechanisms is crucial. At its core, input is how a program receives data, while output is how it presents results to the user.

This article is a practical guide to mastering these essential skills. This article provides 20+ Python Input and Output practice questions that focus entirely on taking user input, displaying information, and interacting with files. You will also learn techniques for formatting output to present your data clearly and in a user-friendly way.

Each coding challenge includes a Practice Problem, Hint, Solution code, and detailed Explanation, ensuring you don’t just copy code, but genuinely practice and understand how and why it works.

  • All solutions have been fully tested on Python 3.
  • Interactive Learning: Use our Online Code Editor to solve these exercises in real time.

Also Read:

  • Python Exercises: A set of 20 topic-specific exercises
  • Python input and Output
  • Python File Handling
  • Python Input and Output Quiz
+ Table of Contents (23 Exercises)

Table of contents

  • Exercise 1. Accept numbers from a user
  • Exercise 2. Display variables with a separator
  • Exercise 3. Convert decimal number to octal
  • Exercise 4. Binary representation
  • Exercise 5. Accept any three strings from one input() call
  • Exercise 6. Hexadecimal representation
  • Exercise 7. Display float number with 2 decimal places
  • Exercise 8. Percentage display
  • Exercise 9: Display right-aligned output
  • Exercise 10. Center-aligned text
  • Exercise 11: Padding with zeros
  • Exercise 12: Format variables using string.format() method
  • Exercise 13. Currency formatting with commas
  • Exercise 14: Accept a list of 5 float numbers
  • Exercise 15. Tabular output from lists
  • Exercise 16. Interactive menu
  • Exercise 17. Masked password input ( getpass )
  • Exercise 18. Read a file and store its content in a list
  • Exercise 19. Write list of strings to a file
  • Exercise 20. Count total lines in a file
  • Exercise 21. Read line number 4 from a file
  • Exercise 22. Check if file is empty
  • Exercise 23. Delete a specific file

Exercise 1. Accept numbers from a user

Practice Problem: Write a program that accepts two integer numbers from the user and calculates their multiplication. Print the final result to the console.

Exercise Purpose: This exercise introduces the fundamental concept of user interaction. It teaches how to use the input() function to capture data and the importance of “type casting” (converting strings to integers) since all input starts as text.

Given Input:

  • First Number: 10
  • Second Number: 20

Expected Output: The multiplication is: 200

Help: Take user input in Python

Solution
# Accept input from user
num1 = int(input("Enter first number: "))
num2 = int(input("Enter second number: "))

# Calculate multiplication
res = num1 * num2

# Display result
print("The multiplication is:", res)Code language: Python (python)

Explanation to Solution:

  • int(input(...)): This nested function call takes the user’s keystrokes and immediately transforms them into a whole number (integer) so Python can do math with them.
  • num1 * num2: The asterisk is the multiplication operator in Python.
  • print(): This function outputs the final calculated value to the screen.

Exercise 2. Display variables with a separator

Practice Problem: Use the print() function to format the words “Name”, “Is”, and “James” so they appear with three asterisks (***) between them.

Exercise Purpose: The print() function is more powerful than it looks. This exercise teaches the use of the sep (separator) keyword argument, which allows you to define how multiple items should be joined together in the output without manually typing strings.

Given Input:

  • Strings: “Name”, “Is”, “James”

Expected Output:

Name***Is***James
Solution
# Using the sep parameter to join strings
print('Name', 'Is', 'James', sep='***')Code language: Python (python)

Explanation to Solution:

  • Comma Separation: In Python’s print(), commas signify different objects to be printed.
  • sep='***': By default, sep is a space. By changing it to '***', we tell Python to place that specific string between every object listed in the function call.

Exercise 3. Convert decimal number to octal

Practice Problem: Accept an integer from the user and display it as an octal number (Base 8).

Exercise Purpose: Computers often use different numbering systems (Hexadecimal, Octal, Binary). This exercise demonstrates how to use “Format Specifiers” in strings to automatically convert values between number systems for display.

Given Input: Decimal: 8

Expected Output:

The octal number of decimal number 8 is 10
Solution
num = 8
# Using %o to format the integer as octal
print('%o' % num)Code language: Python (python)

Explanation to Solution:

  • %o: This is a placeholder that tells Python: “Take the integer provided and represent it as an Octal value.”
  • Base-8 Logic: In Octal, the number 8 is represented as 10 because the system “rolls over” after 7.

Exercise 4. Binary representation

Practice Problem: Accept an integer from the user and display its value in binary format (Base 2).

Exercise Purpose: Computers process everything in binary. This exercise shows how to use Python’s built-in formatting to visualize how a decimal number is represented at the hardware level using only 0s and 1s.

Given Input: Decimal Number: 45

Expected Output:

The binary representation of 45 is 101101
Solution
num = int(input("Enter a decimal number: "))

# Using f-string with the 'b' (binary) type code
binary_val = f"{num:b}"

print(f"The binary representation of {num} is {binary_val}")Code language: Python (python)

Explanation to Solution:

  • :b: This is the binary type code. It tells Python to convert the integer into its Base-2 equivalent.
  • Base-2 Logic: In binary, 45 is calculated as ( 32 * 1 ) + ( 16 * 0 ) + ( 8 * 1 ) + ( 4 * 1 ) + ( 2 * 0) + ( 1 * 1)

Exercise 5. Accept any three strings from one input() call

Practice Problem: Write a program that takes three names (or any words) from a user in a single input prompt and assigns them to three separate variables.

Exercise Purpose: Users dislike having to hit Enter three times for three pieces of data. This exercise teaches the split() method, the standard way to parse a single string into multiple data points based on whitespace.

Given Input: Emma Jessa Kelly

Expected Output:

Name1: Emma
Name2: Jessa
Name3: Kelly
Solution
# Taking multiple inputs in one go
str1, str2, str3 = input("Enter three names: ").split()

print('Name1:', str1)
print('Name2:', str2)
print('Name3:', str3)Code language: Python (python)

Explanation to Solution:

  • .split(): By default, this function looks for spaces and “splits” the string there.
  • Unpacking: The syntax str1, str2, str3 = ... is called “iterable unpacking.” It takes the resulting list of three items and distributes them into the three variables in order.

Exercise 6. Hexadecimal representation

Practice Problem: Accept an integer and display its value in hexadecimal format (Base 16).

Exercise Purpose: Hexadecimal is widely used in computing for memory addresses and color codes (e.g., #FFFFFF). This exercise teaches you how to bridge the gap between human-readable decimals and developer-centric hex values.

Given Input: Decimal Number: 255

Expected Output: The hexadecimal value is ff

Solution
num = int(input("Enter a number: "))

# :x produces lowercase (ff), :X produces uppercase (FF)
hex_val = f"{num:x}"

print(f"The hexadecimal value is {hex_val}")Code language: Python (python)

Explanation to Solution:

  • :x: The hexadecimal type code. Hex uses sixteen symbols: 0–9 and a–f.
  • Case Sensitivity: Using lowercase x results in ff, while uppercase X would result in FF. This is a common requirement in protocol documentation.

Exercise 7. Display float number with 2 decimal places

Practice Problem: Display a float number (a number with decimals) such as 458.541315 rounded to exactly two decimal places.

Exercise Purpose: Real-world data can be messy. This task is important for UI/UX and reporting because it helps make long, complex floating-point numbers easier to read.

Given Input: Number: 458.541315

Expected Output: 458.54

Solution
num = 458.541315

# Displaying 2 decimal places using formatting
print('%.2f' % num)Code language: Python (python)

Explanation to Solution:

  • %.2f: The f stands for “float,” and the .2 tells Python to stop after two digits following the decimal point.
  • Rounding: Python automatically rounds the last digit appropriately when using this formatting method.

Exercise 8. Percentage display

Practice Problem: Ask the user for a numerator and a denominator. Calculate the percentage (numerator/denominator * 100) and display it with exactly two decimal places followed by a percent sign.

Exercise Purpose: In this exercise, you will learn about string interpolation. You will practice combining math results with symbols like % and learn how to control the number of decimal places so your answers look neat.

Given Input:

  • Numerator: 22
  • Denominator: 29

Expected Output: The result is: 75.86%

Solution
num = int(input("Enter numerator: "))
den = int(input("Enter denominator: "))

percentage = (num / den) * 100

# Using f-string for precision and adding the '%' literal
print(f"The result is: {percentage:.2f}%")Code language: Python (python)

Explanation to Solution:

  • percentage:.2f: Inside the curly braces of an f-string, the :.2f part tells Python to format the number as a float with two digits after the decimal point.
  • The trailing %: Since the percent sign isn’t a special character in f-strings (unlike in the old % formatting style), you can just type it at the end of the curly brace.

Exercise 9: Display right-aligned output

Practice Problem: Ask the user for a word and a number. Print the word right-aligned in a total field width of 20 characters, followed by the number.

Exercise Purpose: Good design is important. When you create text-based reports, lining up columns makes them easier to read. In this exercise, you will learn how to use Alignment Flags to set aside space on the screen and move text to the left, right, or center.

Given Input:

  • Word: “Python”
  • Number: 3.12

Expected Output:

               Python 3.14
Solution
word = input("Enter a word: ")
version = input("Enter a version number: ")

# Right-align the word in 20 spaces
print(f"{word:>20} {version}")Code language: Python (python)

Explanation to Solution:

  • :>20: This tells Python, “Reserve a block of 20 characters. Put the variable at the very end (right) and fill the remaining space on the left with blanks.”
  • Padding: If the word is “Python” (6 letters), Python will automatically insert 14 spaces before it.

Exercise 10. Center-aligned text

Practice Problem: Display a string centered within a 40-character field, using hyphens (-) as the padding character.

Exercise Purpose: Centering text is a common way to make headers or dividers in console reports. In this exercise, you will learn about the “Fill” and “Align” parts of f-string formatting.

Given Input: Text: “REPORT SUMMARY”

Expected Output:

-------------REPORT SUMMARY-------------
Solution
title = "REPORT SUMMARY"

# Center (^) with hyphen (-) as fill in a width of 40
formatted_title = f"{title:-^40}"

print(formatted_title)Code language: Python (python)

Explanation to Solution:

  • -: The character used to fill the empty space.
  • ^: The alignment flag for “Center.”
  • 40: The total width of the resulting string. Python calculates how many hyphens are needed on each side to make the total length exactly 40.

Exercise 11: Padding with zeros

Practice Problem: Ask the user for a number. Print this number padded with leading zeros so the total width is exactly 5 digits.

Exercise Purpose: This method is important when you need to create standardized IDs, serial numbers, or digital clock displays, such as showing “09” instead of “9” minutes. It shows you how to set a specific number format no matter the original input size.

Given Input: Number: 42

Expected Output: 00042

Solution
val = input("Enter your ID number: ")

# Method 1: Using zfill
print(val.zfill(5))

# Method 2: Using f-string (requires integer)
# print(f"{int(val):05}")Code language: Python (python)

Explanation to Solution:

  • zfill(5): This is a built-in string method specifically designed to add “0” characters to the start of a string until it reaches the desired length.
  • Use Case: This is incredibly common when naming files (e.g., image_001.jpg, image_002.jpg) so they sort correctly in your computer’s folders.

Exercise 12: Format variables using string.format() method

Practice Problem: Given three variables quantity = 3, totalMoney = 450, and price = 150, use the format() method to print a sentence that neatly displays these values.

Exercise Purpose: Hard-coding strings with plus signs (+) is messy and error-prone. This exercise introduces the .format() method, a powerful way to inject variables into templates with precision and readability.

Given Input: quantity = 3, totalMoney = 450, price = 150

Expected Output:

I have 450 dollars so I can buy 3 football for 150.00 dollars.
Solution
quantity = 3
totalMoney = 450
price = 150
statement = "I have {1} dollars so I can buy {0} football for {2:.2f} dollars."

print(statement.format(quantity, totalMoney, price))Code language: Python (python)

Explanation to Solution:

  • {0}, {1}, {2}: These numbers refer to the position of the arguments in the .format() call. This allows you to reuse variables or change their order without rearranging the function call.
  • {2:.2f}: This is a bit of formatting magic that tells Python to treat the third variable as a float and show exactly two decimal places.

Exercise 13. Currency formatting with commas

Practice Problem: Display a large number as currency, including a dollar sign, commas for thousands, and two decimal places.

Exercise Purpose: Financial applications require strict formatting. This exercise combines three concepts: prefixing, grouping (using commas), and precision to create a professional-grade money display.

Given Input: Amount: 1250500.7

Expected Output:

Total Balance: $1,250,500.70
Solution
balance = 1250500.7

# , adds commas, .2f adds two decimal places
formatted_balance = f"${balance:,.2f}"

print(f"Total Balance: {formatted_balance}")Code language: Python (python)

Explanation to Solution:

  • ,: This special grouping character tells Python to insert a comma every three digits.
  • .2f: Ensures the cents are always shown as two digits (e.g., .70 instead of .7).
  • $: Simply a literal character placed outside the curly braces to denote the currency.

Exercise 14: Accept a list of 5 float numbers

Practice Problem: Write a program that accepts 5 float numbers as input from the user and stores them in a list.

Exercise Purpose: This exercise moves beyond single variables to “Data Structures.” It teaches how to use loops or list comprehension to efficiently handle multiple inputs and store them in a single list.

Given Input: Numbers: 78.6, 78.6, 85.3, 1.2, 3.5

Expected Output: [78.6, 78.6, 85.3, 1.2, 3.5]

Refer: Take a list as input in Python.

Solution
numbers = []

# Run a loop 5 times to get 5 inputs
for i in range(0, 5):
    print("Enter number at location", i, ":")
    item = float(input())
    numbers.append(item)

print("User List:", numbers)Code language: Python (python)

Explanation to Solution:

  • numbers = []: Creates an empty container (list) to hold the data.
  • range(0, 5): Ensures the loop runs exactly five times.
  • float(input()): Similar to Exercise 1, but converts the input to a decimal-capable “float” instead of an integer.
  • .append(item): This method adds the new number to the end of the existing list.

Exercise 15. Tabular output from lists

Practice Problem: You have two lists: names = ["Alice", "Bob", "Charlie"] and scores = [85, 92, 78]. Print these as a table with aligned columns.

Exercise Purpose: This exercise introduces “Parallel Iteration.” It teaches you how to step through two related lists simultaneously and format them to look like an organized database table.

Given Input:

  • names = ["Alice", "Bob", "Charlie"]
  • scores = [85, 92, 78]

Expected Output:

Name       Score
----------------
Alice 85
Bob 92
Charlie 78
Solution
names = ["Alice", "Bob", "Charlie"]
scores = [85, 92, 78]

print(f"{'Name':<10} {'Score'}")
print("-" * 15)

for name, score in zip(names, scores):
    print(f"{name:<10} {score}")Code language: Python (python)

Explanation to Solution:

  • zip(names, scores): This “zips” the two lists together like a zipper, pairing “Alice” with 85, “Bob” with 92, and so on.
  • :<10: This is the “left-align” flag. It ensures the Name column is always 10 characters wide, so the Score column always starts at the exact same horizontal position.

Exercise 16. Interactive menu

Practice Problem: Create a menu that offers three options: “1. Say Hello”, “2. Calculate Square”, and “3. Exit”. The program should perform the action based on the number the user types.

Exercise Purpose: This is the foundation of “Command Line Interfaces” (CLI). It teaches you how to map user input to specific logic blocks using conditional statements, turning a linear script into an interactive application.

Given Input:

  • Choice: 2
  • Number to square: 5

Expected Output:

Enter choice (1-3): 2
Enter number to square: 5
The square is: 25
Solution
print("1. Say Hello\n2. Calculate Square\n3. Exit")
choice = input("Enter choice (1-3): ")

if choice == "1":
    print("Hello there! Hope you're having a great day.")
elif choice == "2":
    val = int(input("Enter number to square: "))
    print(f"The square is: {val * val}")
elif choice == "3":
    print("Exiting... Goodbye!")
else:
    print("Invalid choice. Please pick 1, 2, or 3.")Code language: Python (python)

Explanation to Solution:

  • String Comparison: Notice we compare choice == "1". Since input() returns a string, we don’t even need to convert it to an integer unless we plan to do math with the choice itself.
  • Control Flow: The elif (else-if) ensures that only one block of code runs, skipping the others once a match is found.

Exercise 17. Masked password input (getpass)

Practice Problem: Write a script that asks a user for their username using standard input and their password using masked input (where the characters don’t appear on the screen).

Exercise Purpose: Security is paramount. Using input() for passwords is a major vulnerability because the password remains visible in the terminal’s scrollback buffer. The getpass module is the standard way to handle sensitive credentials by suppressing local echo.

Given Input:

  • Username: admin
  • Password: SecretPassword123 (invisible during typing)

Expected Output:

Enter Username: admin
Password:
Login successful for admin!
Solution
import getpass

user = input("Enter Username: ")
# Characters will not be displayed as you type
pwd = getpass.getpass("Password: ")

if user == "admin" and pwd == "SecretPassword123":
    print(f"Login successful for {user}!")
else:
    print("Access Denied.")Code language: Python (python)

Explanation to Solution:

  • import getpass: This is a standard Python library designed specifically for secure interaction.
  • getpass.getpass(): This function talks directly to the terminal to turn off “echoing.” While the user types, the cursor stays still, and no characters are sent to the display.
  • Logic: Despite being hidden from the screen, the variable pwd still stores the exact string the user typed for comparison.

Exercise 18. Read a file and store its content in a list

Practice Problem: Read an existing file test.txt and store every line as an individual element in a Python list.

Exercise Purpose: It’s the first step in “Data Parsing”, taking raw text from a disk and converting it into a structured format (a list) that Python can easily sort, filter, or search.

Given Input: A file test.txt with multiple lines.

Expected Output: ['Line 1', 'Line', 'Line']

See:

  • Python file handling
  • Python Read file
Solution
# Read file content into a list
with open("test.txt", "r") as f:
    lines = f.readlines()
    print(lines)Code language: Python (python)

Explanation to Solution:

  • readlines(): This is a memory-efficient way to capture the entire structure of a file.
  • \n in Output: You will notice the newline characters are preserved in the list. To remove them, you would typically use a list comprehension with .strip().

Exercise 19. Write list of strings to a file

Practice Problem: Take a list of favorite fruits and save each fruit onto a new line in a file named fruits.txt.

Exercise Purpose: In data science or web dev, you often process data in memory (as a list) and then need to “persist” it (save it to a disk). This exercise teaches you how to export structured Python data into a permanent text format.

Given Input:

  • fruit_list = ["Apple", "Banana", "Cherry", "Date"]

Expected Output: A file fruits.txt created with each fruit on its own line.

Help: Python write file

Solution
fruit_list = ["Apple", "Banana", "Cherry", "Date"]

# Open file for writing
with open("fruits.txt", "w") as f:
    for fruit in fruit_list:
        f.write(fruit + "\n")

print("File 'fruits.txt' has been created successfully.")Code language: Python (python)

Explanation to Solution:

  • with open(...) as f: This is the “Context Manager.” It handles opening and closing the file stream, ensuring no memory leaks occur even if the code fails midway.
  • "w" mode: This stands for “write.” Be careful: it will completely overwrite the file if it already exists.
  • + "\n": Files are just long streams of characters. We manually add the “New Line” character to ensure the file is human-readable.

Exercise 20. Count total lines in a file

Practice Problem: Write a program that opens an existing text file and calculates exactly how many lines of text it contains.

Exercise Purpose: This is a fundamental “Data Auditing” task. Before you process a log file or a dataset, you need to know its size. This exercise teaches you how to iterate through a file object efficiently.

Given Input: A file sample.txt with 12 lines of text.

Expected Output: 12

Solution
line_count = 0

with open("sample.txt", "r") as f:
    for line in f:
        line_count += 1

print(f"The file contains {line_count} lines.")Code language: Python (python)

Explanation to Solution:

  • Memory Efficiency: Instead of using f.readlines() (which loads the entire file into RAM), for line in f reads one line at a time. This allows you to count lines in a 10GB file without crashing your computer.
  • The Counter: Every time the loop completes one cycle, it means it found a newline character, so we increment line_count.

Exercise 21. Read line number 4 from a file

Practice Problem: Open a file and display only the fourth line of the content.

Exercise Purpose: Sometimes files are massive (gigabytes in size), and you only need a specific snippet. This exercise reinforces the idea that file lines can be treated like a list, allowing for direct, indexed access.

Given Input: A file test.txt containing:

Line 1
Line 2
Line 3
Line 4
Line 5

Expected Output: Line 4

See: Read Specific Lines From a File in Python

Solution
# Opening the file in read mode
with open("test.txt", "r") as f:
    # Read all lines into a list
    lines = f.readlines()
    # Print the 4th line (index 3)
    print(lines[3])Code language: Python (python)

Explanation to Solution:

  • readlines(): Once again, this creates a list where each element is one line of text.
  • lines[3]: Because Python is zero-indexed, the first line is at index 0, the second at index 1, and so on. Therefore, line 4 is found at index 3.

Exercise 22. Check if file is empty

Practice Problem: Write a script that checks a file’s metadata. If the file size is 0 bytes, print “File is empty”; otherwise, print the size in bytes.

Exercise Purpose: Sometimes a file exists but contains no data (common in failed downloads or interrupted logs). This exercise introduces the os module and “system metadata”—information about a file rather than the content inside it.

Given Input: An empty file named empty_log.txt.

Expected Output:

Checking empty_log.txt...
Status: File is empty.
Solution
import os

filename = "empty_log.txt"

# Check if the file actually exists first to avoid errors
if os.path.exists(filename):
    file_info = os.stat(filename)
    if file_info.st_size == 0:
        print(f"Status: {filename} is empty.")
    else:
        print(f"Status: {filename} size is {file_info.st_size} bytes.")
else:
    print("File not found.")Code language: Python (python)

Explanation to Solution:

  • os.stat(): This function performs a “system call” to the Operating System to retrieve a structure of information (size, creation date, permissions).
  • .st_size: This specific attribute tells you the size in bytes. 1 byte usually equals one character.
  • os.path.exists(): A defensive programming practice that prevents your script from crashing if the file is missing.

Exercise 23. Delete a specific file

Practice Problem: Write a program that asks the user for a filename and deletes it from the folder. Caution: This operation is permanent.

Exercise Purpose: File system maintenance. This exercise shows you how Python can perform high-level administrative tasks. It also emphasizes the importance of “High Risk” operations and the need to always verify the user’s intent.

Given Input: Filename to delete: old_data.csv

Expected Output:

Are you sure you want to delete 'old_data.csv'? (y/n): y
File 'old_data.csv' has been deleted.
Solution
import os

target = input("Enter filename to delete: ")

if os.path.exists(target):
    confirm = input(f"Are you sure you want to delete '{target}'? (y/n): ")
    if confirm.lower() == 'y':
        os.remove(target)
        print(f"File '{target}' has been deleted.")
    else:
        print("Operation cancelled.")
else:
    print("Error: File does not exist.")Code language: Python (python)

Explanation to Solution:

  • os.remove(): This is the core command that tells the OS to un-link the file from the directory. There is no “Recycle Bin” for this command; it is gone immediately.
  • .lower() == 'y': This makes your user interface more robust by accepting “Y” or “y”.
  • Defensive Logic: By checking os.path.exists(), you ensure the program handles missing files gracefully rather than stopping with a red error message.

深圳市网捷达科技有限公司 联系电话:18910898173;

ICP备案号:粤ICP备2024312167号-2

Copyright © 网捷达 版权所有

Did you find this page helpful? Let others know about it. Sharing helps me continue to create free Python resources.

TweetF  sharein  shareP  Pin

About Vishal

I’m Vishal Hule, the Founder of PYnative.com. As a Python developer, I enjoy assisting students, developers, and learners. Follow me on Twitter.

Related Tutorial Topics:

Python Python Basics Python Exercises

All Coding Exercises:

C Exercises
C++ Exercises
Python Exercises

Python Exercises and Quizzes

Free coding exercises and quizzes cover Python basics, data structure, data analytics, and more.

  • 15+ Topic-specific Exercises and Quizzes
  • Each Exercise contains 25+ questions
  • Each Quiz contains 25 MCQ
Exercises
Quizzes

Comments

  1. Malcolm says

    November 15, 2024 at 6:32 am

    My answer for 6 removes the item from a list rather than skipping it during the write stage:

    old = open(‘test.txt’, ‘r’)
    document = old.readlines()
    old.close()
    document.pop(4)
    new = open(‘answer.txt’, ‘w’)
    for i in document:
    new.write(i)
    new.close()

    Reply
    • Malcolm says

      November 15, 2024 at 6:34 am

      oops. “new.write(i)” should be indented!!

      Reply
  2. Malcolm says

    November 14, 2024 at 6:22 pm

    An alternative for question 1:

    data = input(‘Enter two numbers separated by a space: ‘)
    a, b = data.split()
    print(‘{} times {} equals {}’.format(a, b, int(a)*int(b)))

    Reply
  3. sahul hameed says

    May 20, 2024 at 9:50 pm

    #exercise2
    class exercise2:
    def display(self):
    a=”Name”
    b=”Is”
    c=”James”
    print(a,b,c, sep=” **”)
    ex2=exercise2()
    ex2.display()

    Reply
  4. sahul hameed says

    May 20, 2024 at 9:48 pm

    #exercise 1
    class excercise1:
    def __init__(self):
    self.a=int(input(“enter the value for a”))
    self.b=int(input(“enter the value for b”))

    def calMulti(self):
    ans=self.a * self.b
    print(ans)

    ex1=excercise1()
    ex1.calMulti()

    Reply
  5. Adesayo says

    April 10, 2024 at 9:27 pm

    EXERCISE 5 SOLUTION

    numbers = []
    while True:
    item = (float(input(“enter a float”)))
    numbers.append(item)
    if len(numbers) == 5:
    break
    print (numbers)

    Reply
  6. Nethra says

    February 17, 2024 at 10:35 am

    def exe_four():
    num = int(float(input(“Enter the number : “)))
    res = format(num, ‘.2f’)
    print(res)
    exe_four()

    //** I am not getting expected output **//

    Reply
  7. Phindulo Ratshilumela says

    December 15, 2023 at 9:13 pm

    Question 10

    with open(r”newone”,”r”) as file:
    lines = file.readlines()
    for i in range(len(lines)):
    if i == 3:
    print(lines[i])

    Reply
  8. Phindulo Ratshilumela says

    December 15, 2023 at 9:08 pm

    question 9
    we can use a list and check if the list is empty using the readlines
    with open(r”newone”,”r”) as file:
    lines = file.readlines()
    if lines == []:
    print(“there is nothing”)
    else:
    print(lines)

    Reply
  9. Phindulo Ratshilumela says

    December 15, 2023 at 6:58 pm

    Question 7

    user = input(“Enter three string: “).split(” “)
    count = 1
    for i in user:
    print(f”Name{count} : {i}”)
    count = count + 1

    Reply
    • Joonatan says

      March 30, 2025 at 4:04 am

      names = input(“Enter three names separated by a space: “).split()
      for i, name in enumerate(names, 1):
      print(f”Name{i}: {name}”)

      Reply
  10. Phindulo Ratshilumela says

    December 15, 2023 at 2:29 pm

    Question 6

    with open(“small.txt”,”r+”) as file:
    altlist = []
    lines = file.readlines()
    for i in range(4):
    altlist.append(lines[i])
    print(altlist)
    newlines = lines[5:]
    print(newlines)
    newlist = altlist + newlines
    print(newlist)
    with open(“newone”,”w”) as newo:
    for line in newlist:
    newo.write(line)

    Reply
  11. Jack says

    December 12, 2023 at 5:34 pm

    The solution to exercise 5 appears outside of the ‘+ solution’ box

    Reply
    • David says

      March 8, 2024 at 8:25 pm

      yahoo

      Reply
      • how you smart says

        April 27, 2024 at 12:02 pm

        my brain is no morre

        Reply
  12. ffrancisco says

    August 16, 2023 at 3:55 pm

    $exercise 1

    x = input(“1st number here “)
    y = input(“2nd number here “)

    z = (int(x)*int(y))

    print(z)

    Reply
    • nitro says

      August 21, 2023 at 9:04 pm

      nice one bro.

      Reply
  13. divya says

    July 12, 2023 at 5:59 pm

    q8:

    def formating(quantity,money,price):
    print(f"i have {money} so i can buy {quantity} football for {price:.2f}")
    formating(3,1000,450)

    with function

    Reply
  14. divya says

    July 12, 2023 at 5:54 pm

    question9:

    with open("empty.txt", "r") as file:
    content = file.read()

    if len(content.strip()) == 0:
    print("Empty")
    else:
    print("Not empty")

    we can aslo use tell() method to find the solution

    Reply
    • DiptiRanjan says

      October 12, 2023 at 8:57 pm

      Thanks Divya

      Reply
  15. Yutik says

    June 18, 2023 at 4:13 pm

    #6
    filename1 = "D:\\Exercise_python\\Doc1.txt"
    filename2 = "D:\\Exercise_python\\Doc2.txt"
    with open(filename1,'r') as file1:
    content = file1.readlines()
    with open(filename2,'w') as file2:
    for line in range(0,len(content)):
    if line == 4:
    continue
    file2.write(content[line])

    Reply
  16. 0xAH says

    March 2, 2023 at 1:04 am

    #9

    with open('one.txt', 'r') as one:
    print(len(one.read()) != 0)

    Reply
    • jack says

      May 17, 2023 at 6:57 pm

      YESS MATTTE

      Reply
  17. 0xAH says

    March 2, 2023 at 12:53 am

    #6

    with open('one.txt', 'r') as one:
    with open('two.txt', 'w') as two:
    x = 1
    for i in one:
    if x != 5:
    two.write(i)
    x += 1

    Reply
    • 0xAH says

      March 2, 2023 at 12:55 am

      oh cmon how to edit the comment
      cannot post the code as a code

      with open('one.txt', 'r') as one:
      with open('two.txt', 'w') as two:
      x = 1
      for i in one:
      if x != 5:
      two.write(i)
      x += 1

      Reply
      • 0xAH says

        March 2, 2023 at 12:56 am

        wtf do i neet to add tags for every line? what a dumb comments area, incredible

        Reply
        • 0xAH says

          March 2, 2023 at 12:56 am

          *need

          Reply
        • Vishal says

          March 2, 2023 at 1:34 pm

          Just add your entire code inside a pre tag

          your entire code

          tag

          Reply
          • Nethra says

            February 17, 2024 at 9:46 am

            Question 3:
            def exe_three():
            num = int(float(input(“Enter the number : “)))
            res = oct(num)
            print(res)
            exe_three()

  18. 0xAH says

    March 2, 2023 at 12:32 am

    #5

    print(['%.1f' % float(input()) for _ in range(5)])

    Reply
  19. Ankit Raj says

    February 20, 2023 at 11:09 am

    QUES-8
    print("My name is {Myname},i'm {Age} old, my goal is to become {ds}".format(Myname="Ankit Raj",Age = 24, ds = "Data Scientist"))

    Reply
    • Atul Sachan says

      February 22, 2023 at 7:05 pm

      print("My name is {Myname},i’m {Age} old, my goal is to become {ds}".format(Myname="Ankit Raj",Age = 24, ds = "Data Scientist"))

      use the below instead if you are using python3.6 and above:
      These are called f strings. easy to use and comprehend.

      <codeMyname = 'Ankit Raj'
      Age = 24
      ds = 'Data Scientist'

      print(f'My name is {Myname}, I am {Age} years old and I want to become {ds}')

      Reply
  20. Abdallah Muhammad says

    January 22, 2023 at 5:06 pm

    QUESTION 5:
    numbers = [ ]
    for i in range(5):
    print('Enter a number at location', i, ":")
    number = float(input())

    numbers.append(number)
    print('Userlist:', numbers)

    Reply
  21. pratishtha Singh says

    August 23, 2022 at 11:41 am

    Q:5

    user_input=eval(input("Enter a list of five floating numbers: "))
    print(user_input)
    Reply
  22. pratishtha Singh says

    August 23, 2022 at 11:34 am

    question-5 Here is an alternative solution

    user_input=eval(input("Enter a list of five floating numbers: "))
    
    convert_to_list=list(user_input)
    print(convert_to_list)
    
    output:  [78.6, 78.6, 85.3, 1.2, 3.5]
    Reply
    • jake says

      October 17, 2022 at 10:14 am

      ?

      Reply
    • vetri says

      January 11, 2023 at 9:10 pm

      it’s not work

      Reply
  23. camal says

    July 31, 2022 at 9:54 pm

    silution for exercise7

    Reply
    • Phindulo Ratshilumela says

      December 15, 2023 at 6:56 pm

      user = input(“Enter three string: “).split(” “)
      count = 1
      for i in user:
      print(f”Name{count} : {i}”)
      count = count + 1

      Reply
  24. Henry Piao says

    January 27, 2022 at 10:27 pm

    I have a problem while solving exercise 10. The Below code will not work properly but shows the wrong result.

    with open('./test.txt', 'r') as text:
        f_readline=text.readline(3)
        f_readlines=text.readlines()
        f_read=text.read()
    
        print(f_readlines[3])
    Reply
    • garoa says

      March 22, 2022 at 12:15 pm

      with open('.//test.txt', 'r') as text:
      with open(r'./test.txt', 'r') as text:
      with open('.\test.txt', 'r') as text:

      / is escape character in python

      Reply
  25. Aravindan says

    December 16, 2021 at 1:06 pm

    1. Write a program to accept two numbers from the user and calculate multiplication

    user_a = int(input('enter your first number'))
    user_ai = int(input('enter your second number'))
    
    print(f'addition of {user_a} and {user_ai} is {user_a + user_ai}')
    print(f'multiplication of {user_a} and {user_ai} is {user_a * user_ai}')

    2.

    print('Name**name**Is**James')

    # or

    print('My', 'Name', 'Is', 'James', sep='**')

    3.

    num = 29
    print('%o' % num) # % o - octal number base

    4.

    num = 38.98989 
    
    print('%.2f' %num)

    5.

    a = []
    for i,n in enumerate(range(5)):
        a.append(float(input(f'Enter the floating number:: {i}')))
    print('Your Floating Values are')
    print('')
    print(a)

    6.

    with open('test.txt', 'r') as read:
        li = read.readlines()  # Helps to read the lines!
        
    with open('summa.txt', 'w') as read:
        for i,line in enumerate(li):
            if i == 4:
                i = 5
                continue # Here we are assigning i = 5 and skipping the 4 th index 
            else:
                read.write(line)   # Helps to write the lines

    7.

    ie = input('Enter more names by using space in between!')
    
    ie = ie.split()
    print('\n')
    
    for i in range(len(ie)):
        print(f'Name {i}: {ie[i]}')

    8.

    import os # Operatung systms.. 
    size = os.stat('test.txt').st_size 
    
    if size == 0: # It means it does not have anything inside of this 
        print('file is empty')
    else:
        print('file has something')

    9.

    with open('test.txt', 'r') as file:
        li = file.readlines()
        
    for i, r in enumerate(li):
        if i == 3:
            print(r)
    Reply
  26. Washif says

    August 8, 2021 at 11:42 am

    #2 solution

    print('My name is James'. replace(' ', '**'))
    Reply
  27. Hemanta says

    August 6, 2021 at 6:21 pm

    totalMoney = 1000
    quantity = 3
    price = 450
    txt = "I have {} dollars so I can buy {} football for {} dollars."
    print(txt.format(totalMoney,quantity,('%.2f' % price)))

    **You can do this way also**

    Reply
    • Ayesha Hafiz says

      October 19, 2021 at 3:36 pm

      # YOU CAN ALSO DONE THIS WITH F-STRINGS:

      totalMoney = 1000
      quantity = 3
      price = 450
      print(f "I have {totalMoney} dollars so I can buy {quantity} football for {price} dollars."
      Reply
      • Akash says

        January 21, 2023 at 12:03 am

        in your code the price isn’t a float number

        Reply
        • Atul Sachan says

          February 22, 2023 at 7:08 pm

          put {price:.2f}

          Reply
  28. amani says

    July 31, 2021 at 11:56 pm

    count = 0
    with open("test.txt", "r") as fp:
        lines = fp.readlines()
        count = len(lines)
    with open("newFile.txt", "w") as fp:
        for line in lines:
            if (count == 3):
                count -= 1
                continue
            else:
                fp.write(line)
            count-=1

    i don’t understood it

    Reply
  29. WET says

    July 27, 2021 at 5:23 am

    question 1 says to calculate multiplication but the given solution returns sum. also, it converts float inputs to int.

    Reply
  30. Jac_1999 says

    July 12, 2021 at 3:48 pm

    # Read line number 4 from the following file

    x="l1","l2","l3","l4","l5"
    lines=x
    print(lines[2])
    Reply
  31. Mazhar says

    July 6, 2021 at 4:30 pm

    In Exercise 1 the question is for multiplication but Ans is giving in Sum.

    Reply
  32. ilyass says

    June 29, 2021 at 4:40 pm

    i can do this just by this simple code :

    str = input('enter three strings : ')
    print(str)

    output:

    Enter three strings : jhon emma kelly
    jhon emma kelly
    Reply
    • Karyse says

      July 12, 2021 at 9:13 pm

      That’s true, but it would be one string, not three.

      Reply
    • John Smith says

      December 14, 2021 at 5:20 am

      The exercise is asking for a specific output sequence that forces you to split the user input into three strings. There are many ways of accomplishing this. Here’s how I got there:

      user_input = input("Enter three string: ")
      three_strings = user_input.split(" ")
      id = 1
      for name in three_strings:
          print(f"Name{id}: {name}")
          id += 1
      Reply
  33. Aman Pratap says

    March 14, 2021 at 11:42 am

    Why this code is not working??
    Showing this error–

    Traceback (most recent call last):
    File “script.py”, line 5, in
    print(staa.format(mon, q, pr))
    ValueError: Format specifier missing precision

    
    mon = 1000
    q = 3
    pr = 200
    staa = "I have {0} money to buy {1} mangoes of price {2:.f} each"
    print(staa.format(mon, q, pr))
    Reply
    • vish says

      May 22, 2021 at 11:57 am

      nothing like .f and .2f

      Reply
    • sahil says

      June 5, 2021 at 6:39 am

      In bracket you should write {mon}, {q}, {pr} respectively.and before ‘I have put f to use fstrings

      Reply
    • RISHABH says

      July 2, 2021 at 8:57 am

      staa = "I have {0} money to buy {1} mangoes of price {2:.2f} each"

      try with this f single character will not support
      for decimal point

      Reply
  34. Glückskeks says

    March 6, 2021 at 10:03 pm

    Can someone explain to me how the solution for exercise 4 works? I don’t know what ‘%o’ means.

    Reply
    • aditi gupta says

      May 24, 2021 at 1:35 pm

      so we find 8 octal number so we use %o is given octal number

      Reply
  35. Hung Phan says

    March 1, 2021 at 10:27 am

    
    a = int(input ("your first number is: "))
    b = int(input ("your second number is: "))
    
    c = a*b
    c = str(c)
    
    print ("your result is: " + c)
    Reply
  36. Hung Phan says

    March 1, 2021 at 10:25 am

    In Ex.1, it is stated that u have to calculate the multiplication of the 2 inputs rather than the sum of the two
    (as the result given has shown)

    
    a = int(input ("your first number is = "))
    b = int(input ("your second number is: "))
    
    c = a*b
    c = str(c)
    
    print ("your result is: " + c)
    Reply
  37. Anchal says

    February 1, 2021 at 11:07 pm

    A person is playing a guessing game in which they have 3 guesses to figure out the computer’s secret letter which will be between A and Z inclusive. If they guess the letter correctly on the first guess the program should stop making them guess and they should get 26 points. If they guess the letter correctly on the second guess the program should stop making them guess and they should get 13 points. If they guess the letter correctly on the third guess, they should get 7 points. After an incorrect guess tell the user if their guess was too high or too low based on the results of checkGuess. If they fail to guess the letter correctly after 3 guesses they get 0 points. Be sure to tell them what score they got.

    Answer of this question how to make ipo chart

    Reply
    • John Smith says

      December 14, 2021 at 6:18 am

      This was a fun exercise. Thank you! Here’s how I approached this challenge:

      import random, string
      
      letters = ['A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M', 'N', 'O', 'P',
      'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X', 'Y', 'Z']
      secret_letter = random.choice(letters)
      p1, p2, p3, p4 = 26, 13, 7, 0
      
      alphabet = dict()
      for id, letter in enumerate(string.ascii_uppercase):
          alphabet[letter] = id + 1
      
      rounds = 1
      while rounds != 4:
          player_guess = input("Guess a letter from A - Z: ").upper()
          if rounds == 1 and player_guess == secret_letter:
              print(f"Congrats! You guessed the Secret Letter: '{secret_letter}' in Round {rounds}! You get {p1} points.")
              break
          elif rounds == 2 and player_guess == secret_letter:
              print(f"Congrats! You guessed the Secret Letter: '{secret_letter}' in Round {rounds}! You get {p2} points.")
              break
          elif rounds == 3 and player_guess == secret_letter:
              print(f"Congrats! You guessed the Secret Letter: '{secret_letter}' in Round {rounds}! You get {p3} points.")
              break
          elif rounds == 3 and player_guess != secret_letter:
              print(f"You failed to guess the secret letter, {secret_letter}, in time. You get {p4} points.")
              break
          else:
              if alphabet[player_guess]  alphabet[secret_letter]:
                  print(f"Your guess, '{player_guess}' is too high.")

      rounds += 1

      Reply
  38. Roberto Carpegiane says

    January 21, 2021 at 1:28 am

    Great exercises, Thank you!

    Reply
  39. Reese Ata says

    January 4, 2021 at 3:34 pm

    A solution to question 5

    A=list(map(float,input().split()))
    print(A)
    Reply
  40. Michel says

    September 1, 2020 at 3:08 pm

    A simple solution for exercise 6 : )

    f0 = open('test.txt', 'r')
    
    f = open('newTest.txt', 'w')
    
    count = 0
    for i in f0:
        if count != 5:
            f.write(i)
        count += 1
    
    </pre?
    Reply
  41. zizzygirl says

    August 27, 2020 at 2:18 am

    QUESTION8

    totalMoney= 1000
    quantity= 3
    price= 450

    print(“I have {} dollars so I can buy {} football for {} dollars.”.format(1000, 3, 4500))

    Reply
    • Joyson says

      December 14, 2020 at 2:30 am

      Your code is not logical, because what if i change the numbers from 1000, 3 , 4500 to something else what then…

      Reply
      • Qudus says

        December 31, 2020 at 2:39 pm

        Better way to do exercise 5

        b = []
        c = ['first', 'second', 'third','four','fifth']
        for i in c:
        	a = float(input(f'input {i} float: '))
        	b.append(a)
        print(b)
        Reply
  42. Chris says

    August 26, 2020 at 10:14 am

    Vishal can you help, when I try to run the question 10 code it gives error saying I don’t have the file or directory.

    Reply
    • Abhijit says

      September 21, 2021 at 11:18 am

      Hey Chris,

      Try to run it in your own IDE. First create a file with #text.txt on the same location where your python file is. Then run the code. Hope this helps!!!!!

      Reply
  43. Susmi Sharma says

    July 26, 2020 at 1:25 am

    Easy way to do Exercise 5.

    
    i = 0
    Floatnumbers = []
    while i != 5:
        ans = float(input("Enter a number:"))
        Floatnumbers.append(ans)
        i +=1
    print(f"The User list is {Floatnumbers}.")
    Reply
    • Chris says

      August 26, 2020 at 10:22 am

      Please, ok a beginner. What’s the use of the

       i += 1 
      Reply
      • shwetha says

        December 8, 2020 at 7:44 pm

        i+=1 is equivalent to i=i+1

        Reply
  44. rahat says

    July 15, 2020 at 1:42 pm

    #question-6

    
    with open("text.txt", "r") as f:
        lines = f.readlines()
    count = 0
    with open("newtext.txt", "w") as f:
        for i in lines:
            count+=1
            if count != 5:
                f.write(i)
    Reply
  45. Khalid says

    July 9, 2020 at 3:30 pm

    Question5:

    
    list1 = [12, 15, 32, 42, 55, 75, 122, 132, 150, 180, 200]
    
    for num in list1:
        if num <= 150 and num % 5 == 0:
            print(num)
    
    Reply
  46. code_teen says

    July 6, 2020 at 7:48 pm

    Easy solution for Question.5:

    
    list1= []
    for i in range(5):
        inputs = float(input())
        list1.append(inputs)
    print(list1,end = ' ')

    Output:

    12.34
    45.6
    78.9
    09.23
    56.89
    [12.34, 45.6, 78.9, 9.23, 56.89]
    Reply
    • code_teen says

      July 6, 2020 at 7:50 pm

      Actually, the indents are missed. Please, do check. Good Luck!

      Reply
  47. Khalid says

    July 6, 2020 at 4:13 pm

    Exercise 9

    
    file_name ="C:/Users/RUFAI/Desktop/new file.txt"
    
    with open(file_name) as file_object:
        content = file_object.read()
        if content == "":
            print("file is empty")
    
    Reply
  48. Khalid says

    July 6, 2020 at 3:43 pm

    Question6

    
    with open("Test file.txt") as file_object:
        content = file_object.readlines()
    count = 0
    for lines in content:
        count += 1
        if count != 5:
            print(lines.strip())
            with open("new file.txt", 'a') as file_obj:
                file_obj.write(lines)
    Reply
  49. Khalid says

    July 6, 2020 at 3:08 pm

    Excersice 5

    
    def enter_float_num():
        num_list = []
        print("Enter five float number at the prompt")
        while len(num_list) < 5:
            try:
                entry = float(input("Number entry: "))
                num_list.append(entry)
            except ValueError:
                print("Please enter a number")
        print(num_list)
    
    
    enter_float_num()
    
    Reply
  50. Angshumaan Basumatary says

    June 8, 2020 at 9:10 pm

    Question 6: As I am a beginner I had gone through three different styles of for loops to keep track of indexing.
    For the beginner:
    1) Refer to the manual solution of sir which might make you more aware of how indexing works though it’s confusing for newbies.
    2) Try using range() if you have understood the first solution. (Check out my code below using a range)
    3) Try using enumerate() and is the easiest I have come across.
    …….Here is the code given below using range

    with open("test.txt", "r") as f:
        a = f.readlines()
    with open("newFile.txt", "w+") as f:
        for line in range(0, len(a)):
            if line == 4:
                continue
            else:
                f.write(a[line])
     
    Reply
  51. Kid trying to learn Python says

    June 5, 2020 at 10:21 am

    Hey Vishal, in the last ones, once I was done, I look at the solutions. I think you should do Variables and inputs, No DEF Functions. Thanks.

    Reply
  52. Kid trying to learn Python says

    June 5, 2020 at 10:16 am

    Thanks Vishal. Please Answer. Tomorow(Today Was 6/4/202).
    Help.

    Reply
  53. Kid trying to learn Python says

    June 5, 2020 at 10:10 am

    What Does Exercise Question 8 mean, Mr. Vishal, or should I call You just Vishal.

    quantity = 3
    totalMoney = 1000
    price = 450
    

    Huh?

    Reply
    • Vishal says

      June 8, 2020 at 9:19 am

      Hey, It means how you can use string.format() method to display variables

      Reply
      • Murga says

        June 20, 2020 at 2:58 am

        ???????????I NEED HELP PLEASE!
        Write a program that asks the user for a number, then prints out the numbers from 1 to that number, one on each line:

        Enter a number: 10
        1
        2
        3
        4
        5
        6
        7
        8
        9
        10
        ​

        Reply
        • killerrbot says

          July 19, 2020 at 11:15 am

          for num in range(10):
              print (num+1, end=" ")
              print("\n")
          Reply
          • hokaiseig says

            August 3, 2020 at 3:39 pm

            index =input("enter a number")
            for num in range(index):
                  print(str(num+1)+"\n")
          • shami says

            August 22, 2020 at 4:13 pm

            for num in range(1,11):
                print(num)
        • Danilo says

          November 4, 2021 at 8:24 pm

          user_num = int(input('Enter your number: '))
          for i in range(1, user_num + 1):
              print(i)
          Reply
    • Tousif says

      August 20, 2020 at 10:22 am

      Q:display above data using string.format() method

      output : I have 1000 dollars so I can buy 3 football for 450.00 dollars

      Answer :
      totalMoney = 1000
      quantity = 3
      price = 450

      statement1 = “I have {1} dollar so I can buy {0} football for {2:.2f} dollars.”
      print(statement1.format(quantity, totalMoney, price))

      Reply
  54. Parag Khedikar says

    May 25, 2020 at 5:42 pm

    Solution 5 :

    def acceptfloatValue():
        lst = []
        for i in range(5):
            lst.append(float(input()))
        return lst
    
    print('List is :',acceptfloatValue())
    
    
    		
    Reply
  55. Parag K says

    May 25, 2020 at 5:03 pm

    Question 4:

    def add():
        a = float(input())
        b = float(input())
        return a+b
    
    
    print("Values: ", add().__format__('.2f'))
    
    Reply
  56. Boris says

    May 17, 2020 at 8:45 pm

    Question 6, different way, without enumerate

     text1=open("myfile.txt","r")
    lines=text1.readlines()
    del lines[4]
    print(lines)
    text2=(open("newfile.txt","w"))
    for i in range(len(lines)):
     text2.write(str(lines[i]))
    text2.close()
    Reply
  57. Nikhil K says

    April 27, 2020 at 11:16 pm

    For Q:6

    testFile = open("test.txt","r")
    newFile = open("newFile.txt", "w+")
    
    for num, line in enumerate(testFile, 1):
        if num == 5:
            continue
        else:
            newFile.write(line)
    
    
    Reply
    • Ramneek says

      May 6, 2020 at 5:19 pm

      Thanks for introducing enumerate.

      Reply
    • manpreet says

      August 23, 2023 at 11:13 am

      with open(“f1.txt”,”r”) as f:
      data=f.read()
      data1=data.removeprefix(“line1”)
      with open(“f3.txt”,”w”) as f:
      data3=f.write(data1)
      print(data3)

      Reply
  58. nikhil k says

    April 27, 2020 at 10:29 pm

    for Ex. 1

    print((int(input("Enter first number: ")))*(int(input("Enter second number: "))))
    
    Reply
  59. Yasin says

    April 27, 2020 at 12:45 am

    For exercise 6, here is an alternative solution:

    testFile = open("test.txt","r")
    newFile= open("newFile.txt", "w+")
    
    for num, line in enumerate(testFile, 1):
        if num != 5:
            newFile.write(line)
      
    Reply
    • Vishal says

      April 27, 2020 at 4:39 pm

      Thank you, Yasin

      Reply
  60. kevin says

    April 15, 2020 at 5:06 am

    Hi, can we use this online code editor to read files from our computer? If so, how can we do that?

    Reply
    • Vishal says

      April 15, 2020 at 9:31 pm

      Hi Kevin, there is a small “upload button” on the right side of the text editor where you can upload your files. You need to import it in main.py to call its functions. Or if you have other files than .py just upload it and read it in main.py

      Reply
  61. A says

    March 4, 2020 at 12:00 pm

    Hi,
    What does question 2 mean?

    Reply
    • Vishal says

      March 4, 2020 at 5:18 pm

      Hi, It means we need to use Use print() statement formatting to display ** separator between each word. I have updated the question with more description.

      Reply
      • patrick says

        April 7, 2020 at 5:27 pm

        i am finding it so hard dont mind if u can hlp me out

        Reply
        • Vishal says

          April 8, 2020 at 2:51 pm

          Hey Patrick, Please let me know the problem you are facing

          Reply
      • Levie says

        February 25, 2024 at 3:13 pm

        Help me i want to try please

        Reply
  62. Nifdi says

    February 29, 2020 at 8:28 am

    Question 7 is not working. It gives an error.

    Reply
    • Vishal says

      March 1, 2020 at 12:38 pm

      Hi, It is working on our end. You need to enter three strings separated by spaces when a program executes.

      Reply

Leave a Reply Cancel reply

your email address will NOT be published. all comments are moderated according to our comment policy.

Use <pre> tag for posting code. E.g. <pre> Your entire code </pre>

In: Python Python Basics Python Exercises
TweetF  sharein  shareP  Pin

  Python Exercises

  • All Python Exercises
  • Basic Exercise for Beginners
  • Intermediate Python Exercises
  • Input and Output Exercise
  • Loop Exercise
  • Functions Exercise
  • String Exercise
  • Data Structure Exercise
  • List Exercise
  • Dictionary Exercise
  • Set Exercise
  • Tuple Exercise
  • Date and Time Exercise
  • OOP Exercise
  • File Handling Exercise
  • Python JSON Exercise
  • Random Data Generation Exercise
  • NumPy Exercise
  • Pandas Exercise
  • Matplotlib Exercise
  • Python Database Exercise

 Explore Python

  • Python Tutorials
  • Python Exercises
  • Python Quizzes
  • Python Interview Q&A
  • Python Programs

All Python Topics

Python Basics Python Exercises Python Quizzes Python Interview Python File Handling Python OOP Python Date and Time Python Random Python Regex Python Pandas Python Databases Python MySQL Python PostgreSQL Python SQLite Python JSON

About PYnative

PYnative.com is for Python lovers. Here, You can get Tutorials, Exercises, and Quizzes to practice and improve your Python skills.

Follow Us

To get New Python Tutorials, Exercises, and Quizzes

  • Twitter
  • Facebook
  • Sitemap

Explore Python

  • Learn Python
  • Python Basics
  • Python Databases
  • Python Exercises
  • Python Quizzes
  • Online Python Code Editor
  • Python Tricks

Coding Exercises

  • C Exercises
  • C++ Exercises
  • Python Exercises

Legal Stuff

  • About Us
  • Contact Us

We use cookies to improve your experience. While using PYnative, you agree to have read and accepted our:

  • Terms Of Use
  • Privacy Policy
  • Cookie Policy

Copyright © 2018–2026 pynative.com

深圳市网捷达科技有限公司 联系电话:18910898173;

ICP备案号:粤ICP备2024312167号-2

Copyright © 网捷达 版权所有