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
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
Explanation to Solution:
- Comma Separation: In Python’s
print(), commas signify different objects to be printed. sep='***': By default,sepis 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
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
10because 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
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
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
Explanation to Solution:
:x: The hexadecimal type code. Hex uses sixteen symbols: 0–9 and a–f.- Case Sensitivity: Using lowercase
xresults inff, while uppercaseXwould result inFF. 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
Explanation to Solution:
%.2f: Thefstands for “float,” and the.2tells 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
Explanation to Solution:
percentage:.2f: Inside the curly braces of an f-string, the:.2fpart 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
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
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
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
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
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.,.70instead 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
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
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
Explanation to Solution:
- String Comparison: Notice we compare
choice == "1". Sinceinput()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
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
pwdstill 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:
Solution
Explanation to Solution:
readlines(): This is a memory-efficient way to capture the entire structure of a file.\nin 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
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
Explanation to Solution:
- Memory Efficiency: Instead of using
f.readlines()(which loads the entire file into RAM),for line in freads 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
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
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
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.

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()
oops. “new.write(i)” should be indented!!
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)))
#exercise2
class exercise2:
def display(self):
a=”Name”
b=”Is”
c=”James”
print(a,b,c, sep=” **”)
ex2=exercise2()
ex2.display()
#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()
EXERCISE 5 SOLUTION
numbers = []
while True:
item = (float(input(“enter a float”)))
numbers.append(item)
if len(numbers) == 5:
break
print (numbers)
def exe_four():
num = int(float(input(“Enter the number : “)))
res = format(num, ‘.2f’)
print(res)
exe_four()
//** I am not getting expected output **//
Question 10
with open(r”newone”,”r”) as file:
lines = file.readlines()
for i in range(len(lines)):
if i == 3:
print(lines[i])
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)
Question 7
user = input(“Enter three string: “).split(” “)
count = 1
for i in user:
print(f”Name{count} : {i}”)
count = count + 1
names = input(“Enter three names separated by a space: “).split()
for i, name in enumerate(names, 1):
print(f”Name{i}: {name}”)
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)
The solution to exercise 5 appears outside of the ‘+ solution’ box
yahoo
my brain is no morre
$exercise 1
x = input(“1st number here “)
y = input(“2nd number here “)
z = (int(x)*int(y))
print(z)
nice one bro.
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
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
Thanks Divya
#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])
#9
with open('one.txt', 'r') as one:print(len(one.read()) != 0)
YESS MATTTE
#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
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
wtf do i neet to add tags for every line? what a dumb comments area, incredible
*need
Just add your entire code inside a pre tag
tag
Question 3:
def exe_three():
num = int(float(input(“Enter the number : “)))
res = oct(num)
print(res)
exe_three()
#5
print(['%.1f' % float(input()) for _ in range(5)])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"))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}')
QUESTION 5:
numbers = [ ]for i in range(5):
print('Enter a number at location', i, ":")
number = float(input())
numbers.append(number)print('Userlist:', numbers)
Q:5
question-5 Here is an alternative solution
?
it’s not work
silution for exercise7
user = input(“Enter three string: “).split(” “)
count = 1
for i in user:
print(f”Name{count} : {i}”)
count = count + 1
I have a problem while solving exercise 10. The Below code will not work properly but shows the wrong result.
/is escape character in python1. Write a program to accept two numbers from the user and calculate multiplication
2.
# or
3.
4.
5.
6.
7.
8.
9.
#2 solution
**You can do this way also**
# YOU CAN ALSO DONE THIS WITH F-STRINGS:
in your code the price isn’t a float number
put
{price:.2f}i don’t understood it
question 1 says to calculate multiplication but the given solution returns sum. also, it converts float inputs to int.
# Read line number 4 from the following file
In Exercise 1 the question is for multiplication but Ans is giving in Sum.
i can do this just by this simple code :
output:
That’s true, but it would be one string, not three.
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:
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
nothing like
.fand.2fIn bracket you should write
{mon}, {q}, {pr}respectively.and before ‘I have put f to use fstringstry with this f single character will not support
for decimal point
Can someone explain to me how the solution for exercise 4 works? I don’t know what ‘%o’ means.
so we find 8 octal number so we use %o is given octal number
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 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
This was a fun exercise. Thank you! Here’s how I approached this challenge:
rounds += 1
Great exercises, Thank you!
A solution to question 5
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?QUESTION8
print(“I have {} dollars so I can buy {} football for {} dollars.”.format(1000, 3, 4500))
Your code is not logical, because what if i change the numbers from 1000, 3 , 4500 to something else what then…
Better way to do exercise 5
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.
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!!!!!
Easy way to do Exercise 5.
Please, ok a beginner. What’s the use of the
i+=1is equivalent toi=i+1#question-6
Question5:
Easy solution for Question.5:
Output:
Actually, the indents are missed. Please, do check. Good Luck!
Exercise 9
Question6
Excersice 5
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
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.
Thanks Vishal. Please Answer. Tomorow(Today Was 6/4/202).
Help.
What Does Exercise Question 8 mean, Mr. Vishal, or should I call You just Vishal.
Huh?
Hey, It means how you can use
string.format()method to display variables???????????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
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))
Solution 5 :
def acceptfloatValue(): lst = [] for i in range(5): lst.append(float(input())) return lst print('List is :',acceptfloatValue())Question 4:
def add(): a = float(input()) b = float(input()) return a+b print("Values: ", add().__format__('.2f'))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()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)Thanks for introducing enumerate.
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)
for Ex. 1
print((int(input("Enter first number: ")))*(int(input("Enter second number: "))))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)Thank you, Yasin
Hi, can we use this online code editor to read files from our computer? If so, how can we do that?
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
.pyjust upload it and read it in main.pyHi,
What does question 2 mean?
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.i am finding it so hard dont mind if u can hlp me out
Hey Patrick, Please let me know the problem you are facing
Help me i want to try please
Question 7 is not working. It gives an error.
Hi, It is working on our end. You need to enter three strings separated by spaces when a program executes.