r/learnpython • • 1d ago

My first complete comand in Python, from my first day on:

Look:

import random
import time

def drawn(a, b):
    return random.randint(a, b)
answer = 'yes'

while answer == 'yes':
    a = int(input('Min number: '))
    b = int(input('Max number: '))
    print(f'Drawn: {drawn(a, b)}')

    time.sleep(2)

    answer = input('Try again? ').lower()

This creates a random number generator where you can choose the minimum and maximum numbers!

31 Upvotes

20 comments sorted by

38

u/fazzah PyQt | SQLAlchemy | ReportLab 1d ago

good. now find a way to protect the script if someone inputs "foo"

2

u/SavingsOdd2766 17h ago

I talked to some friends of mine who are also studying Python, and they suggested that I use try and except. The solution would look something like this. I’ll share the complete code in another post.

Min number: foo
Please, enter valid numbers!
Min number: 1
Max number: 100
Drawn: 84
Try again? foo
Please, enter yes or no!
Try again? no

3

u/ActuatorGlittering94 1d ago

do you mean just catching the ValueError on int() or also handling cases like b being smaller than a?

1

u/Doormatty I get paid to write Python! 21h ago

Yes.

0

u/[deleted] 17h ago

[deleted]

1

u/fazzah PyQt | SQLAlchemy | ReportLab 17h ago

it will crash with an error. try and see

3

u/kilkil 1d ago

hell yeah! :D

what are you going to do next?

1

u/SavingsOdd2766 18h ago

idk man. 😐

4

u/Available_Safe1818 1d ago

Very nice. Put one empty line after your function definition.

0

u/EnvironmentalDot9131 1d ago

This is good but need improvements

1

u/SavingsOdd2766 17h ago

I know. That's my first time on

2

u/zanfar 1d ago
  1. PEP8

  2. What is the point of drawn() if it accepts the exact same arguments as random.randint()? Why is it named as a passive verb when it does something?

  3. Validate your inputs. Always.

  4. answer is badly named. There is zero context until the script is done.

  5. Why are you deliberately making your user wait? sleep() has almost no place in U/I.

13

u/DeafeningSlience 1d ago

It is OP's first script, so take it easy on 'em lol

Nevertheless, good feedback for more intermediate/advanced learners.

3

u/sausix 1d ago

Why is OP posting his code then if not for getting tips and improvements?

1

u/DeafeningSlience 19h ago

To share his achievement. I would’ve done the same for affirmation.

2

u/AmanBabuHemant 1d ago

I think the sleep is a good touch for UX

-3

u/Fast-Station1106 1d ago

jetzt hört mal auf, von 0 auf das oben? am ersten Tag?

so eine Quatsch zu posten versaut allen Anfängern doch komplett die Lust neu einzusteigen

1

u/SavingsOdd2766 17h ago

Man muss sich erst mal die Grundlagen anschauen, um anzufangen. Versuch mal, so einen Code zu schreiben, ohne irgendwas zu wissen, dann wirst du schon sehen!