How to use a variable function several times without creating another variable? How to draw a number

Asked

Viewed 57 times

-1

import random
n = random.randint(1, 6)
print('O valor sorteado foi {}'.format(n))
if nd !=n:
    print('Não foi dessa vez')
if nd ==n:
    print('Parabéns! Você está com sorte')
start1 = str(input('Deseja continuar? '))
if start1 =='Sim':
    nd1 = int(input('Qual valor você deseja? De 1 até 6? '))
else: exit()
n1 = random.randint(1, 6)
print('O valor sorteado foi {}'.format(n1))
if nd1 ==n1:
    print('Parabéns! Você está com sorte')
else: print('Não foi dessa vez!')

> Citação

2 answers

0

What you are looking for is a repetition loop like while, i.e., a command that repeats a set of instructions while the conditions for it to continue are true, example from your code:

import random
start1 = 'Sim'
while (start1 == 'Sim'):
  nd = int(input('Qual valor você deseja? De 1 até 6? '))
  n = random.randint(1, 6)
  print('O valor sorteado foi {}'.format(n))
  if nd !=n:
    print('Não foi dessa vez')
  else:
    print('Parabéns! Você está com sorte')
  
  start1 = str(input('Deseja continuar? '))    #Ao chegar aqui ele irá voltar para o while e caso o start1 permaneça como 'Sim' então ele executará novamente
exit()
  • Lucas, I can apply this property while the variable n too?

  • I didn’t understand why to do this separately, realize that while will run everything within its scope

0

As I understand it, you are trying to create a little guessing game. Where the computer will draw a value between 1 and 6 and the user will try to discover the value drawn by the computer.

Well, to build the code, we must:

  1. Import the library Random, as well as the method randint;
  2. Draw a value between 1 and 6, storing it in a variable;
  3. Implement a repeat loop to capture the value typed by the user;
  4. Check if the user’s value corresponds to the drawn value;
  5. Display an approval or disapproval message.

With this logic and using Assignment Expressions, we can assemble the following code:

from random import randint

cont = 1
s = randint(1, 6)
while (n := int(input('Digite um valor entre "1" e "6": '))) != s:
    print('Não foi desta vez. Tente novamente.')
    cont += 1

print(f'Parabéns! Você acertou o valor "{s}" na {cont}º tentativa!')

Note that when we execute this code, the draw is carried out. Then, we are asked to enter a value. Later the code checks if the entered value corresponds to the drawn value. If so, we receive a positive message. If not, we will receive a disapproval message and then we will be prompted again for a value.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.