This is a random number generator I got from a Youtube channel TechWithTim. The video was “5 Mini Python Projects”. I made some modifications from what he did. His original program. His original program was all if/elif/else statements. While I do use them, I decided to break it into functions to clean it up a bit and make the code easier to read. At least, I think it is easier to read. I also added a name prompt to make it a bit friendlier sounding when it is run. I also tweaked some of the outputs. Nothing major. The biggest change is the functions I created to modularize it.
Before anyone says anything, I do know that the string concatenation can be done simpler, but the syntax I wanted to use wouldn’t work. So, I had to do it the old school way. I do like a lot of the simplicity that comes with python compared to Java, but it is nice that they have these…older?…methods for string concatenation.
I also wanted to use some of the methods, just to get more familiar with them. The “.capitalize()” method is an interesting one, particularly useful for names when displaying them. Method creation and calling are quite simple and easy to use, like method creation in java, but again, simplified. I’d like to learn how to run this python in a browser so people can see it and run it without needing to download it and run, but that is a project for another day.
UPDATE 2022-12-24: I found a website that lets you embed a javascript based python editor/terminal so you can see the output of the code. I have to tweak it a bit since the paid version doesn’t run the latest python version so it doesn’t support some of the things I like (like f strings) but its free and simple and lets me show my python scripts. The editor includes the code but I’ll include a code block below as well. Because of the differences in python version the code shown in the editor will be slightly different than the code below. Since this is from May, it doesn’t include some of the error checking I’ve learned (like entering a char/string instead of number). May or may not update it, that is visible on the Random Password Generator page.
import random
name = input('Please enter your name: ')
range = input(f'Hello {name.capitalize()}, please type a number: ')
def isdigit(d):
if d.isdigit():
d = int(d)
return d
else:
print('Please enter a number next time')
quit()
def guesses(score):
score = 0
while True:
guess = input(f'Enter a number between 0 and {str(range)}: ')
guess = isdigit(guess)
score += 1
if guess == r:
print(f'Congratulations {name.capitalize()}, you got it right!')
return score
elif guess > r:
print('Too high')
continue
else:
print('Too low')
continue
range = isdigit(range)
r = random.randint(0, range)
score = guesses(r)
print('It took you', score, 'guesses')