2015-10-27 110 views
-2

我正在嘗試寫入文本文件,並且遇到一些問題。我想寫入一個文本文件,並在每行上都有一個名稱,一個費率和工作小時數,每一行都顯示在一行上。我希望顯示一條錯誤消息,並讓用戶輸入另一個值,如果用戶沒有輸入字符串作爲名稱,並且他們沒有輸入5到50之間的值, 100小時。我只是不能想到在這一點上該做什麼。向用戶顯示錯誤消息

這裏是我的代碼,感謝

confirmation = (input("Would you like to add to the payroll file? Enter y for yes, or any other key to end operation: ")) 

while confirmation == "y": 
name = f.write(str(input("What is the employees name?: "))) 

    while name != str: 
    name = f.write(str(input("Please enter a name: "))) 
    f.write(" ") 

    rate = f.write(input("What is the employees hourly rate?: ")) 
    f.write(" ") 

    hours = f.write(input("How many hours did the employee work?: ")) 
    hours = float (hours) 

    f.write(str("\n"))  
    confirmation = (input("Would you like to keep adding to the payroll file? Enter y for yes, or any other key to end operation: "))  


print ("File Closed") 

f.close() 
+1

檢查輸入以查看它是否在可接受的數字範圍內,如果沒有,則顯示消息。 – Andy

+0

確實。你正在尋找一個「if-then-else」結構。 –

+0

我已經嘗試過,但是當我使用if語句時,只會在出現錯誤時重複一次。例如rate = f.write(input(「什麼是員工小時工資率:」)) rate = float(rate) if rate < 5 or rate > 50: rate = f.write(input(「Please enter value between 5 -50:「))只會在一次出現錯誤時顯示,然後繼續前進。 – djmistaspot

回答

0


input()功能已經返回一個字符串。你不需要str()

你的語法while name != str是錯誤的 - 如果你需要檢查它是否是一個字符串,你應該使用isinstance(name, str)

write()函數不返回任何東西。當你等於你的f.write()函數,你會等於零。