It's a guessing game and at the end of the code I want to ask if they would like to play the game again. If they do say yes then it start back from the top and if they say no the program ends. This is what i currently have not sure what i did wrong, ive had some help and this is what i have so far
import random
name = input('Entrez votre nom: ')
Kilo = input (name + ' Veux-tu jouer un jeu ')
def play(name):
randomNumber = random.randrange(0,100)
guessed = False
want_to_play = True
while want_to_play:
print("Un nombre aléatoire a été généré 1 a 100 ")
while guessed==False:
userInput = int(input("Entrez votre estimation: "))
if userInput==randomNumber:
guessed = True
print("Bien joué!")
elif userInput>100:
print("Notre fourchette est entre 0 et 100, essayez un peu plus bas")
elif userInput<0:
print("Notre fourchette est comprise entre 0 et 100, essayez un peu plus haut ")
elif userInput>randomNumber:
print("Essayez une fois de plus, un peu plus bas")
elif userInput < randomNumber:
print("Essayer une fois de plus, un peu plus haut")
You could encapsulate your game into a function. Then, use a loop around the function call:
name = input('Entrez votre nom: ')
def play(name):
randomNumber = random.randrange(0,100)
guesses = False
# etc...
want_to_play = True
while want_to_play:
play(name) # This start your game
want_to_play = input('Veux tu encore jouer? (O/N)')
if want_to_play.lower() == 'o':
want_to_play = True
elif want_to_play.lower() == 'n':
want_to_play = False # EDIT: oups, thanks Primusa
else:
print('invalid input!')
want_to_play = False
Related
Im using objects.create to create object o my model. Using the following logic. But payment_quantity (somehow) is setting to NoneType. And not setting to the value i passed into objects.create
class PrizesExchangeModeResourceBMR(resources.ModelResource):
#transaction.atomic
def create_exchange_mode(self, code, points, price):
cuotas = [1,3,6,12] # array de cuotas
prize = Prize.objects.filter(code = code) # busca el premio
if len(prize) != 0: # si existe el premio
PrizesExchangeMode.objects.create( #crea puntos al 100%, 0 cuotas
prize = prize[0],
payment_amount = 0,
points_value = points,
payment_quantity=0,
price_value = 0
)
puntos = round(points/2)
for cuota in cuotas: # crea con puntos al 50% y [1,3,6,12] cuotas
valor = round(price/cuota)
PrizesExchangeMode.objects.create(
prize = prize[0],
payment_amount = valor,
points_value = puntos,
payment_quantity = 0.0,
price_value = 0.0)
else:
print("Premio no encontrado") # no existe el premio
def get_instance(self,instance_loader, row):
self.get_queryset().get(prize__code=row.get('prize'))
def save_instance(self, instance, using_transactions, dry_run):
code = instance.prize.code #guarda el codigo
points = instance.points_value # guarda puntos
price = instance.payment_amount # guarda precio
self.create_exchange_mode(code, points, price) # se lo pasa a la funcion anterior
class Meta:
model = PrizesExchangeMode
fields = ("prize", "points_value", "payment_amount") # Campos que queremos importar
Since I've been leaning Python, I have often seen and used :
class FicheDeleteView(LoginRequiredMixin, DeleteView):
model = Fiche
success_url = reverse_lazy('fiche-list')
success_messages = "La Fiche %(ref_id)s a bien été supprimée"
def delete(self, request, *args, **kwargs):
fiche = self.get_object()
messages.success(self.request, self.success_messages %
fiche.__dict__)
return super(FicheDeleteView, self).delete(request, *args, **kwargs)
Even if I see this mechanic's effects, I'm not really sure to understand.
Does it mean : I send to the "reverse-lazy" all the FICHE dict and in my message.success I retrieve the fiche.ref_id with %(ref_id)s ?
The % operator is an old string formatting placeholder, which lets you include variables in your string. So if you would want to include the variable name in your string then you could use the % operator as a placeholder.
name = 'world'
print('Hello, %s' % name)
>>> Hello, world
In your example, the % operator in success_message is taking a dictionary as variable and then accessing the value from the key ref_id in this dictionary.
success_messages = "La Fiche %(ref_id)s a bien été supprimée"
example_dict = {'key_1': 'value_1', 'ref_id': 'value_2'}
print(success_messages % example_dict)
>>> La Fiche value_2 a bien été supprimée
From Python >= 3.6 you can use f-strings which makes it more readable:
example_dict = {'key_1': 'value_1', 'ref_id': 'value_2'}
print(f"La Fiche {example_dict['ref_id']} a bien été supprimée")
>>> La Fiche value_2 a bien été supprimée
You can read more about python string formatting here
j = True
while j == True:
area = raw_input("Elije la figura geometrica para calcular su area
\nCuadrado=1 \nTriangulo=2 \nCirculo=3\n")
if area == 1 :
acuadrado()
the problem is in the area.It is something in the syntax?
raw_input in python2.x returns a "string" representation of the users input. Your wanting to do numerical comparison on the input, so you'll want to cast the area variable to an integer (int) before performing the comparison. Something like the following:
area = int(raw_input("Elije la figura geometrica..")
or
area = raw_input("Elije ...")
area = int(area)
then you can compare int values:
if area == 1 :
acuadrado()
etc...
altogether something like this might help you get along:
def acuadrado():
print 'acuadrado'
def atriangulo():
print 'atriangulo'
def acirculo():
print 'acirculo'
j = True
while j == True:
area = raw_input("Elije la figura geometrica para calcular su area \nCuadrado=1 \nTriangulo=2 \nCirculo=3\n")
area = int(area)
if area == 1 :
acuadrado()
elif area == 2:
atriangulo()
elif area == 3:
acirculo()
else:
print 'nada'
j = False
Also see How can I convert a string to an int in Python?
Hope that helps.
I am trying to do a multipectral camera calibration using Open Cv2 and Python 2.7, and the code is working well with the pictures that I have from the 3 monochrome sensors (RED, NIR, and GRE) and the RGB ones. The only pictures that are not working in the code are the pictures from the REG sensor (Red Green).
The code reads the pictures, converts them to gray and then finds the corners, the SubPixels, and finally producres a camera calibration matrix.
I have built the code with multiple print in each part so that I will know which is the exact part that is not working, so I know that it is not working for the REG case in the cv2.findChessboardCorners line.
ret, Bords_Trouves = cv2.findChessboardCorners(Images_en_gris, Lignes_et_Collones, None)
So my question is :
What's not working in the code ? Or is it a problem with the REG sensor pictures, I would have to try another approach to convert them to gray ? Or what ?
Here is all the code:
# -*- coding: utf-8 -*-
import numpy as np
import cv2
import glob
import math
import pickle
import matplotlib.pyplot as plt
critere = (cv2.TERM_CRITERIA_MAX_ITER | cv2.TERM_CRITERIA_COUNT, 10, 0.01)
Lignes = 13
Collones = 13
Collones_et_Lignes = (Collones, Lignes)
Lignes_et_Collones = (Lignes, Collones)
Points_Reels = np.zeros((Lignes*Collones, 3), np.float32)
Points_Reels[:, :2] = np.mgrid[0:Lignes, 0:Collones].T.reshape(-1, 2)
# Préparer deux tableaux pour sauvegarder les points objet et points images de totues les images trouvées.
Tableau_points_reels = []
Tableau_points_imaginaires = []
# Les photos du damier qu'on a pris pour le test
Source = "C:/Users/Mourad/Desktop/Calib1804/REG/"
Mes_Images = glob.glob(Source + '*.TIF')
print "les images ont bien étaient récupérées." if Mes_Images else "PROBLEME: images non récupérés !! "
for leo, fname in enumerate(Mes_Images):
print("Image : " + fname)
#if leo > 10:
# break
image_originale = cv2.imread(fname)
Images_en_gris = cv2.cvtColor(image_originale, cv2.COLOR_BGR2GRAY)
print "les images ont bien étaient transformés en gris." if Images_en_gris.all() else "PROBLEME: images non transformés en gris!! "
ret, Bords_Trouves = cv2.findChessboardCorners(Images_en_gris, Lignes_et_Collones, None)
print str(len(Bords_Trouves)) + " Bords trouvés" if ret else "PROBLEME: Bords Non trouvés !!"
Tableau_points_reels.append(Points_Reels)
PL = (11, 11)
Plus_de_precision = cv2.cornerSubPix(Images_en_gris, Bords_Trouves[1], PL, (-1, -1), critere)
print "Sub pixels trouvées" if Plus_de_precision else "PROBLEME: Pas de sub pixels trouvées"
Tableau_points_imaginaires.append(Bords_Trouves)
# far = cv2.drawChessboardCorners(image_originale, Lignes_et_Collones, Bords_Trouves, ret)
#cv2.imshow("Bords trouvées déssinés sur l'image originale", image_originale)
#cv2.waitKey(500)
#()
print "Nombre de points réels trouvés: " + str(len(Tableau_points_reels))
print "Nombres de points imaginaires trouvés: " + str(len(Tableau_points_imaginaires))
h, w = Images_en_gris.shape[:2]
derik, matrice, distortion, vecteur_de_rotation, vecteur_de_translation = cv2.calibrateCamera(Tableau_points_reels, Tableau_points_imaginaires, (w, h), None, None, flags=cv2.CALIB_RATIONAL_MODEL)
print "La matrice de calibration est: "
print matrice
print "La distortion est egale a: "
print distortion
print "Le vecteur de rotation est egal a: "
print vecteur_de_rotation
print "Le vecteur de translation est egal a: "
print vecteur_de_translation
print "\n La matrice de calibration trouvée et données récupérés" if derik else "PROBLEME: Pas de calibration"
newcameramtx, roi = cv2.getOptimalNewCameraMatrix(matrice, distortion, (w, h), 1, (w, h))
# undistortion
Image_calibree = cv2.undistort(image_originale, matrice, distortion, None, newcameramtx)
fgh = cv2.imread("C:/Users/Mourad/Desktop/Calib1804/RGB/IMG_700101_000800_0000_RGB.JPG")
h, w = fgh.shape[:2]
x, y, w, h = roi
Image_calibree = Image_calibree[y:y+h, x:x+w]
cv2.imwrite('Desktop/imagecalibre.png', Image_calibree)
plt.subplot(121), plt.imshow(fgh), plt.title('image originale')
plt.subplot(122), plt.imshow(Image_calibree), plt.title('image calibree')
plt.show()
Erreur_totale = 0
for i in xrange(len(Tableau_points_reels)):
imgpoints2, _ = cv2.projectPoints(Tableau_points_reels[i], vecteur_de_rotation[i], vecteur_de_translation[i], matrice, distortion)
Erreur = cv2.norm(Tableau_points_imaginaires[i], imgpoints2, cv2.NORM_L2)/len(imgpoints2)
Erreur_totale += Erreur
print "Erreur totale: ", Erreur_totale/len(Tableau_points_reels)
cv2.destroyAllWindows()
If that same piece of code worked for the images from other sensors there has to be something wrong with the pictures you hand to cv2.findChessboardCorners.
Try visualizing the images with cv2.imshow before the go into the function. Probably the color conversion is wrong because with cv2.COLOR_BGR2GRAY a 3-channel image is converted to grayscale but you should have two channels, if I understood your format right.
cv2.findChessboardCorners should also work with color images so the easiest solution may just be skipping the color conversion if that's what messes up your images.
Hi guys I have a syntax error that I really don't understand... Anyone can help?
I get this message on the console:
File "./data_4.0.1.py", line 170
elif:
^
SyntaxError: invalid syntax
The error is raised on this elif:
#controllo ultimo timestamp
elif:
with open(nomen, 'rb') as f:
last_timestamp = f.readlines()[-1].split(",")[0]
Here is my code:
def funzione_aggiornamento_prezzi(titolo,timeframe,lookback):
#parametri per scaricare lo storico dei prezzi
if timeframe =='TBT':
lookback = 0
elif timeframe =='1M':
lookback = 7
elif timeframe =='5M':
lookback = 60
elif timeframe =='60M':
lookback = 180
elif timeframe =='1D':
lookback = 1800
params = {'item': titolo,
'frequency': timeframe,
'dataDa':x_giorni_fa(lookback)}
try:
r = requests.get(myurl, params=params)
except:
pprint("Si e' verificato un errore")
else:
pprint(r.status_code)
pprint(r.url)
new_list = crea_lista(r)
#codice per scrivere su di un csv da una lista
nomen = "%s.%s.csv" % (titolo,timeframe)
csvfile = open(nomen, 'a')
reportwriter = csv.writer(csvfile, quoting=csv.QUOTE_MINIMAL)
#codice per scrivere su di un csv
#controllo del numero di rows nel file
with open(nomen,"r") as f:
reader = csv.reader(f,delimiter = ",")
data = list(reader)
row_count = len(data)
if row_count == 0:
for i in new_list:
da_appendere = i
reportwriter.writerow(da_appendere)
csvfile.close()
#controllo ultimo timestamp
elif:
with open(nomen, 'rb') as f:
last_timestamp = f.readlines()[-1].split(",")[0]
#codice per appendere solo i nuovi dati
found_it = 0
for i in range((len(new_list))-1):
if new_list[i] == last_timestamp:
found_it = 1
if found_it == 1:
this_elem = new_list[i]
next_elem = new_list[(i+1)]
#print(this_elem)
#print(next_elem)
da_appendere1 = next_elem
reportwriter.writerow(da_appendere1)
csvfile.close()
for i in lista_indici:
for j in lista_timeframe:
funzione_aggiornamento_prezzi(i,j,lookback)
you end the if block in the previous line when put a instruction at the same level indentation that the if statement
if condition:
stuff
something # doing this close the if block
and a elif can only happen in a if block
and you do that in
if row_count == 0:
for i in new_list:
da_appendere = i
reportwriter.writerow(da_appendere)
csvfile.close() #<-- here you close the if block
#controllo ultimo timestamp
elif: #<-- you forgot the condition, and is outside of a 'if' block
with open(nomen, 'rb') as f:
last_timestamp = f.readlines()[-1].split(",")[0]
futhermore you forget to put a condition in the elif, if you don't need one use else instead
If you do not have another if statement, you should use else instead of elif.
See the documentation regarding control-flow.