Note: I am using Python 3.5 I just started creating a part two to a text based game I made, and here is the code I'm having trouble with:
import random
def game():
randomIp = random.randint(10, 999)
def tutorial():
global randomIp
print('Hello.')
print(randomIp + '.' + randomIp + '.' + randomIp + '.' + randomIp)
The problem that kept coming up was:
File "C:\Users\Anony\Desktop\SICCr4k2BrokeFold\SICCr4k2Broke.py", line 18, in tutorial
print(randomIp + '.' + randomIp + '.' + randomIp + '.' + randomIp)
NameError: name 'randomIp' is not defined
I don't know what's up. I have the global put into tutorial()
and it doesn't have an error for saying randomIp
isn't defined in the command global randomIP
only for print(randomIp + '.' + randomIp + '.' + randomIp + '.' + randomIp)
. Does anyone know what the problem is? And if I wanted a different random number to be printed after each "."
. What would the code be for that? I would like it so that it would print out something like 23.321.43.23
. A completely different number after each period.
You created a local variable, but then you try to access a global of the same name.
You could simply omit the global
keyword.
def game():
randomIp = ...
def tutorial():
print(randomIp + ...)
Note that this will only work if you don't assign randomIp
inside tutorial()
, otherwise you will need the nonlocal
declaration:
def game():
randomIp = ...
def tutorial():
nonlocal randomIp
randomIp += 5 # counts as assignment
print(randomIp + ...)
Also note that it's more typical in python to use .format()
instead of +
when working with strings...
# This works
print('{0}.{0}.{0}.{0}'.format(randomIp))
# This does not work
# print(randomIp + '.' + randomIp + '.' + randomIp + '.' + randomIp)
This is because you can't add an integer to a string in Python. In some other languages, this will result in automatic conversion. In Python, it will just result in an error.
This will generate a random IP address from a valid /8 block, skipping the 127
localhost block, multicast blocks, and whatnot. It may generate addresses which are broadcast addresses, depending on the netmask.
def randomIp():
x = random.randint(1, 222)
if x == 127:
x += 1
return '{}.{}.{}.{}'.format(
x,
random.randint(0, 255),
random.randint(0, 255),
random.randint(0, 255))
Of course, you shouldn't actually use the IP address for anything.