Problem with a program for decided to watch Star Wars [duplicate] - python

This question already has answers here:
How do I create variable variables?
(17 answers)
How do I perform a random event in Python by picking a random variable?
(3 answers)
Closed 8 days ago.
I do a program for decide how to watch Star Wars movies. And I creat a option to print random of Star Wars, bat I have a problem. I do the program made a variable that have the name of other vairble between "", and I want that this variable conect to the information of the original variable.
import random
def Menu():
print("Como ver Star wars:")
print("Elige opción:")
print("1. Orden de salida de las peliculas")
print("2. Orden corlologico")
print("3. Mix (esta opción es una mezcla de la 1 trilogia y las percuelas)")
print("4. Aleatorio")
print("5. Salir del programa")
return
def main():
Episodeo1 ="Star Wars: Episodio I - La amenaza fantasma"
Episodeo2 ="Star Wars: Episodio II - El ataque de los clones"
Episodeo3 ="Star Wars: Episodio III - La venganza de los sith"
Episodeo4 ="Star Wars: Episodeo IV - Una nueva esperanza"
Episodeo5 ="Star Wars: Episodio V - El imperio contraataca"
Episodeo6 ="Star Wars: Episodio VI - El retorno del Jedi"
Menu()
opcion = int(input( ))
while opcion <5:
if opcion ==1:
print("1. Orden de salida de las peliculas")
print(Episodeo4)
print(Episodeo5)
print(Episodeo6)
print(Episodeo1)
print(Episodeo2)
print(Episodeo3)
if opcion ==2:
print("2. Orden corlologico")
print(Episodeo1)
print(Episodeo2)
print(Episodeo3)
print(Episodeo4)
print(Episodeo5)
print(Episodeo6)
if opcion ==3:
print(Episodeo4)
print(Episodeo5)
print(Episodeo1)
print(Episodeo2)
print(Episodeo3)
print(Episodeo6)
if opcion ==4:
print("4. Aleatorio")
num = str(random.randint(1,6))
Eprandom="Episodeo"+num
print("Star Wars:", Eprandom,)
opcion = int(input( ))
I know that i can do more easy using 'if', bat this question is more for know more of python, and if this idea work good.

Related

Why doesnt it print

I dont understand why it doesnt print the sentence. I have tried everything i can think off but im new to python is there something im missing?
def main():
print("1 = USD 2= GB pounds 3 = Japanse Yen")
valuta = input(" Welke valuta wilt u in wisselen voor de euro (graag het getal geven) ")
if __name__ == "__main__":
main()
Try changing your code to:
def main():
print("1 = USD 2= GB pounds 3 = Japanse Yen")
valuta = input(" Welke valuta wilt u in wisselen voor de euro (graag het getal geven) ")
print(valuta)
if __name__ == "__main__":
main()

CPU player dice game

Need to program a CPU that decides between throwing the dice again or ending its turn.
The game already works with two players. Now I just need the 2nd player to make decisions on its own.
What do I do? This is a part of the code:
while not juego_termina:
print("")
jug_turno.lanzar_dado(dado)
jug2.dec_cpu()
while jug_turno.jugando:
jug2.dec_cpu() #Se anida un while para cada turno del jugador
print("Puntaje parcial acumulado:",end=' ')
print(jug_turno.p_parcial)
continuar = ""
jug2.dec_cpu()
while continuar != "SI" and continuar != "NO": #Pregunta si continua el turno
print("Desea seguir jugando? (SI/NO)")
continuar = input().upper() #.upper para la mayuscula
if continuar == "SI":
jug_turno.lanzar_dado(dado)
else:
jug_turno.terminar_turno()
if jug_turno.p_total >= meta: #Compara el puntaje total con la meta asignada al inicio
juego_termina = True #Se acaba el juego y salta a nombrar el ganador
else:
if jug_turno == jug1:
jug_turno = jug2
else:
jug_turno = jug1
mostrar_puntajes(jug1,jug2)
print("El ganador es:")
print(jug_turno.nombre)
I only know a small amount of Spanish, so it's possible I'm reading your code incorrectly, but it looks like the game works like Blackjack - the winning player is the player who has the highest total without going over some maximum value (21 in the case of Blackjack). The code for the simplest algorithm you could use probably looks something like this:
def dec_cpu(maximum):
total = 0
while total < maximum and (highest_possible_die_roll / 2) < (maximum - total):
total = total + roll_die()
return total
The (highest_possible_die_roll / 2) < (maximum - total) part is essentially saying, "if there's less than a 50% chance that rolling the die again will put me over the maximum, roll again". From there, you can refine it depending on the rules of the game. For example, if there's an amount of money being wagered each time, the computer might want to be 75% sure that they won't go over the maximum when the die is rolled if there's a lot of money on the line.

Python file executable error

I did a fuel calculator program for a game with python and then I compiled to .exe with cx_Freeze. It converts it well to .exe and I can open the executable but when the script interacts with the user the window closes after pressing enter when the user introduce the requested information.
This is one part of the code, after requesting some information to the user the program does some calculations but I think it's irrelevant because the problem is in the input. I want that the program doesn't close when the user press enter in the input of info requested.
import sys
COMBUSTIBLE=chr(raw_input("Introduce unidad de combustible: "))
DURACION=chr(raw_input("Introduce unidad de duracion: "))
if COMBUSTIBLE != "litros" and COMBUSTIBLE != "kilos" and DURACION != "vueltas" and DURACION != "tiempo" and DURACION != "km":
print "Error: Ambos argumentos son invalidos"
print "Primer argumento debe ser 'litros' o 'kilos'"
print "Segundo argumento debe ser 'tiempo' o 'vueltas' o 'km'"
sys.exit(1)
elif COMBUSTIBLE != "litros" and COMBUSTIBLE != "kilos":
print "Error: Primer argumento invalido"
print "Primer argumento debe ser 'litros' o 'kilos'"
sys.exit(2)
elif DURACION != "tiempo" and DURACION != "vueltas" and DURACION != "km":
print "Error: Segundo argumento invalido"
print "Segundo argumento debe ser 'tiempo' o 'vueltas' o 'km'"
sys.exit(3)
else:
pass
# TIPO 1 - LITROS - VUELTAS
if COMBUSTIBLE == "l" and DURACION == "v":
# DATA REQUEST
RACE_DURATION=int(raw_input("Introduce el total de vueltas de la carrera: "))
CAR_FUEL=float(raw_input("Introduce los litros totales del coche: "))
FUEL_PER_LAP=float(raw_input("Introduce el consumo medio en litros por vuelta: "))
The window will be closed right after your proggram finished executing. So if you want the window stays open you should remove sys.exit() statements and add something at the end of your script like:
input("Press any key to exit: ")
in Python 3 or
raw_input("Press any key to exit: ")
in Python 2

NameError: global name 'Circulo_Mohr_v1_2' is not defined

I'm trying make a simple menu (options: 1,2,3) and the second option (input 2) should run a graphical menu.
When I try run python reports a NameError ("global name 'Circulo_Mohr_v1_2' is not defined").
I don't know the correct syntax
print "inicio"
import sys
from librerias import Circ_Mohr_motor_v2
import librerias.Circulo_Mohr_v1_2
from librerias import prueba_importacion
'''
def definicion_ventana():
Circulo_Mohr_v3_0.Ui_CalculodecirculosMohr()
#Ui_CalculodecirculosMohr.setupUi()
'''
def seleccion_de_libreria():
print '''Escoger opcion:
1) motor
2) Ventana
3) test
'''
opcion = raw_input ("Opcion seleccionada: ")
opcion = int (opcion)
if opcion == 1:
print "se ejecuta el motor de calculo"
punto_Ax = raw_input ("Insertar coordenada X de primer punto: ")
punto_Ay = raw_input ("Insertar coordenada Y de primer punto: ")
punto_Bx = raw_input ("Insertar coordenada X de segundo punto: ")
punto_By = raw_input ("Insertar coordenada Y de segundo punto: ")
Circ_Mohr_motor_v2.circulo_mohr(punto_Ax,punto_Ay,punto_Bx,punto_By)
elif opcion == 2:
print "se ejecuta la funcion ventana"
Circulo_Mohr_v1_2.Ui_CalculodecirculosMohr()
print "fin la funcion ventana"
else:
print "se ejecuta el test"
prueba_importacion.prueba_01()
seleccion_de_libreria()
print "fin"
How can I fix that?
try replace
import librerias.Circulo_Mohr_v1_2
with
from librerias.Circulo_Mohr_v1_2 import Ui_CalculodecirculosMohwith
and call directly Ui_CalculodecirculosMohr()
Ui_CalculodecirculosMohr()

Keep the list through functions

I have this code wrote in Python:
liste_usager = input("Veuillez entrer la liste d'entiers:")
liste = []
for n in liste_usager.split(' '):
liste.append(int(n))
print(liste)
return liste
print('liste enregistrée')
print('que voulez-vous faire?')
boucle = True
while boucle:
print('''
1-afficher la liste
2-trier la liste
3-afficher la valeur maximale
4-afficher la valeur minimale
5-afficher la somme des valeurs
6-inverser la liste
7-modifier la liste
0-retour
''')
choix= input('choissisez une commande:')
if choix =='1':
print(liste_usager)
if choix =='2':
menu_tri()
else:
boucle= False
this just return a list of integer such as [1,2,3]. My problem is that I have other def function/module in this same .py file,and those module needs to use the resulting list of this gestionliste() module.For example a module sort the list,but how to keep the list or transfer it to other modules/functions without asking it again to the user? Thanks!
Return the list from the function, and pass it to other functions.
At the bottom of your function, add
return liste
When you call the function, use:
liste = gestionliste();
When you call a new function, pass it in like this:
otherFunction(liste)
Of course your other function must take it as a parameter.
def otherFunction(liste):
# You can now use liste inside this function.
You have the return the result list.
def gestionliste():
liste_usager = input("Veuillez entrer la liste d'entiers:") #user enter number(s) of his choices
liste = []
for n in liste_usager.split(' '):
liste.append(int(n))
return liste
In your original copy of code, you did not return anything explicitly. So by default, it return None.
And to use the result in another function, to say func2, you could do like:
temp = gestionliste()
func2(temp)
Just change your print to return
def gestionliste():
liste_usager = input("Veuillez entrer la liste d'entiers:") #user enter number(s) of his choices
# I used list comprehension instead of your for loop
liste = [int(n) for n in liste_usager.split(' ')]
return liste
Return liste from the function.
Example:
# In function definiton file
def gestionliste():
liste_usager = input("Veuillez entrer la liste d'entiers:") #user enter number(s) of his choices
liste = []
for n in liste_usager.split(' '):
liste.append(int(n))
return liste
# In your main script
liste = gestionliste()

Categories