'How to use the "randint" output in an if statement?

this is my first question on stack overflow. I'm still learning python so I wanted to make something fun, but not very advanced. I want to know how to make a random number into an if statement. Here is my code:

import random
print("Congratulations! You are our ")
print(random.randint(0, 200))
print(" Caller!")
if (randint >= 200);{
print("Oops, you lost!")
}

I tried but it kept showing errors.



Solution 1:[1]

In order to use the same number again, you must assign it to a variable first. Something like:

import random   
randnum = random.randint(0, 200)
print("Congratulations! You are our ")
print(randnum)
print(" Caller!")
if (randnum >= 200):
    print("Oops, you lost!")                                                                               

Solution 2:[2]

I suggest you read some basic info about conditions in python, e.g. here: https://www.w3schools.com/python/python_conditions.asp

as for your code, this will work:

print("Congratulations! You are our ")
randint = random.randint(0, 200)
print(randint)
print(" Caller!")
if randint >= 100:
  print("Oops, you lost!")

Solution 3:[3]

You have to save the random number you created.

import random

random_number = random.randint(0, 200)
print(f"Congratulations! You are our {random_number} Caller!")
if random_number >= 200:
    print("Oops, you lost!")

With the current values you won't see the output in the if block often, because the maximum of the number is 200.

Solution 4:[4]

This is how your code'd look like when it is fixed:

import random

print("Congratulations! You are our ")
print(random.randint(0, 200))
print(" Caller!")
if random.randint(0, 200) >= 200:
    print("Oops, you lost!")

So first of all you don't use ; and {} to denote an if block in python, rather you use : and indentation like in the above example.

Also you tried to refer to a variable called randint which was not defined yet, or maybe you wanted to call the same random.randint function like you did above. Either way make sure to define variables and assign value to them in order to compare them in an if condition or properly call functions.

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Ayush
Solution 2 amy989
Solution 3 Matthias
Solution 4 Szabolcs