Home > database >  How to write the value of z into the string?
How to write the value of z into the string?

Time:01-20

import random

x = 1

z = random.randint(0,255)

if x != z:
    print('unsuccessful')
    
if x = z:
    
    print('successful')

    f = open("C:\Users\AsusTUF\ai.txt", "a")
    del = text.replace('z = random.randint(0,255)','z = '

So i want to write value of z into the file, but I dont have an idea on how to do it! Thanks in advance for the help.

Keep in mind I am new to python so I tried return z but did not even run that because i know it wont work.

CodePudding user response:

The function you are looking for is f.write('text'). For example:

import random

x = 1

z = random.randint(0,255)

if x != z:
    print('unsuccessful')
    
if x == z:
    
    print('successful')

    f = open("C:\Users\AsusTUF\ai.txt", "a")
    f.write(str(z))
    f.close()

Also it's not a good idea to use del as a variable name once it is a keyword from the language.

CodePudding user response:

The line being as such:

del = ...

It 'll not actually work.

Here is the repro example using a Python REPL:

py
zsh: command not found: py
python
Python 3.8.14 (default, Nov  7 2022, 11:52:33) 
[Clang 14.0.0 (clang-1400.0.29.202)] on darwin
Type "help", "copyright", "credits" or "license" for more information.
>>> del = ...
  File "<stdin>", line 1
    del = ...
        ^
SyntaxError: invalid syntax

Even other operator, being as such in:

>>> in = ...
  File "<stdin>", line 1
    in = ...
    ^
SyntaxError: invalid syntax

Rename it, then We All Good ™️:

>>> IN = ...
>>> IN
Ellipsis

CodePudding user response:

Apart from other answers, I assume that you are trying to check how many runs it takes to get the random value equals to x.

It can easily be done by adding a while loop with a counter.

import random

x = 1
count = 0  # Counter
while True:  # Loop indefinitely
    z = random.randint(0, 255)  # Generate random number
    count  = 1  # Increasing the counter

    if x != z:
        print('Unsuccessful: %d' % count)
    else:
        print('Successful: %d' % count)
        f = open("i.txt", "a")  # You can also give relative path here
        f.write(str(z))  # Writing the value to file
        break  # Breaking the loop
  • Related