applying a QUIT function to mini game in python - python

So I just started with python and I received the following task;
I need to create a mini game where the game choses a random number from 0-10.
Now I got most of my code but it seems I keep having issues with implementing a Quit option.
So the point is that the player can at any time give Quit as an answer and then the game quits.
It seems I can not attribute Quit in the right way.
When typing the Quit command (nee) I keep getting the following error message;
**Traceback (most recent call last):
File "C:\Users\aarabsa\PycharmProjects\projecten1\Lotto1.2.py", line 22, in <module>
guess = int(input('Probeer opnieuw of typ nee om het spel te verlaten: '))
ValueError: invalid literal for int() with base 10: 'nee'**
Could any of you guys give some advise ?
import random
import sys
print("Hello, wat is uw naam?")
naam = input()
print("Kan je de juiste cijfer raden tussen 0 en 10?")
answer = random.randint(0, 10)
guess = int(input('geef uw gekozen nummer: '))
TotalGuesses = 0
while guess != answer:
TotalGuesses += 1
if guess < answer:
print('fout antwoord!')
guess = int(input('Probeer opnieuw of typ nee om het spel te verlaten: '))
if guess in ['nee']:
print('Jammer dat je nu al opgeeft ' + naam + ', tot de volgende keer!')
sys.exit()
elif guess > answer:
print('fout antwoord!')
guess = int(input('Probeer opnieuw of typ nee om het spel te verlaten: '))
if guess in ['nee']:
print('Jammer dat je nu al opgeeft ' + naam + ', tot de volgende keer!')
sys.exit()
if guess == answer:
break
if guess == answer:
print('Correct ' + naam + '! Je hebt ' + str(TotalGuesses) + 'foutief geraden voordat je de juiste antwoord kon vinden!')

You should convert to an int only if you've first made sure the user didn't enter that string. For example:
guess = None # So it's defined
guess_string = input('geef uw gekozen nummer: ')
if guess_string.lower() == 'nee':
... # tell the user goodbye, or whatever
sys.exit()
else:
guess = int(guess_string)
Additionally, you could check that their input is a valid number before converting it and assigning it to guess. Here is an explanation of how you can do that.
Since you get user input multiple times in your program, you could wrap all that up in a function and just call that, so you don't have repeats in your code.

Related

How to avoid "can be undefined" error in Python?

I am trying to make a simple code to input a positive integer in the most accurate way possible. I mention that I am very new to the language.
Here is my code :
while number != None:
try:
while True:
number = int(input("Donnez la longueur de votre liste: "))
if number > 0:
break
except TypeError:
print("Tu doit donner un nombre entier")
The warning I get is number can be Undefined I am not aware of what is the specific situation where number is undefined as the while loop breaks only when number is not None ( means defined according to me ). I’m so grateful for your help. It is a challenging time but you would make it easier.
You can sidestep any warnings with a more idiomatic loop:
while True:
number = input("Donnez la longueur de votre liste: ")
try:
number = int(number)
except ValueError:
print("Tu doit donner un nombre entier")
continue
if number > 0:
break

Python while loops never ends (on a numworks calculator) [duplicate]

This question already has answers here:
Asking the user for input until they give a valid response
(22 answers)
Closed 3 years ago.
Just grabbed a calculator with python integrated (numworks).
I'm writing a python program wich includes a function to check if an input is a number (float).
When i type a proper float number everything goes right, but when an exception is catched here is the behavior:
the except block is run properly
then the while loops restarts, ask my imput again and enter an infite loops and freezes. No time for typing my input again.
I'm not familiar with Python, I'm pretty sure it's a simple syntax thing... But I didn't manage to work it out.
Help would be appreciated!
Here is the code:
# controle de saisie d'un nombre
def inputFloat(text):
ret = ''
while ret is not float:
try:
ret = float(input(text + " (nombre)"))
except ValueError:
print("saisie incorrecte.")
return ret
# test
def test():
print(inputFloat("saisir nombre"))
# affichage du menu
while True:
print("[1] test")
print("[0] quitter")
choix = input("Choisir une fonction:")
if choix == "0":
print("au revoir.")
break
elif choix == "1":
test()
Cheers
PS: infos about the environnement : the calculator uses MicroPython 1.9.4 (source https://www.numworks.com/resources/manual/python/)
Edit
here is the clean working version of the code with all suggestions from you guys.
Pushed it to the calc: works like a charm.
# controle de saisie d'un nombre
def inputFloat(text):
while True:
try:
return float(input(text + " (nombre)"))
except ValueError:
print("saisie incorrecte.")
continue
# test
def test():
print(inputFloat("saisir nombre"))
# affichage du menu
while True:
print("[1] test")
print("[0] quitter")
choix = input("Choisir une fonction:")
if choix == "0":
print("au revoir.")
break
elif choix == "1":
test()
break
I think the simplest way is the following:
def input_float():
while True:
try:
return float(input("Give us a number: "))
except:
print("This is not a number.")
You could also use a recursive version:
def input_float():
try:
return float(input("Give us a number: "))
except:
print("This is not a number.")
return input_float()

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

eval () Unexpected EOF while parsing

So I'm trying to get two inputs that separate usernames by credit hours and every time after I've exited the loop I get an unexpected EOF.
fresh = []
soph = []
jun = []
sen = []
def classify(cr, un):
if cr <= 27:
fresh.append(un)
print(un, 'is a freshman.\n')
elif 28 <= cr <= 56:
soph.append(un)
print(un, 'is a sophomore.\n')
elif 57 <= cr <= 84:
jun.append(un)
print(un, 'is a junior.\n')
elif cr >= 85:
sen.append(un)
print(un, 'is a senior\n')
def main():
un = input('Student: ')
cr = eval(input('Credits: '))
while un and cr != '':
un = input('Student: ')
cr = eval(input('Credits: '))
classify(cr, un)
Specifically the error I get is:
File "./class.py", line 58, in <module>
main()
File "./class.py", line 51, in main
cr = eval(input('Credits: '))
File "<string>", line 0
I'm not sure if it's related (or if it's just something I'm overlooking) but I have to enter through Credit in order to exit the loop. Shouldn't the loop exit after pressing enter when Student comes up due to the AND operator?
edit: added classify func. I don't think this is the problem though, I've tried removing it and it still brings me back to the EOF.
You shouldn't be using eval() to turn a string into an integer. Use int instead.
def main():
un = input('Student: ')
cr = input('Credits: ')
classify(int(cr), un)
while un and cr:
un = input('Student: ')
cr = input('Credits: ')
classify(int(cr), un)
Credits must still be entered even after skipping the student name because the while condition is only evaluated before going into the code block, not after every statement in the block. If you want it to stop immediately when the user skips the student or credit value, do this:
def main():
while 1:
un = input('Student: ')
if not un: break
cr = input('Credits: ')
if not cr: break
classify(int(cr), un)
And, of course, use input for Python 3, and raw_input for Python 2.

Categories