can this code be shortened or improved? [closed]

2024/7/8 6:39:51

Can this be shortened/improved? I'm trying to make a password checker in python.

Could the if's be put into a for loop? And if so, how?

pw = input("Enter password to test: ")caps = sum(1 for c in pw if c.isupper())
lower = sum(1 for c in pw if c.islower())
nums = sum(1 for c in pw if c.isnumeric())scr = ['weak', 'medium', 'strong']
r = [caps, lower, nums]if len(pw) < 6:print("too short") 
elif len(pw) > 12:print("too long")if caps >= 1:if lower >= 1:if nums >= 1:print(scr[2])elif nums < 1:print("your password is " + scr[1])elif lower < 1:print("your password strength is " + scr[0])
elif caps < 1:print("your password strength is " + scr[1])

Thanks for any suggestions :D

Answer
caps = sum(1 for c in pw if c.isupper())

can be:

caps = sum(c.isupper() for c in pw)

if caps >= 1:

can be:

if caps:

The most significant improvement: The bottom if/elif block can be completely removed by doing

i_strength = sum(map(bool,[caps,lower,nums])) - 1 #or sum(map(bool,r)) - 1
print('your password is {}'.format(scr[i_strength]))

Explanation: map(bool,[caps,lower,nums]) accumulates how many times each of caps,lower,nums is non-zero. Adding them up with sum gives you your "strength", which you've conveniently already put into a list, which can be accessed by index.

All of these improvements leverage the concept of "falsiness" in python, otherwise known as an object's value in a boolean context. Generally empty and zero things are False, and summing booleans is equivalent to adding ones and zeroes, so there you go.


Of course, it doesn't seem that you're doing anything with the counts of upper/lower/nums other than checking if they're nonzero. So a cleanup would just be

caps = any(c.isupper() for c in pw)
...

and then

i_strength = sum([caps,lower,nums]) -1
https://en.xdnf.cn/q/120237.html

Related Q&A

Count Running and Stopped Ec2 Instances with AWS Lambda

How can I count number of running and stopped EC2 instances in a particular region using boto3 and an AWS Lambda function?

Python2.7: How to split a column into multiple column based on special strings like this?

Im a newbie for programming and python, so I would appreciate your advice!I have a dataframe like this.In info column, there are 7 different categories: activities, locations, groups, skills, sights, t…

python - return and print does not give same result

what Im trying to do is take the entered string separated by commas and change it to list then for each list as a key print the associated value.def main():myDict = {a:1, b:2, c:3, d:4, e:5....}u_input…

Creating a menuBar in a frame?

import Tkinter as tk from Tkinter import Label, StringVar, Entry, Button, Menu, Frame, Tk, Canvas import subprocess from Tkconstants import LEFT, CENTER,W, SUNKEN , X, Yclass SampleApp(tk.Tk):def __ini…

Python return dictionary [closed]

Closed. This question needs debugging details. It is not currently accepting answers.Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to repro…

Use selenium and python to move mouse outside of web page area

I need to test the exit intent form on this page: https://www.graphicproducts.com/guides/5s-system/When the mouse pointer is moved outside of the web page area a popup window appears. I then need to en…

Python „stack overflow” (104 if statements). Is def(x) the only solution to optimise code?

Today have tried to check files with path directory name. Previously it worked, until I tried to create 104 if/else statements. How to dispose of this overflow error? More specific question: Does def(…

How to fix Python restarting whenever I start program on IDLE environment?

import randomwinning_conditon = 0 no_of_guesses = 0 comp_guess = random.randint(1,100)while (no_of_guesses == 11) or (winning_conditon == 1):user_guess = int(input("What is your guess? "))if…

Fetching Lawyers details from a set of urls using bs4 in python

I am an absolute beginner to Web Scraping using Python and know very little about programming in Python. I am just trying to extract the information of the lawyers in the Tennessee location. In the web…

Having trouble with python simple code running in console [closed]

Closed. This question is not reproducible or was caused by typos. It is not currently accepting answers.This question was caused by a typo or a problem that can no longer be reproduced. While similar q…