DEV Community

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

Posted on

👨‍💻 Daily Code 47 | Random Number 1-100, 🐍 Python and 🟨 JavaScript (2)

So as promised yesterday, I’m going to try this random number exercise again without ChatGPT. In Python I just generate the number and show it in the console, but in JavaScript I want to have a button in the browser to generate it and then also show it in the browser.

Let’s see how far I get!

My Code

Python

# Randomly generate a number between 1 and 100

import random

def main():
    print(random.randint(1, 100))

if __name__ == '__main__':
    main()
Enter fullscreen mode Exit fullscreen mode

Python was super easy for me now. Took me less than a minute. Really the only thing you need to know is random.randint().

JavaScript

Now JS is where it got harder… Below is exactly how far I came without any help until I started struggling. How does that work again with .onclick…? I can’t just use it as a function.

<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Random Number Generator</title>
</head>

<body>
    <button id="js-button">Generate random number</button>
    <div id="js-output"></div>

    <script>
        document.getElementById('js-button').onclick /* ...
    </script>
</body>

</html>
Enter fullscreen mode Exit fullscreen mode

Alright ChatGPT to the rescue again!

<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Random Number Generator</title>
</head>

<body>
    <button id="js-button">Generate random number </button>
    <div id="js-output"></div>

    <script>
        document.getElementById('js-button').onclick = function () {
            let randomNumber = Math.floor(Math.random() * 100) + 1;
            document.getElementById("js-output").textContent = randomNumber;
        }
    </script>
</body>

</html>
Enter fullscreen mode Exit fullscreen mode
  1. Alright it turns out instead of just calling .onclick as a function I just need to somehow use it with = function () {} .
  2. And then the math works with Math.floor(Math.random() * 100) + 1.
  3. And lastly .textContent = randomNumber

Alright if I can remember these three things I think I should be able to do this exercise out of my head and without any help. I’ll try exactly that tomorrow!

Top comments (0)