だから私はあなたが電流と基数を持っていて、あなたの電流と基数を「10進数、8進数など」に変換できるはずの変換プログラムに取り組んでいます。私は基本的にプログラムを完了しましたが、新しい電流またはベースに更新する新しい電流またはベースのユーザー入力を取得しようとする最後のメソッドを実装する方法に困惑しています。
皆さん、ありがとうございました!
class numberConverter:
def __init__(self, current=0, base=10):
self.__current = current
self.__base = base
def print(self):
print("Current set to:",
self.__current, "Base set to:", self.__base)
def menu(self):
return("\n'S'et\n'C'urrent\n'B'inary\n'H'ex\n'O'ctal\n'D'ecimal\n'q'uit: ")
#Converts to Hexidecimal
def convHex(self):
print("Hex Conversion Commencing")
print("Converting:", self.__current, "Base", self.__base, "to Base 16")
self.__current = format(int(str(self.__current), self.__base), '02X')
self.__base = 16
self.print()
#Converts to Octal
def convOct(self):
print("Octal Conversion Commencing")
print("Converting:", self.__current, "Base", self.__base, "to Base 8")
self.__current = format(int(str(self.__current), self.__base), '02o')
self.__base = 8
self.print()
#Converts to Decimal
def convDec(self):
print("Decimal Conversion Commencing")
print("Converting:", self.__current, "Base", self.__base, "to Base 10")
self.__current = format(int(str(self.__current), self.__base))
self.__base = 10
self.print()
#Converts to Binary
def convBinary(self):
print("Binary Conversion Commencing")
print("Converting:", self.__current, "Base", self.__base, "to Base 2")
self.__current = format(int(str(self.__current), self.__base), '02b')
self.__base = 2
self.print()
#Change the current value or base
#This is the section I am trying to work on
def setCurrent(self):
userInput = str(input("Set 'C'urrent or 'B'ase: "))
if userInput.upper() == "C":
print(input("Enter new current value: "))
elif userInput.upper() == "B":
print(input("Enter new base value: "))
num1 = numberConverter(14,10)
select = ""
while select !='q':
select = input(num1.menu())
if select == "C":
num1.print()
if select == "H":
num1.convHex()
if select == "O":
num1.convOct()
if select == "D":
num1.convDec()
if select == "B":
num1.convBinary()
if select == "S":
num1.setCurrent()
ここでの主な問題は、入力フィルタリングにあるようです。この質問を読む必要があります; これは、一般的に入力をフィルタリングする方法の良い例を提供します。
あなたの場合、次のようなものを実装できます。
def setCurrent(self):
userInput = str(input("Set 'C'urrent or 'B'ase: "))
if userInput.upper() == "C":
while True:
try:
value = int(input("Enter new current value: "))
break
except ValueError:
print("Invalid number!")
self.__current = value
elif userInput.upper() == "B":
while True:
base = input(self.menu())
if base in "HODB":
break
else:
print('Base must be "H", "O", "D", or "B"!')
if base == "H":
self.convHex()
elif base == "O":
self.convOct()
elif base == "D":
self.convDec()
elif base == "B":
self.convBinary()
また、更新する必要がありますself.menu()
; 別のメソッドとして保持するのではなく、このメソッドに文字列を追加します。
PEP-8を読む必要があります; これはPythonの標準スタイルガイドであり、他の人がコードを読みやすく、使いやすくすることができます。また、CodeReview.SEに(完成した)コードを投稿することも検討します(トピックに関するガイドラインを必ずお読みください)。現在のコードに加えることができる他の多くの改善があり、あなたは多くを学ぶでしょう。
この記事はインターネットから収集されたものであり、転載の際にはソースを示してください。
侵害の場合は、連絡してください[email protected]
コメントを追加