2017-06-10 2 views
0

私はuser_input.lower()を追加しましたが、このコードはW、M、Sの入力として期待される出力を与えません。なぜ誰かが私の説明をしてくれますか?PythonでStringメソッドの概念を適用するには?

# Password Generator 
import random 
import string 

print('----------------PASSWORD GENERATOR-------------------') 

print('''We will help you to generate 3 types of passwords 
1. Weak passwords : It will consist 4 alphabets. 
2. Moderate passwords: It will consist 7 alphanumeric characters. 
3. Strong Passwords : It will consist 10 alphanumeric and symbol  
characters.''') 


while True: 
     user_input = input(''' 
    What type of password you need? 
    Enter "W" for weak password 
    Enter "M" for moderate password 
    Enter "S" for strong password\n''') 

    # To reduce chances of error if user gives command in upper or lower case. 
     user_input.lower() 


     if user_input is 'w': 
      alphabet = string.ascii_letters # string.digits + string.punctuation 
      password = ''.join(random.choice(alphabet) for i in range(4)) 
      print(password) 
      break 

     elif user_input is 'm': 
      alphabet = string.ascii_letters + string.digits # string.punctuation 
      password = ''.join(random.choice(alphabet) for i in range(7)) 
      print(password) 
      break 

     elif user_input is 's': 
      alphabet = string.ascii_letters + string.digits + string.punctuation 
      password = ''.join(random.choice(alphabet) for i in range(10)) 
      print(password) 
      break 

     else: 
      print('Please enter a valid choice') 
+1

正確に何を期待しているのか明確にする必要がありますが、string.lowerは新しい文字列を返します。変更している文字列は変更されません。文字列は不変です。一度作成すると変更することはできません。 また、あなたは==そうではありません。オブジェクトアイデンティティーのチェックが等価でないかどうか。 's' == 's'はTrue、 's'は 's'はFalseです。 –

答えて

0

これは、 ".lower()"を使用すると実際に出力を変数に保存していないためです。変数に保存するには、 "user_input = user_input.lower()"を実行する必要があります。

+0

これを拡張するために、Pythonのplaceメソッドは常にNoneを返します。非インプレース(文字列メソッド)の変更は値を返します。つまり、a = a.append(1)はリストが変更されたときにNoneを返します。 b = b.lower()は、文字列全体に適用されるb.lower()の値を返します。 – Rosh

関連する問題