Python3 if if else - python-3.x

When i do this in this way
x = "Hello"
if len(x) <= 9:
print("The password must contain at least 9 letters")
if x[0].islower():
print("The first password letter must be uppercase")
else:
print("Password saved")
password = x
i getting
>The password must contain at least 9 letters
>Password saved
What should I do to make the program stop on:
>The password must contain at least 9 letters

Use elif between if and else:
x = "Hello"
if len(x) <= 9:
print("The password must contain at least 9 letters")
elif x[0].islower():
print("The first password letter must be uppercase")
else:
print("Password saved")
password = x
elif is executed only when if wasn't executed, and elif's condition is true. You can also chain as many elifs as you want, in which case the first elif whose condition matches is executed.
Update: Since OP said in comments that he wants all errors to be shown at once, I would use something like this:
x = "Hello"
errors = []
if len(x) <= 9:
errors.append("The password must contain at least 9 letters")
if x[0].islower():
errors.append("The first password letter must be uppercase")
if errors:
print('\n'.join(errors))
else:
print("Password saved")
password = x

The problem is that you have two if filters in the code. I'm assuming you want the structure where both "The password must contain at least 9 letters" and "The first password letter must be uppercase"can be returned if both their conditions are met.
If, however, you don't need this capability, simply replace the second if with an elif and it should work.
If you need this capability, try something like:
x = "Hello"
if len(x) <= 9:
print("The password must contain at least 9 letters")
if x[0].islower():
print("The first password letter must be uppercase")
if len(x) >= 9 and x[0].isupper():
print("Password saved")
password = x
This simply adds a third if statement testing that the previous conditions were fulfilled.

Related

Why does my if statement return the wrong prompt?

I am sure the answer is right in front of my face but I can't seem to figure out how to fix the return on my first if statement when I input the right conditions.
create_password = input("Enter password here: ")
if len(create_password) > 6 and create_password.isdigit() > 0:
print("Your account is ready!")
elif len(create_password) < 6 and create_password.isdigit() < 1:
print("Password must be more than 6 characters and must include a number")
elif len(create_password) > 6 and create_password.isdigit() == 0:
print("Password must include a number")
else:
print("Your password sucks")
Let's say I enter elephant100, I am trying to get the prompt to be "Your account is ready!". But to my dismay, it prints "Password must include a number" and I cannot figure out why. My other conditions match the right input but that is the only one that does not work.
.isdigit() method returns True if all the characters are digits, otherwise False. Hence it returns False in this case since your string contains letters like e, l, p etc. So the statement print("Your account is ready!") will never be executed.
Turns out I needed to use isalnum(), isnumeric(), and isalpha() to fix my problem. Thank you Muhammed Jaseem for helping me figure it out! Here is my revised code.
if create_password.isnumeric() == True:
print("Password must be more than 6 characters and include letters")
elif create_password.isalpha() == True:
print("Password must be more than 6 characters and include numbers")
elif len(create_password) > 6 and create_password.isalnum() == True:
print("Your account is ready!")
else:
print("Your password sucks. Must be more than 6 characters and contain only letters and numbers")

Is there a way to return to input if condition is not met in python?

What i am trying to do do is this.
1.User Inputs a number (for example a SSN or any Identification number)
2.If the user is not 14 digits, return to the input and try again
3.If Input is 14 digits, continue in program.
4.Check if SSN starts with 1 or 2 (in my scenario all male ID start with 1 and all female ID start with 2
5. If 1 print male if 2 print female.
My last code is:
ssn=str(input("SSN: "))
x=len(ssn)
while x != 14:
print("Wrong digits")
break
else:
print("Thank you")
y=str(ssn[0])
if y == 1:
print("Male")
else:
print("ok")*
In execution i get:
SSN: 12345
Wrong digits
ok
The problem is that this does not break if i input 12 digits. It does say wrong digits but continues to in the execution.
Second problem is that it prints ok even though i added 1234 which starts with 1 and it should be male.
Any ideas on this please?
First str(input(...)) is unnecessary, as input already returns a string (why convert string to a string ?). Second, you update neither ssn nor x. Third, while x != 14 will run only as long as x is unequal 14. But you want it to do some processing when x is equal 14. Fourth, 1 == "1" will always be False. Following code should work:
while True: # endless loop
ssn = input("SSN : ")
if not ssn.isdigit(): # if the ssn is not a number, stop
print("not a number")
continue # let the user try again
l = len(ssn)
if len(ssn) != 14:
print("Wrong digits")
continue # let the user try again
else:
print("Thank you")
if ssn[0] == "1":
print("Male")
else: # This will print Female even if first ID digit is 3 or 4 or whatever, should use elif ssn[0] == "2"
print("Female")
break # stop asking again
another shorter and cleaner way to do this is by using regular expressions:
import re
while True:
SSN = input('Enter number:')
if re.match('1\d{13}',SSN): # 1 + 13 digits
print('Male')
break
elif re.match('2\d{13}',SSN):# 2 + 13 digits
print('Female')
break
elif re.match('\d{14}',SSN): # 14 digits
print('Thank you')
break
print('Try again')

what is this syntax error? I don't even know what the error is. I m just beginning

number = input("Please enter your number:")
number = int(number)
if number % 10 == 0 :
print("Yes the number is a multiple of 10.")
elif :
print("No the number is not a multiple of 10.")
else :
print("Invalid number!")
this code gives the following output:
File "multiple_10.py", line 5
elif :
^
SyntaxError: invalid syntax
You need to provide a condition when you use elif--otherwise just use else. Check out the python docs here: https://docs.python.org/3/tutorial/controlflow.html?highlight=elif.
elif need a condition, add a condition or use else
The main problem is elif need a condition, but in your code that is missing
I don't know what condition is suitable for your code but I tried this and its working fine
number = input("Please enter your number:")
number = int(number)
number = number % 10
print(number)
if number == 0 :
print("Yes the number is a multiple of 10.")
elif number > 0 :
print("No the number is not a multiple of 10.")
else :
print("Invalid number!")

How to verify if input is not a letter or string?

I'm writing a basic program in IDLE with a menu choice with options from 1 to 4.
If a user input anything else then a number, it gives a ValueError: invalid literal for int() with base 10: 'a'
How can I check if the input is not a letter, and if it is, print a error message of my own?
def isNumber (value):
try:
floatval = float(value)
if floatval in (1,2,3,4):
return True
else:
return False
except:
return False
number_choice = input('Please choose a number: 1, 2, 3 or 4.\n')
while isNumber(number_choice) == False:
number_choice = input('Please choose a number: 1, 2, 3 or 4.\n')
else:
print('You have chosen ' + number_choice + '.\n')
This will check if the number is 1,2,3 or 4 and if not will ask the user to input the number again until it meets the criteria.
I am slightly unclear on whether you wish to test whether something is an integer or whether it is a letter, but I am responding to the former possibility.
user_response = input("Enter an integer: ")
try:
int(user_response)
is_int = True
except ValueError:
is_int = False
if is_int:
print("This is an integer! Yay!")
else:
print("Error. The value you entered is not an integer.")
I am fairly new to python, so there might very well be a better way of doing this, but that is how I have tested whether or not input values are integers in the past.
isalpha() - it is a string method which checks that whether a string entered is alphabet or words(only alphabets, no spaces or numeric) or not
while True:
user_response = input("Enter an integer : ")
if user_response.isalpha():
print("Error! The value entered is not an integer")
continue
else:
print("This is an integer! Yay!")
break
This program is having infinite loop i.e. until you enter an integer this program will not stop. I have used break and continue keyword for this.

Checking an input for characters $#!%&*_ python

No i'm not cursing in the title. i need to create a password processing program that checks a input on whether it meets certain criteria one of which is that it must contain one of the characters $#!%&*_.
this is what i currently have.
def pword():
global password
global lower
global upper
global integer
password = input("Please enter your password ")
length = len(password)
lower = sum([int(c.islower()) for c in password])
upper = sum([int(c.isupper()) for c in password])
integer = sum([int(c.isdigit()) for c in password])
def length():
global password
if len(password) < 8:
print("Your password is too short, please try again")
elif len(password) > 24:
print("Your password is too long, please try again")
def strength():
global lower
global upper
global integer
if (lower) < 2:
print("Please use a mixed case password with lower case letters")
elif (upper) < 2:
print("Please use a mixed case password with UPPER case letters")
elif (integer) < 2:
print("Please try adding numbers")
else:
print("Strength Assessed - Your password is ok")
This kind of thing will work:
required='$#!%&*_'
def has_required(input):
for char in required:
if input.contains(char):
return True
return False
has_required('Foo')
must_have = '$#!%&*_'
if not any(c in must_have for c in password):
print("Please try adding %s." % must_have)
any(c in must_have for c in password) will return True if any one of the characters in password is also in must_have, in other words, it will return True is the password is good. Because want to test for bad passwords, we put not in front of it to reverse the test. Thus the print statement is executed here only for bad passwords.
You can achieve this easily with a list comprehension + the any() built-in.
has_symbol = any([symbol in password for symbol in list('$#!%&*_')])
Or a little more broken up:
required_symbols = list('$#!%&*_')
has_symbol = any([symbol in password for symbol in required_symbols])

Resources