# Pseudorandom telephone generator

Was tinkering around in Python after a long hiatus, and decided to do a very simple fake telephone generator.

Anything I can do to improve it?

import random

areacode = input("Enter your desired area code prefix: ")
print(areacode + "-", end='')
for i in range(3):
print(random.randint(0,9), end='')

print("-",end='')

for j in range(4):
print(random.randint(0,9), end='')


What are some of the things I should keep in mind syntax wise? I feel like I'm using unnecessary looping here.

• What rules does your telephone numbers have to comply to? Which numbers are invalid? Are all numbers possibly generated by your generator valid?
– Mast
Jan 20, 2018 at 21:29
• @Mast yes, basically I'm not doing anything 'real' just yet. I just want to know if there is a faster more pythonic way to generate telephone numbers with the user defining his area code. Jan 20, 2018 at 21:32
• I didn't downvote, but I wanted to let you know somebody voted to close your question as Too Broad. While I'm not sure it is, your lack of specification might have something to do with it. Might want to clarify it.
– Mast
Jan 20, 2018 at 21:56
• The prefix-AAA-BBBB seems to suggest you're only making NANP numbers; if that's the case, you should mention it in your specification. The other 90% of the world deserves to know! Jan 22, 2018 at 9:22
• @TobySpeight I'm a dumbass when it comes to interpretations of collective prime societies. Jan 22, 2018 at 21:12

Assuming you're looking for numbers of the format XXX-XXX-XXXX (keeping in mind that this excludes international numbers):

I wouldn't separate the printing onto separate lines. I would build up the number (perhaps extracting this logic into a function) and then print the whole thing. You can also eliminate those unnecessary loops by generating numbers in different ranges and using different formatting strings to add the leading zeros (ex. a routing code of 2 should be 002).

You'll also probably want to handle the case that an invalid area code is input. For this, I pulled out the prompt into a separate function that can be used in a loop (until a valid area code is given).

Finally, for scripts you should wrap the main action in if __name__ == '__main__':

#!/bin/env python3
from random import randint

def random_phone_number(area_code):
"""Returns a random phone number (XXX-XXX-XXXX) with a given
area_code."""
prefix = randint(0, 999)
line_number = randint(0, 9999)
return f'{area_code:03d}-{prefix:03d}-{line_number:04d}'

def prompt_area_code():
"""Interactively prompts the user for an area code, returning it."""
while True:
try:
area_code = int(input('enter an area code: '))
except ValueError:
pass

if 0 <= area_code <= 999:
return area_code

def main():
print(random_phone_number(prompt_area_code()))

if __name__ == '__main__':
main()


Things of note: