Why does my while loop only run once? - python

I want to make this loop run more than once but it will only run once and then stop. What am I doing wrong?
a = 0
Let = input("Enter a sentence to decrypt : ")
Num = 0
b = 0
while b < 26 :
Num = Num + 1
num = int(Num)
while a < len(Let) :
if ord(Let[a]) > 96 and ord(Let[a]) < 123 and ord(Let[a]) + Num > 96 and ord(Let[a]) + Num < 123 :
print(chr(ord(Let[a]) + Num))
elif ord(Let[a]) > 64 and ord(Let[a]) < 91 and ord(Let[a]) + Num > 64 and ord(Let[a]) + Num < 91 :
print(chr(ord(Let[a]) + Num))
elif ord(Let[a]) > 96 and ord(Let[a]) < 123 and ord(Let[a]) + Num >= 123 :
while ord(Let[a]) + num >= 123 :
num = Num - 26
print(chr(ord(Let[a]) + num))
elif ord(Let[a]) > 64 and ord(Let[a]) < 91 and ord(Let[a]) + Num >= 91 :
while ord(Let[a]) + num >= 91 :
num = Num - 26
print(chr(ord(Let[a]) + num))
a = a + 1
b = b + 1

"a" is not being reset to 0 in the "b" loop:
Let = input("Enter a sentence to decrypt : ")
Num = 0
b = 0
while b < 26 :
Num = Num + 1
num = int(Num)
a = 0
out = ""
while a < len(Let) :
if ord(Let[a]) > 96 and ord(Let[a]) < 123 and ord(Let[a]) + Num > 96 and ord(Let[a]) + Num < 123 :
out += (chr(ord(Let[a]) + Num))
elif ord(Let[a]) > 64 and ord(Let[a]) < 91 and ord(Let[a]) + Num > 64 and ord(Let[a]) + Num < 91 :
out += (chr(ord(Let[a]) + Num))
elif ord(Let[a]) > 96 and ord(Let[a]) < 123 and ord(Let[a]) + Num >= 123 :
while ord(Let[a]) + num >= 123 :
num = Num - 26
out += (chr(ord(Let[a]) + num))
elif ord(Let[a]) > 64 and ord(Let[a]) < 91 and ord(Let[a]) + Num >= 91 :
while ord(Let[a]) + num >= 91 :
num = Num - 26
out += (chr(ord(Let[a]) + num))
a = a + 1
print(out)
b = b + 1
Changed to a "for" loop:
Let = input("Enter a sentence to decrypt : ")
Num = 0
b = 0
while b < 26 :
Num = Num + 1
num = int(Num)
out = ""
for a in Let:
if ord(a) > 96 and ord(a) < 123 and ord(a) + Num > 96 and ord(a) + Num < 123 :
out += (chr(ord(a) + Num))
elif ord(a) > 64 and ord(a) < 91 and ord(a) + Num > 64 and ord(a) + Num < 91 :
out += (chr(ord(a) + Num))
elif ord(a) > 96 and ord(a) < 123 and ord(a) + Num >= 123 :
while ord(a) + num >= 123 :
num = Num - 26
out += (chr(ord(a) + num))
elif ord(a) > 64 and ord(a) < 91 and ord(a) + Num >= 91 :
while ord(a) + num >= 91 :
num = Num - 26
out += (chr(ord(a) + num))
print(out)
b += 1

Related

How to make a Number/Letter interval in Python

So ...
Am writing a code that makes a Matrix table then calculate how many ( uppercase Letter , Lowercase Letter , Numbers , Symbols )
That's the code i tried :
def Proc_Affiche(T,P,X):
Nb_Maj = 0
Nb_Min = 0
Nb_chiffre = 0
Nb_symbole = 0
for i in range(P):
for j in range(X):
if T[i] in ["A","Z"]:
Nb_Maj = Nb_Maj + 1
elif T[i] in ["a","z"] :
Nb_Min = Nb_Min + 1
elif T[i] in range(1,9):
Nb_chiffre = Nb_chiffre + 1
else :
Nb_symbole = Nb_symbole + 1
print("Nb_Maj= ",Nb_Maj)
print("Nb_Min= ",Nb_Min)
print("Nb_chiffre= ",Nb_chiffre)
print("Nb_symbole= ",Nb_symbole)
So the Output should be like that :
Nb_Maj= ...
Nb_Min= ...
Nb_chiffre= ...
Nb_symbole= ...
The Problem is on the part of intervals Like ["A","Z"]
Strings have some functions you can use to check what they contain
.isalpha() is true for letters
.isnumeric() is true for numbers
.isalnum() is true for letters and numbers
.isupper() is true for uppercase
Thus you could do something like
if T[i].isalpha():
if T[i].isupper():
Nb_Maj += 1
else:
Nb_Min += 1
elif T[i].isnumeric():
Nb_chiffre += 1
else:
Nb_symbole += 1
Yes it is , here is the whlole code if that would help :
from math import*
def Proc_saisie():
X = -1
while X < 1 or X > 20 :
X = int(input("Donner un entier entre 5 et 20 : "))
return X
def Proc_Remplir(P,X):
T= [[] for i in range(P)]
for i in range(P):
for j in range(X):
d = input("T["+str(i)+","+str(j)+"]=")
T[i].append(d)
return T
def Proc_Affiche(T,P,X):
Nb_Maj = 0
Nb_Min = 0
Nb_chiffre = 0
Nb_symbole = 0
for i in range(P):
for j in range(X):
if T[i] in ["A","Z"]:
Nb_Maj = Nb_Maj + 1
elif T[i] in ["a","z"] :
Nb_Min = Nb_Min + 1
elif T[i] in range(1,9):
Nb_chiffre = Nb_chiffre + 1
else :
Nb_symbole = Nb_symbole + 1
print("Nb_Maj= ",Nb_Maj)
print("Nb_Min= ",Nb_Min)
print("Nb_chiffre= ",Nb_chiffre)
print("Nb_symbole= ",Nb_symbole)
#---------------------------
L = Proc_saisie()
C = Proc_saisie()
print("L =",L)
print("C =",C)
TAB = []
TAB = Proc_Remplir(L,C)
TAB = Proc_Affiche(TAB,L,C)
I'm not sure I understand what you want 100%, but I think something like follows would fit:
def Proc_Affiche(T,P,X):
Nb_Maj = 0
Nb_Min = 0
Nb_chiffre = 0
Nb_symbole = 0
for i in range(P):
for j in range(X):
if "A" <= T[i][j] <= "Z":
Nb_Maj = Nb_Maj + 1
elif "a" <= T[i][j] <= "z" :
Nb_Min = Nb_Min + 1
elif 1 <= T[i][j] <= 9:
Nb_chiffre = Nb_chiffre + 1
else :
Nb_symbole = Nb_symbole + 1
print("Nb_Maj= ",Nb_Maj)
print("Nb_Min= ",Nb_Min)
print("Nb_chiffre= ",Nb_chiffre)
print("Nb_symbole= ",Nb_symbole)

How do I limit 10 number per line in python

What's the error here?. I cant print the CozaLoza, CozaWoza and LozaWoza. And it only prints from 1-109. I also wants to print 11 output per lines. How can I do that?
for num in range (1, 22):
if (num % 3 == 0):
print("Coza" )
elif (num % 5 == 0):
print("Loza")
elif (num % 7 == 0):
print("Woza")
elif (num % 3 and num % 5 == 0):
print(" CozaLoza")
elif (num % 3 and num % 7 == 0):
print("CozaWoza")
elif (num % 5 and num % 7 == 0):
print("LozaWoza")
else :
print (num)
I updated the code as following:
num = int ( input ( "Enter a number: " ) )
if num < 1 or num > 110:
print("From 1-110 number is allowed")
else :
for n in range ( 1, num ) :
name = str(n)
if n % 3 == 0:
name = "Coza"
elif n % 5 == 0:
name = "Loza"
elif n % 7 == 0:
name = "Woza"
print(name, end=" ")
if (n + 1) % 10 == 0:
print("") # print new line each 10 number prints
The answer for your question is the use of if (n+1) % 10 == 0 and under.
It prints newline for each 10 numbers because of every mupltiple of 10 is True on (n+1) % 10 == 0.
BUT it has some wrongs on other lines.
NOT the for num in range(1, num), it is for n in range(1, num). the num is same with a name of variable in loops and it is ambiguous.
you could omit bracket ( and ) at if, elif statement in Python. if (A) equals if A in python :)
anyway, this is the output when input is 55:
Enter a number: 55
1 2 Coza 4 Loza Coza Woza 8 Coza
Loza 11 Coza 13 Woza Coza 16 17 Coza 19
Loza Coza 22 23 Coza Loza 26 Coza Woza 29
Coza 31 32 Coza 34 Loza Coza 37 38 Coza
Loza 41 Coza 43 44 Coza 46 47 Coza Woza
Loza Coza 52 53 Coza
EDITED: (by updated question)
when num is 10, the code can be reached to elif num % 3 and num % 5 == 0? I don't think so. because it was already True on elif num % 5 == 0 above.
you need to fix your if conditions as like:
if num % 3 == 0:
...
elif num % 5 == 0:
if num % 3:
# CozaLoza
else:
# Loza

Global Variable using while

I am trying to increment a global variable in my code but when I use the key word global it says n has already been used. I am trying to increment n so I can assign each person 1 through 27 to a team.
Thank in advance
my_team = 27 % 4
team_1 = ""
team_2 = ""
team_3 = ""
team_4 = ""
team_5 = ""
team_6 = ""
team_7 = ""
print(my_team)
global n
n = 1
for n in range(1, 28):
while n <= 4 :
global n
team_1 = team_1 + str(n) + " "
n = n + 1
if n == 5:
break
for n in range (4,8):
n= n + 1
team_2 = team_2 + str(n)
while n < 13 and n > 8:
team_3 =team_3 + str(n)
n= n + 1
while n < 17 and n > 12:
team_4 = team_4 + str(n)
n= n + 1
while n < 21 and n > 16:
team_5 = team_5 + str(n)
n= n + 1
while n < 25 and n > 20:
team_6 = team_6 +str(n)
n= n + 1
while n < 28 and n > 24:
team_7 = team_7 + str(n)
n = n+1
print(team_1)
my_team = 27 % 4
team_1 = ""
team_2 = ""
team_3 = ""
team_4 = ""
team_5 = ""
team_6 = ""
team_7 = ""
print(my_team)
n = 1
while n <= 4:
team_1 += str(n) + " "
n += 1
while 4 < n <= 8:
team_2 += str(n) + " "
n += 1
while 8 < n <= 12:
team_3 += str(n) + " "
n += 1
while 12 < n <= 16:
team_4 += str(n) + " "
n += 1
while 16 < n <= 21:
team_5 += str(n) + " "
n += 1
while 21 < n <= 25:
team_6 += str(n) + " "
n += 1
while 25 < n <= 28:
team_7 += str(n) + " "
n += 1
print(team_1)
print(team_2)
print(team_3)
print(team_4)
print(team_5)
print(team_6)
print(team_7)
I've fixed some other problems according to what I think is your goal and made a few other changes which you might be able to learn from.

multiple if else conditions in pandas dataframe and derive multiple columns

I have a dataframe like below.
import pandas as pd
import numpy as np
raw_data = {'student':['A','B','C','D','E'],
'score': [100, 96, 80, 105,156],
'height': [7, 4,9,5,3],
'trigger1' : [84,95,15,78,16],
'trigger2' : [99,110,30,93,31],
'trigger3' : [114,125,45,108,46]}
df2 = pd.DataFrame(raw_data, columns = ['student','score', 'height','trigger1','trigger2','trigger3'])
print(df2)
I need to derive Flag column based on multiple conditions.
i need to compare score and height columns with trigger 1 -3 columns.
Flag Column:
if Score greater than equal trigger 1 and height less than 8 then Red --
if Score greater than equal trigger 2 and height less than 8 then Yellow --
if Score greater than equal trigger 3 and height less than 8 then Orange --
if height greater than 8 then leave it as blank
How to write if else conditions in pandas dataframe and derive columns?
Expected Output
student score height trigger1 trigger2 trigger3 Flag
0 A 100 7 84 99 114 Yellow
1 B 96 4 95 110 125 Red
2 C 80 9 15 30 45 NaN
3 D 105 5 78 93 108 Yellow
4 E 156 3 16 31 46 Orange
For other column Text1 in my original question I have tried this one but the integer columns not converting the string when concatenation using astype(str) any other approach?
def text_df(df):
if (df['trigger1'] <= df['score'] < df['trigger2']) and (df['height'] < 8):
return df['student'] + " score " + df['score'].astype(str) + " greater than " + df['trigger1'].astype(str) + " and less than height 5"
elif (df['trigger2'] <= df['score'] < df['trigger3']) and (df['height'] < 8):
return df['student'] + " score " + df['score'].astype(str) + " greater than " + df['trigger2'].astype(str) + " and less than height 5"
elif (df['trigger3'] <= df['score']) and (df['height'] < 8):
return df['student'] + " score " + df['score'].astype(str) + " greater than " + df['trigger3'].astype(str) + " and less than height 5"
elif (df['height'] > 8):
return np.nan
You need chained comparison using upper and lower bound
def flag_df(df):
if (df['trigger1'] <= df['score'] < df['trigger2']) and (df['height'] < 8):
return 'Red'
elif (df['trigger2'] <= df['score'] < df['trigger3']) and (df['height'] < 8):
return 'Yellow'
elif (df['trigger3'] <= df['score']) and (df['height'] < 8):
return 'Orange'
elif (df['height'] > 8):
return np.nan
df2['Flag'] = df2.apply(flag_df, axis = 1)
student score height trigger1 trigger2 trigger3 Flag
0 A 100 7 84 99 114 Yellow
1 B 96 4 95 110 125 Red
2 C 80 9 15 30 45 NaN
3 D 105 5 78 93 108 Yellow
4 E 156 3 16 31 46 Orange
Note: You can do this with a very nested np.where but I prefer to apply a function for multiple if-else
Edit: answering #Cecilia's questions
what is the returned object is not strings but some calculations, for example, for the first condition, we want to return df['height']*2
Not sure what you tried but you can return a derived value instead of string using
def flag_df(df):
if (df['trigger1'] <= df['score'] < df['trigger2']) and (df['height'] < 8):
return df['height']*2
elif (df['trigger2'] <= df['score'] < df['trigger3']) and (df['height'] < 8):
return df['height']*3
elif (df['trigger3'] <= df['score']) and (df['height'] < 8):
return df['height']*4
elif (df['height'] > 8):
return np.nan
what if there are 'NaN' values in osome columns and I want to use df['xxx'] is None as a condition, the code seems like not working
Again not sure what code did you try but using pandas isnull would do the trick
def flag_df(df):
if pd.isnull(df['height']):
return df['height']
elif (df['trigger1'] <= df['score'] < df['trigger2']) and (df['height'] < 8):
return df['height']*2
elif (df['trigger2'] <= df['score'] < df['trigger3']) and (df['height'] < 8):
return df['height']*3
elif (df['trigger3'] <= df['score']) and (df['height'] < 8):
return df['height']*4
elif (df['height'] > 8):
return np.nan
Here is a way to use numpy.select() for doing this with neat code, scalable and faster:
conditions = [
(df2['trigger1'] <= df2['score']) & (df2['score'] < df2['trigger2']) & (df2['height'] < 8),
(df2['trigger2'] <= df2['score']) & (df2['score'] < df2['trigger3']) & (df2['height'] < 8),
(df2['trigger3'] <= df2['score']) & (df2['height'] < 8),
(df2['height'] > 8)
]
choices = ['Red','Yellow','Orange', np.nan]
df['Flag1'] = np.select(conditions, choices, default=np.nan)
you can use also apply with a custom function on axis 1 like this :
def color_selector(x):
if (x['trigger1'] <= x['score'] < x['trigger2']) and (x['height'] < 8):
return 'Red'
elif (x['trigger2'] <= x['score'] < x['trigger3']) and (x['height'] < 8):
return 'Yellow'
elif (x['trigger3'] <= x['score']) and (x['height'] < 8):
return 'Orange'
elif (x['height'] > 8):
return ''
df2 = df2.assign(flag=df2.apply(color_selector, axis=1))
you will get something like this :

Python for loop breaks text based game

#!/usr/bin/env python
import random
import time
import os
class vars:
running = 1
def win ():
print("You escaped!")
vars.running = 0
time.sleep(4)
return 0
def main ():
char_loc = 11 #The characters current co-ordinates in XY format
pos_char_loc = 11
ex_y = random.randint(1, 5)
ex_x = random.randint(1, 5) * 10
ex_loc = ex_x + ex_y
while vars.running == 1:
os.system('CLS')
x0 = ["#"] * 5
x1 = ["#"] * 5
x2 = ["#"] * 5
x3 = ["#"] * 5
x4 = ["#"] * 5
if (char_loc >= 11 and char_loc <= 55):
if (char_loc >= 11 and char_loc <= 15):
i = 0; k = 11
for x in range(0, 4):
if char_loc == k:
x0.insert(i, '#')
else:
i += 1
k += 1
if (char_loc >= 21 and char_loc <= 25):
i =0; k = 21
for loop1 in range(0, 4):
if char_loc == k:
x1.insert(i, '#')
else:
i += 1
k += 1
if (char_loc >= 31 and char_loc <= 35):
i =0; k = 31
for loop2 in range(0, 4):
if char_loc == k:
x2.insert(i, '#')
else:
i += 1
k += 1
if (char_loc >= 41 and char_loc <= 45):
i =0; k = 41
for loop3 in range(0, 4):
if char_loc == k:
x3.insert(i, '#')
else:
i += 1
k += 1
if (char_loc >= 51 and char_loc <= 55):
i =0; k = 51
for loop5 in range(0, 4):
if char_loc == k:
x4.insert(i, '#')
else:
i += 1
k += 1
else:
print("fail")
print( x0[4],x1[4],x2[4],x3[4],x4[4])
print( x0[3],x1[3],x2[3],x3[3],x4[3])
print( x0[2],x1[2],x2[2],x3[2],x4[2])
print( x0[1],x1[1],x2[1],x3[1],x4[1])
print( x0[0],x1[0],x2[0],x3[0],x4[0])
print(char_loc, ex_loc)
if char_loc == ex_loc:
win()
move = input()
if move == "w" and (char_loc != 15 and char_loc != 25 and char_loc != 35 and char_loc != 45 and char_loc !=55):
char_loc += 1
print("up")
elif move == "s" and (char_loc != 11 and char_loc != 21 and char_loc != 31 and char_loc != 41 and char_loc != 51):
char_loc -= 1
print("down")
elif move == "a" and (char_loc != 11 and char_loc != 12 and char_loc != 13 and char_loc != 14 and char_loc != 15):
char_loc -= 10
print("left")
elif move == "d" and (char_loc != 51 and char_loc != 52 and char_loc != 53 and char_loc != 54 and char_loc != 55):
char_loc += 10
print("right")
else: print("You can't move there!")
if __name__ == '__main__': main()
I'm trying to make a simple text based game where you move the '#' around a grid of '#'s
and try to find the exit. I've changed the code to make it easier for me to make the grid bigger or smaller without adding or deleting huge chunks of code and it keeps on giving me this output:
fail
# # # # #
# # # # #
# # # # #
# # # # #
# # # # #
11 52
and I can't figure out what's wrong with it! Only one '#' is supposed to appear :(
I am only a newbie at python so if you have any tips for improving this please, don't hesitate, and post them!
Thanks in advance,
I think the "fail" occurs because it will occur every time the char_loc is not between 51 and 55.
if (char_loc >= 11 and char_loc <= 15):
if (char_loc >= 21 and char_loc <= 25):
if (char_loc >= 31 and char_loc <= 35):
if (char_loc >= 41 and char_loc <= 45):
if (char_loc >= 51 and char_loc <= 55):
else:
What I think you'd want to do here is use elif, which will only fire if the previous checks don't trigger.
if (char_loc >= 11 and char_loc <= 15):
elif (char_loc >= 21 and char_loc <= 25):
elif (char_loc >= 31 and char_loc <= 35):
elif (char_loc >= 41 and char_loc <= 45):
elif (char_loc >= 51 and char_loc <= 55):
else:
In regards to the multiple # symbols, I think this may play a part. Currently you have:
if char_loc == k:
x0.insert(i, '#')
else:
i += 1
k += 1
What I think you're looking to do is:
if char_loc == k:
x0.insert(i, '#')
i += 1
k += 1
Since you want k to change every time that loop iterates.
One last thing that I would suggest is since you have:
i =0; k = 21
i =0; k = 31
i =0; k = 41
i =0; k = 51
You will probably want to add
i =0; k = 11
To the first one.
Hope that helps.

Categories