Python scripts repo

Red Nova

Moderador
Mensajes
573
Oro
27,566
Bueno creo este tema con la intención de que compartamos scripts solamente en Python, no se admiten otros lenguajes, yo recién comencé a estudiar Python, así que voy a empezar con algo muy básico, si pueden comentar el funcionamiento del script mejor.

WARNING!
Cualquier parecido de algunos de los scripts publicados aquí con alguno de Stack Overflow o al de algún tutorial es pura coincidencia.
Script basado en hechos reales.
Un ¨jueguito¨ básico en el que tienes que adivinar un número entre el 0 y el 10 en 3 intentos.
Python:
# Made by レッド・ノヴァ(Red Nova)
import random  # import random module

secret_number = random.randint(0, 10)  # it gets a pseudorandom integer between 0 and 10
guess_count = 0
guess_limit = 3

print("Guess the number between 0 to 10")

while guess_count < guess_limit:
    guess = int(input("Guess: "))
    guess_count +=1
    if guess == secret_number:
        print("You won!")
        break
else:
    print("Sorry, you failed")

Pd: Sabían que una computadora no puede generar verdaderos números aleatorios?(ahora un ¨tufao¨ ve esto y se va a quedar.... Captura de pantalla 2023-03-22 020517.jpg naahhhh mentira!?, ño! eso no me lo sabia... si ya... Lo que genera este pequeño script es un número pseudoaleatorio, que parece aleatorio pero en verdad no lo es.
 
Última edición:
Suerte en tu nuevo patch de vida. Creo que hoy día es importante saber algún tipo de lenguaje de programación.

AURORAbot cuales son los lenguajes de programación mas utilizados en la actualidad?
Todavía no funciona así, hay que comprar un addon aparte para eso, y de hecho aún no sale para el publico. Loco estoy porque lo haga.
 
Sorprendentemente las scripts que uso las escribi en bash.

Aqui un pedazo de codigo al azar para no sentirme excluido.

Python:
def loggedmethod(method):
    """Log a CRUD method and confirm its successful execution"""
    @wraps(method)
    def wrapper(self, *args, **kwargs):
        method_data = inspect.getfullargspec(method)
        method_type = method.__name__.split("_")[0].upper()
        # + 1 because of self
        self.logger.info(
            "%s %s",
            method_type,
            [
                f"{method_data.args[index + 1]}={value}"
                for index, value in enumerate(args)
            ],
        )

        res = method(self, *args, *kwargs)

        self.logger.info("%s --success--", method_type)
        return res

    return wrapper
 
Voy a hacer un push commit en mi código :ROFLMAO:

Fixing crash by wrong input value.
Python:
# Made by レッド・ノヴァ(Red Nova)
import random  # import random module

secret_number = random.randint(0, 10)  # it gets a pseudorandom integer between 0 and 10
guess_count = 0
guess_limit = 3

print("Guess the number between 0 to 10")

while guess_count < guess_limit:
    guess_count += 1
    try:
        guess = int(input("Guess: "))
    except ValueError:
        print("Invalid Value")
        break
    if guess == secret_number:
        print("You won!")
        break
else:
    print("Sorry, you failed!")
 
Voy a hacer un push commit en mi código :ROFLMAO:


Python:
# Made by レッド・ノヴァ(Red Nova)
import random  # import random module

secret_number = random.randint(0, 10)  # it gets a pseudorandom integer between 0 and 10
guess_count = 0
guess_limit = 3

print("Guess the number between 0 to 10")

while guess_count < guess_limit:
    guess_count += 1
    try:
        guess = int(input("Guess: "))
    except ValueError:
        print("Invalid Value")
        break
    if guess == secret_number:
        print("You won!")
        break
else:
    print("Sorry, you failed!")
Deja mandar un parche:
Diff:
Fix input handling.
@@ -10,15 +10,18 @@
 print("Guess the number between 0 to 10")
 
 while guess_count < guess_limit:
-    guess_count += 1
     try:
         guess = int(input("Guess: "))
     except ValueError:
         print("Invalid Value")
-        break
+        continue
+    if not (0 <= guess <= 10):
+        print("Out of range")
+        continue
     if guess == secret_number:
         print("You won!")
         break
+    guess_count += 1
 else:
     print("Sorry, you failed!")
 
Deja mandar un parche:
Diff:
Fix input handling.
@@ -10,15 +10,15 @@
 print("Guess the number between 0 to 10")
 
 while guess_count < guess_limit:
-    guess_count += 1
     try:
         guess = int(input("Guess: "))
     except ValueError:
         print("Invalid Value")
-        break
+        continue
+    if not (0 <= guess <= 10):
+        print("Out of range")
+        continue
     if guess == secret_number:
         print("You won!")
         break
+    guess_count += 1
 else:
     print("Sorry, you failed!")
Estaba buscando como hacer eso que hiciste para resaltar los cambios, ahora si queda más pro(y)
 
Aburrido me dio por implementar el script de Python en C++

Python:
import random  # import random module

secret_number = random.randint(0, 10)  # it gets a pseudorandom integer between 0 and 10
guess_count = 0
guess_limit = 3

print("Guess the number between 0 to 10")


while guess_count < guess_limit:
    try:
        guess = int(input("Guess: "))
    except ValueError:
        print("Invalid Value")
        continue
    if not (0 <= guess <= 10):
        print("Out of range")
        continue
    if guess == secret_number:
        print("You won!")
        break
    guess_count += 1
else:
    print("Sorry, you failed!")

C++:
#include <iostream>
#include <time.h>

int main()
{
    int secret_number;
    int guess_count = 0;
    int guess_limit = 3;
    int guess;

    /* initialize random seed: */
    srand(time(NULL));

    /* generate secret number: */
    secret_number = rand() % 10 + 1;

    std::cout << "Guess the number between 1 to 10" << std::endl;

    while (guess_count < guess_limit)
    {
        std::cout << "Guess ";

        try
        {
            std::cin >> guess;
            if (guess == NULL || guess > 10)
                throw "Invalid Value";
        }
        catch (const char * wrongValue)
        {
            std::cout << "Exception: " << wrongValue << std::endl;
            std::cin.clear(); // reset the fail flags
            std::cin.ignore(std::numeric_limits<std::streamsize>::max(), '\n'); //ignore the bad input until line end
            continue;
        }

        if (guess == secret_number)
        {
            std::cout << "You won!" << std::endl;
            break;
        }
        else
        {
            std::cout << "You failed" << std::endl;
        }
        guess_count++;
    }
    return 0;
}
 
C++:
/* initialize random seed: */
srand(time(NULL));
Aquí vale porque es un jueguito, pero no lo uses para cosas serias.

C++:
if (guess == NULL || guess > 10)
    throw "Invalid Value";
Los int no pueden ser NULL (bueno, en algunos compiladores NULL se expande como 0), aquí las variables no contienen referencias a objetos estilo Python.
Tampoco deberías usar excepciones como control de flujo.

Diff:
@@ -3,10 +3,10 @@
 
 int main()
 {
-    int secret_number;
+    unsigned int secret_number;
     int guess_count = 0;
     int guess_limit = 3;
-    int guess;
+    unsigned int guess;
 
     /* initialize random seed: */
     srand(time(NULL));
@@ -20,17 +20,22 @@
     {
         std::cout << "Guess ";
 
-        try
+        std::cin >> guess;
+
+        if (std::cin.fail())
         {
-            std::cin >> guess;
-            if (guess == NULL || guess > 10)
-                throw "Invalid Value";
-        }
-        catch (const char * wrongValue)
-        {
-            std::cout << "Exception: " << wrongValue << std::endl;
+            if (std::cin.eof())
+                break;
+            std::cout << "Invalid Value" << std::endl;
             std::cin.clear(); // reset the fail flags
             std::cin.ignore(std::numeric_limits<std::streamsize>::max(), '\n'); //ignore the bad input until line end
+            continue;
+        }
+
+        /* `0u - 1` wraps around */
+        if (guess-1 >= 10u)
+        {
+            std::cout << "Out of range" << std::endl;
             continue;
         }
 
Código:
import random

numero_seleccionado = random.randint(1, 100)

while True:
    numero_usuario = int(input("Adivina el número seleccionado: "))
    
    if numero_usuario > numero_seleccionado:
        print("Estás muy alto.")
    elif numero_usuario < numero_seleccionado:
        print("Estás muy bajo.")
    else:
        print("¡Felicidades! Adivinaste el número seleccionado.")
        break
 
Última edición:
Aquí vale porque es un jueguito, pero no lo uses para cosas serias.


Los int no pueden ser NULL (bueno, en algunos compiladores NULL se expande como 0), aquí las variables no contienen referencias a objetos estilo Python.
Tampoco deberías usar excepciones como control de flujo.

Diff:
@@ -3,10 +3,10 @@
 
 int main()
 {
-    int secret_number;
+    unsigned int secret_number;
     int guess_count = 0;
     int guess_limit = 3;
-    int guess;
+    unsigned int guess;
 
     /* initialize random seed: */
     srand(time(NULL));
@@ -20,17 +20,22 @@
     {
         std::cout << "Guess ";
 
-        try
+        std::cin >> guess;
+
+        if (std::cin.fail())
         {
-            std::cin >> guess;
-            if (guess == NULL || guess > 10)
-                throw "Invalid Value";
-        }
-        catch (const char * wrongValue)
-        {
-            std::cout << "Exception: " << wrongValue << std::endl;
+            if (std::cin.eof())
+                break;
+            std::cout << "Invalid Value" << std::endl;
             std::cin.clear(); // reset the fail flags
             std::cin.ignore(std::numeric_limits<std::streamsize>::max(), '\n'); //ignore the bad input until line end
+            continue;
+        }
+
+        /* `0u - 1` wraps around */
+        if (guess-1 >= 10u)
+        {
+            std::cout << "Out of range" << std::endl;
             continue;
         }
Ando con Visual Studio, improvisé un poco la verdad, but if it works, don´t touch it. Son las reglas amigo.
Captura de pantalla 2023-03-26 144806.jpg Captura de pantalla 2023-03-26 144731.jpg
 
Atrás
Arriba