Python Forum
Unexpected output while using random.randint with def
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
Unexpected output while using random.randint with def
#1
So, I just learned about the keyword def; it has been going really smoothly for me because I reuse chunks of code often. However, I have run into a hiccup.

import random

def word():
    random.randint(0,1)

y = word()

print(y)
The output I would like (and expected) was a random chance between 0 and 1; however, the output given is "None." What do I have yet to learn about def?
Reply
#2
Looking at your code snippet - what do you think happens with the value generated from random.randint(0,1)? You do nothing with it, just discard it. In general you can assign it to a name (variable) for future use, or like in this case, directly return it. Your function does not return anything explicitly, so (implicitly) it returns None
import random
 
def word():
    return random.randint(0,1)
 
y = word()
 
print(y)
If you can't explain it to a six year old, you don't understand it yourself, Albert Einstein
How to Ask Questions The Smart Way: link and another link
Create MCV example
Debug small programs

Reply


Possibly Related Threads…
Thread Author Replies Views Last Post
  random numbers, randint janeik 2 574 Nov-27-2023, 05:17 PM
Last Post: janeik
  Unexpected output Starter 2 491 Nov-22-2023, 12:08 AM
Last Post: Starter
  Unexpected Output - Python Dataframes: Filtering based on Overlapping Dates Xensor 5 720 Nov-15-2023, 06:54 PM
Last Post: deanhystad
  Unexpected output from df.loc when indexing by label idratherbecoding 6 1,206 Apr-19-2023, 12:11 AM
Last Post: deanhystad
Sad Iterate randint() multiple times when calling a function Jake123 2 2,061 Feb-15-2022, 10:56 PM
Last Post: deanhystad
  Using Dictionary to Test Evenness of Distribution Generated by Randint Function new_coder_231013 6 3,299 Feb-23-2021, 01:29 PM
Last Post: new_coder_231013
  unexpected output asyrafcc99 0 1,508 Oct-24-2020, 02:40 PM
Last Post: asyrafcc99
  Help with a random.randint choice in Python booponion 5 2,814 Oct-23-2020, 05:13 PM
Last Post: deanhystad
  Unexpected output: symbols for derivative not being displayed saucerdesigner 0 2,061 Jun-22-2020, 10:06 PM
Last Post: saucerdesigner
  output a list of random numbers 'x' columns wide adityavpratap 4 3,010 Jan-13-2020, 05:32 PM
Last Post: perfringo

Forum Jump:

User Panel Messages

Announcements
Announcement #1 8/1/2020
Announcement #2 8/2/2020
Announcement #3 8/6/2020