DEV Community

Cover image for 👨‍💻 Daily Code 46 | Random Number 1-100, 🐍 Python and 🟨 JavaScript
Gregor Schafroth
Gregor Schafroth

Posted on

👨‍💻 Daily Code 46 | Random Number 1-100, 🐍 Python and 🟨 JavaScript

Today I had very little time for code, so I wanted to do a very simple exercise: Generate a random number between 1 to 100, and in the case of JS also put that on the website. In both cases I used a bit of ChatGPT to fix this quickly. should do the same exercise again tomorrow and see if I can remember how to do it without!

My Code

Python

# Exercise: Print a random number between 1 and 100

import random

random_number = random.randint(1, 100)
print(random_number)
Enter fullscreen mode Exit fullscreen mode

JavaScript

<!DOCTYPE html>
<html>

<head>
    <title>Random Number Generator</title>
</head>
<body>
    <button id="generateButton">Generate Random Number</button>
    <div id="randomNumber"></div>
    <script>
        document.getElementById("generateButton").onclick = function () {
            let randomNumber = Math.floor(Math.random() * 100) + 1;
            document.getElementById("randomNumber").textContent = randomNumber;
        };
    </script>
</body>

</html>
Enter fullscreen mode Exit fullscreen mode

(Python actually suggested me ‘var’ here, but I don’t think that’s really used anymore, so I changed it to let)

Have a great day everyone, see you tomorrow! 🙋‍♂️

Top comments (3)

Collapse
 
kaamkiya profile image
Kaamkiya

Since you're not changing the value of randomNumber after initialising it, you can also use const, which is preferred over let. (Constants are good.)

I'm curious, why did you use .textContent instead of .innerText? Is there a difference?

Collapse
 
gregorschafroth profile image
Gregor Schafroth • Edited

@kaamkiya hi again!
const / let: good point. Since I learned to program with Python first I am not used to making that distinction. I guess I should just always use const and then just change them to let if I run into some kind of issue with that.

.textContent / .innerText : I actually never heard about .innerText. What I saw in some tutorials was the use of .innerHTML , but I figured that .textContent would probably be the safer option if I'm not inserting any html tags. Do you think .innerText would be even better to use?

Collapse
 
kaamkiya profile image
Kaamkiya

I don't know, I've only seen textContent used twice, but same with innerText. I doubt it matters, it's likely that one is just a reference to the other.