Get rid of for line in afile:
, and take out what was in it. Also, because input
returns a string in Python 3, convert it to an int
first. And you are trying to write an integer to a file, when you have to write a string.
This is what it should look like:
afile = open["Random.txt", "w" ]
for i in range[int[input['How many random numbers?: ']]]:
line = str[random.randint[1, 100]]
afile.write[line]
print[line]
afile.close[]
If you are worried that the user might input a non-integer, you can use a try/except
block.
afile = open["Random.txt", "w" ]
try:
for i in range[int[input['How many random numbers?: ']]]:
line = str[random.randint[1, 100]]
afile.write[line]
print[line]
except ValueError:
# error handling
afile.close[]
What you were trying to do was iterate through the lines of afile
, when there were none, so it
didn't actually do anything.
Permalink
Tệp này chứa văn bản unicode hai chiều có thể được giải thích hoặc biên dịch khác với những gì xuất hiện dưới đây. Để xem xét, hãy mở tệp trong một trình soạn thảo cho thấy các ký tự Unicode ẩn. Tìm hiểu thêm về các ký tự unicode hai chiều
# Chương 6 | |
# 07. Người viết tệp số ngẫu nhiên | |
Hậu thế random | |
defwrite []: write[]: | |
object_file = open ['Random_numbers.txt', 'w'] = open['random_numbers.txt', 'w'] | |
How_many = int [Input ['Nhập một số dưới dạng số nguyên có bao nhiêu số ngẫu nhiên' = int[input['Enter a number as a integer how many random number' | |
'Tệp sẽ giữ:']]]] | |
foriinrange [how_many]: i in range[how_many]: | |
Number = Random.RandRange [1, 501] = random.randrange[1, 501] | |
number = str [số] = str[number] | |
object_file.write [số].write[number] | |
object_file.write ['\ n'].write['\n'] | |
object_file.close [].close[] | |
viết[][] |
Viết một chương trình viết một loạt các số ngẫu nhiên vào một tệp. Mỗi số ngẫu nhiên phải nằm trong phạm vi từ 1 đến 500. Ứng dụng sẽ cho phép người dùng chỉ định có bao nhiêu số ngẫu nhiên mà tệp sẽ giữ.
Thiết kế và viết một chương trình Python mô -đun: Đặt tên cho tệp đầu ra "RandomNumber.txt"
Name the output file "randomNumber.txt"
#Xem các mô -đun cần thiết nhập ngẫu nhiên #Define hàm main [] def main []: & nbsp; & nbsp; #prompt người dùng nhập số & nbsp; & nbsp; n = int [input ["Vui lòng nhập số số ngẫu nhiên sẽ được giữ trong một tệp:"]] & nbsp; & nbsp; #create một tệp văn bản mới & nbsp; & nbsp; outfile = open ["RandomNumber.txt", "w"] & nbsp; & nbsp; #Write Số trong tệp văn bản [RandomNumber.txt] & nbsp; & nbsp; cho i trong phạm vi [n]: & nbsp; & nbsp; & nbsp; & nbsp; outfile.write [str [ngẫu nhiên.randint [1.500]]+"\ n"] & nbsp; & nbsp; #close tệp & nbsp; & nbsp; Outfile.close [] #Call Main Main []
import random
#define the main[] function
def main[]:
#prompt the user to enter the numbers
n
=int[input["Please enter the number of random number to be hold in a file: " ]]
#create a new text file
outfile =open["randomNumber.txt","w"]
#write the number in the text file[randomNumber.txt]
for i in range[n]:
outfile.write[str[random.randint[1,500]]+"\n"]
#close the file
outfile.close[]
#call the main
main[]
Bài tập này giả định rằng bạn đã hoàn thành chương trình Bài tập 7, người viết tệp số ngẫu nhiên. Viết một chương trình khác đọc các số ngẫu nhiên từ tệp, hiển thị các số và sau đó hiển thị dữ liệu sau: • Tổng số số • Số số ngẫu nhiên được đọc từ tệp
• The total of the numbers
• The number of random numbers read from the file
Thiết kế và viết một chương trình Python mô-đun để đáp ứng các yêu cầu của bài tập lập trình #6-8.
#Main Finction def main []: & nbsp; & nbsp; tệp #open để đọc & nbsp; & nbsp; infile = open ['RandomNumber.txt', 'r'] & nbsp; & nbsp; #varaibel để lưu trữ tổng và đếm số & nbsp; & nbsp; Tổng số = 0 & nbsp; & nbsp; Đếm = 0 & nbsp; & nbsp; #Loop Sử dụng để đọc tất cả các số từ tệp văn bản & nbsp; & nbsp; cho dòng trong Infile: & nbsp; & nbsp; & nbsp; & nbsp; #đọc các số tạo thành văn bản & nbsp; & nbsp; & nbsp; & nbsp; num = int [dòng] & nbsp; & nbsp; & nbsp; & nbsp; #display số & nbsp; & nbsp; & nbsp; & nbsp; in ['số:'+định dạng [num, '. 2f']] & nbsp; & nbsp; & nbsp; & nbsp; & nbsp; & nbsp; Tổng+= num & nbsp; & nbsp; & nbsp; & nbsp; Đếm+= 1 & nbsp; & nbsp; #close tệp & nbsp; & nbsp; & nbsp; & nbsp; infile.close [] & nbsp; & nbsp; #Display trở lại tổng và bộ đếm & nbsp; & nbsp; in [''] & nbsp; & nbsp; in ["Tổng số các số:", tổng số] & nbsp; & nbsp; In ["Số lượng số ngẫu nhiên được đọc từ tệp:", đếm]
def main[]:
#open file to read
infile =
open['randomNumber.txt','r']
#varaibel to store sum and count the numbers
total =0
count=0
#loop use to read all numbers from text file
for line in infile:
#read the numbers form the text
num = int[line]
#display the number
print['Number: '+format[num,'.2f']]
total+=num
count+=1
#close the file
infile.close[]
#display back the sum and counter
print[' ']
print["The total of the numbers: ",total]
print["The number of random numbers read from the file: ",count]
chính[]
Sửa đổi chương trình bạn đã viết cho Bài tập 6 để nó xử lý các ngoại lệ sau: • Nó nên xử lý các ngoại lệ ioerror được nêu ra khi tệp được mở và dữ liệu được đọc từ nó. • Nó sẽ xử lý bất kỳ trường hợp ngoại lệ giá trị nào được nâng lên khi các mục được đọc từ tệp được chuyển đổi thành một số. 1. Tải xuống và lưu tệp đính kèm "ExceptionNumbers.txt" vào đĩa máy tính của bạn. 2. Thiết kế và viết một chương trình Python mô -đun để đọc tệp đĩa và tính toán các mục sau: & nbsp; & nbsp; số lượng số trong tệp & nbsp; & nbsp; số lượng các mục không phải là số trong tệp & nbsp; & nbsp; Tổng số các số & nbsp; & nbsp; trung bình của các số
• It should
handle IOError exceptions that are raised when the file is opened and data is read from it.
• It should handle any ValueError exceptions that are raised when the items that are read from the file are converted to a number.
1. Download and save the attached file "exceptionNumbers.txt" to your computer disk.
2. Design and write a modular python program to read the disk file and calculate the following:
the count of numbers in the file
the count of
non-numeric items in the file
the total of the numbers
the average of the numbers
3. Chương trình sẽ có thể xử lý bất kỳ ngoại lệ ioerror nào được nêu ra khi tệp được mở và dữ liệu được đọc, tức là các tệp bị thiếu, v.v.
4. Chương trình nên xử lý các ngoại lệ giá trị được nâng lên khi các mục được đọc và không thể chuyển đổi thành một số.
5. Đầu ra của bạn phải chứa các thông tin sau:
Có 1 mục không phải là số trong tệp Có 7 số trong tệp tổng số các số là: 141.0 Trung bình của các số là: 20,14
There were 7 numbers in the file
The total of the numbers was: 141.0
The average of the numbers is: 20.14
#Main function def main []: & nbsp; & nbsp; #Declare và khởi tạo các biến & nbsp; & nbsp; Đếm = 0 & nbsp; & nbsp; Tổng số = 0 & nbsp; & nbsp; #Try Statemnt để xử lý các ngoại lệ tệp văn bản & nbsp; & nbsp; thử: & nbsp; & nbsp; & nbsp; & nbsp; object_file = open ['ExcityNumbers.txt', 'r'] & nbsp; & nbsp; Câu lệnh #except để xử lý lỗi giá trị & nbsp; & nbsp; ngoại trừ ioerror: & nbsp; & nbsp; & nbsp; & nbsp; in ['ioerror'] & nbsp; & nbsp; ngoại trừ valueError: & nbsp; & nbsp; & nbsp; & nbsp; in ['valueError'] & nbsp; & nbsp; khác: & nbsp; & nbsp; & nbsp; & nbsp; #Make Tăng giá trị của Đếm và thêm giá trị & NBSP; & nbsp; & nbsp; & nbsp; cho tôi trong object_file: & nbsp; & nbsp; & nbsp; & nbsp; & nbsp; & nbsp; & nbsp; & nbsp; tổng += int [i] & nbsp; & nbsp; & nbsp; & nbsp; & nbsp; & nbsp; & nbsp; & nbsp; đếm += 1 & nbsp; & nbsp; #Display trung bình & nbsp; & nbsp;# print ["Có [] các mục không số trong tệp he"] & nbsp; & nbsp;# print ["Có [] số trong tệp"] & nbsp; & nbsp; #print ["Tổng số anh ấy là:", định dạng [tổng số, '. 2f']] & nbsp; & nbsp; in ["Trung bình của tất cả các số trong tệp là:", định dạng [tổng / đếm, '. 2f']] & nbsp; & nbsp; object_file.close [] main []
def main[]:
#declare and initialize variables
count = 0
total = 0
#try statemnt to handle text file exceptions
try:
object_file = open['exceptionNumbers.txt', 'r']
#except statement to handle value error
except IOError:
print['IOError']
except ValueError:
print['ValueError']
else:
#make increment in value of count and and add value
for i in object_file:
total += int[i]
count += 1
#display
average
# print["There were [ ]non-numberic items in he file"]
# print["There were [ ]numbers in the file"]
#print["The total of he numbers was: ", format[total,'.2f']]
print["The average of all the numbers in the file is: ",format[total / count,'.2f']]
object_file.close[]
main[]
- Ngoại lệNumbers.txt
Những giải pháp này có thể cung cấp các giải thích giải quyết vấn đề từng bước hoặc các ví dụ viết tốt bao gồm các phong cách hiện đại về định dạng và xây dựng các thư mục ra khỏi trích dẫn văn bản và tài liệu tham khảo. Học sinh có thể sử dụng các giải pháp này để xây dựng kỹ năng cá nhân và thực hành. Sử dụng phi đạo đức là nghiêm ngặt bị cấm.
# Nhập các mô -đun cần thiết nhập ngẫu nhiên
import random
# Xác định hàm chính def main []: & nbsp; & nbsp; # nhắc người dùng nhập các số & nbsp; & nbsp; n = int [input ["Vui lòng nhập số số ngẫu nhiên sẽ được giữ trong một tệp:"]]]
def main[]:
# prompt the user to enter the numbers
n = int[input["Please enter the number of random numbers to be hold in a file: "]]
& nbsp; & nbsp; # Tạo một tệp văn bản mới & nbsp; & nbsp; Outfile = Open ["RandomNumbers.txt", "W"]
outfile =
open["randomNumbers.txt", "w"]
& nbsp; & nbsp; # ghi số trong tệp văn bản & nbsp; & nbsp; cho i trong phạm vi [n]: & nbsp; & nbsp; & nbsp; & nbsp; Outfile.Write [str [Random.randint [1, 500]] + "\ n"]
for i in range[n]:
outfile.write[str[random.randint[1, 500]] + "\n"]
& nbsp; & nbsp; # Đóng tệp & nbsp; & nbsp; Outfile.close []
outfile.close[]
# Gọi hàm chính Main [] ...
main[]...
Đây chỉ là một bản xem trước của giải pháp. Vui lòng sử dụng nút Mua hàng để xem toàn bộ giải pháp
Bằng cách mua giải pháp này, bạn sẽ có thể truy cập các tệp sau: Solution.zip.
Solution.zip.