'How to make the try except function easier to read - Python 3 [closed]

import random

chars = list('abcdefghijklmnopqrstuvwxyz1234567890')
password_char_list = []
password = ''

while True:
    try:
        password_length = int(input('Give the length of the password: '))
    except ValueError:
        print("Please give an integer.")
    else:
        break

def random_char():
    char = random.choice(chars)
    password_char_list.append(char)

for n in range(password_length):
    random_char()

for n in password_char_list:
    password += '' + n

print('Your password is ' + password)

So this is some code which I have written, an extremely simple and basic password generator. I'm self taught, new to Python and also new to the Stack Overflow community.

As you can see from the code above, I'm not completely fluent in Python yet. I've tried to use the try except function, but my code is far from concise and is difficult to read. What I would like to know is whether there is a better and slicker way to make sure that the input is an integer?

Many thanks,

Simply

P.S. this is the code which I would like to shorten

while True:
    try:
        password_length = int(input('Give the length of the password: '))
    except ValueError:
        print("Please give an integer.")
    else:
        break


Solution 1:[1]

Your code is fine and you shouldn't expect to be able to write Python more concisely than this. You could wrap the code in a function to make the logic even clearer.

def input_password_length():
    while True:
        try:
            return int(input('Give the length of the password: '))
        except ValueError:
            print("Please give an integer.")

Often you will end up writing a more reusable function to make the overall code more concise and readable:

def input_integer(prompt):
    while True:
        try:
            return int(input(prompt))
        except ValueError:
            print("Please give an integer.")

password_length = input_integer('Give the length of the password: ')

Solution 2:[2]

You can write your try-except expressions in one line. That prevents some smaller codes with less purpose going into few lines.

while True:
    try: password_length= int(input("Give the length of the password:")); break
    except: print("Please give an integer:"); continue

Remove continue if you don't need to run it again.

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1
Solution 2