I have a little problem who block me, I've a work where I must to convert a number to Shadocks (base 4 it seems), and I must to make a decrypter.
So I made the first part, but my code won't work on the second.
Here it's :
def Base10toShadocks(n):
q = n
r = 0
Base4=[]
Shads=["GA","BU","ZO","MEU"]
if q == 0:
Base4.append(0)
else:
while q > 0:
q = n//4
r = n%4
n = q
Base4.append(r)
Base4.reverse()
VocShad = [Shads[i] for i in Base4]
print(VocShad)
def ShadockstoBase10(n):
l=len(n)
Erc_finale=[]
for i in range(l):
Sh=(n[i])
i=i+1
if Sh =="a":
Erc_finale.append(0)
elif Sh =="b":
Erc_finale.append(1)
elif Sh =="o":
Erc_finale.append(2)
elif Sh =="e":
Erc_finale.append(3)
print(Erc_finale)
F=str(Erc_finale)
print(F)
F=F.replace("[","")
F=F.replace("]","")
F=F.replace(",","")
F=F.replace(" ","")
L2=len(F)
F=int(F)
print(L2)
print(F)
r=0
while f < 4 or F ==4:
d=(F%4)-1
F=F//4
print(d)
r=r+d*(4**i)
print(r)
inp = 0
inp2 = 0
print("Tapez \"1\" pour choisir de traduire votre nombre en shadock, ou \"2\" pour inversement")
inp = int(input())
if inp == 1:
print("Quel est le nombre ?")
inp2 = int(input())
if inp2 != None:
Base10toShadocks(inp2)
elif inp == 2:
print("Quel est le nombre ?")
inp2 = str(input())
if inp2 != None:
ShadockstoBase10(inp2)
It blocks at the F=int(F), I don't understand why.
Thanks for your help.
First, some errors in your code:
for i in range(l):
Sh=(n[i])
i=i+1 #### Won't work. range() will override
##### Where do "a","b","o","e" come from
##### Shouldn't it be "G","B","Z","M" ("GA","BU","ZO","MEU")?
if Sh =="a":
Erc_finale.append(0)
elif Sh =="b":
Erc_finale.append(1)
elif Sh =="o":
Erc_finale.append(2)
elif Sh =="e":
Erc_finale.append(3)
print(Erc_finale)
F=str(Erc_finale) ### Not how you join an array into a string
Here's a corrected way:
def ShadockstoBase10(n):
n = n.upper(); # Convert string to upper case
l = len(n)
Erc_finale = "" # Using a string instead of an array to avoid conversion later
i = 0
while i < l: # while loop so we can modify i in the loop
Sh = n[i:i+2] # Get next 2 chars
i += 2 # Skip 2nd char
if Sh == "GA":
Erc_finale += "0"
elif Sh == "BU":
Erc_finale += "1"
elif Sh == "ZO":
Erc_finale += "2"
elif Sh =="ME" and "U" == n[i]:
Erc_finale += "3"
i += 1; # MEU is 3 chars
else:
break; # bad char
return int(Erc_finale, 4) # Let Python do the heavy work
Like everything in Python, there are other ways to do this. I just tried to keep my code similar to yours.
Related
The goal of the code is to add ub before any vowel (klinker) to a new sentence (nieuwe_zin). or to decode sentences.
I want to add a feature where if the last 2 characters in the zin(sentence) are "ub" they will not be deleted when decoded. So that words like club dont become cl.
from pcinput import getString
while True:
zin = getString("Give a sentence")
cd = getString("Coding or decoding (c/d)")
cd = cd.lower()
klinkers = ("eaiou")
nieuwe_zin = ("") zin= zin.lower()
if cd == "c":
for i in range (len(zin)):
if zin[i] in klinkers:
nieuwe_zin += "ub" + zin[i]
else:
nieuwe_zin += zin[i]
print (nieuwe_zin)
break
if cd == "d":
i = 0
while i < len(zin):
if zin[i:i+2] == "ub":
i += 2
if zin[i:i+4] == "ubub":
i += 0
else:
nieuwe_zin += zin[i]
i += 1
print(nieuwe_zin)
break
else:
print ("C or D")
I tried
if zin[i:-2] =="ub":
i = -1
nieuwe_zin = zin + "ub"
EDITED: To account for multiple instances of "ub" as in "clubub"
from pcinput import getString
while True:
zin = getString("Give a sentence")
cd = getString("Coding or decoding (c/d)")
cd = cd.lower()
klinkers = ("eaiou")
nieuwe_zin = ("")
zin= zin.lower()
if cd == "c":
for i in range (len(zin)):
if zin[i] in klinkers:
nieuwe_zin += "ub" + zin[i]
else:
nieuwe_zin += zin[i]
print (nieuwe_zin)
break
if cd == "d":
i = 0
while i < len(zin):
if zin[i:i+3] == "ubub":
i += 3
nieuwe_zin += zin[i]
i += 1
print(nieuwe_zin)
break
else:
print ("C or D")
Cleaned up and optimized version:
from pcinput import getString
while True:
zin = getString("Give a sentence").lower()
cd = getString("Coding or decoding (c/d)").lower()
nieuwe_zin = ""
klinkers = "eaiou"
if cd == "c":
nieuwe_zin = "".join(["ub" + char if char in klinkers else
char for char in zin])
print(nieuwe_zin)
break
elif cd == "d":
i = 0
while i < len(zin):
if zin[i:i+3] == "ubub":
i += 3
nieuwe_zin += zin[i]
i += 1
print(nieuwe_zin)
break
else:
print("Please enter either 'c' or 'd'.")
My Problem is on line 25 when it says
if conformation == 1:
for i in range(l, len(lines[k]), 1):
if lines[k][i].isdigit() or lines[k][i].istitle():
f += lines[k][i]
if f in var:
print(var[f])
What my issue is is that the "f" string isn't being added to and its value stays as "". For context, I'm trying to make my own sort of mini programming language, and I'm trying to make prints read for variables. Every time it loops to set f to the variable name, nothing happens. The only way I get remotely close to finding the variable name is by doing "print(lines[k][i])" before the "if lines[k][i]" condition.
Note: I was using a debugger, and I'm not sure if the "if f in var" condition is even being checked.
Python code that reads my custom programming language:
⌄⌄⌄⌄⌄⌄⌄⌄⌄⌄⌄⌄⌄⌄⌄⌄⌄⌄⌄⌄⌄⌄⌄⌄⌄⌄⌄⌄⌄⌄⌄⌄⌄⌄⌄⌄⌄⌄⌄⌄⌄⌄⌄⌄⌄⌄⌄⌄⌄⌄⌄⌄⌄⌄⌄⌄⌄⌄⌄⌄⌄⌄⌄⌄⌄⌄⌄⌄⌄⌄⌄⌄⌄⌄⌄⌄⌄⌄⌄⌄⌄⌄⌄⌄⌄⌄⌄⌄⌄⌄⌄⌄⌄⌄⌄⌄⌄⌄⌄⌄⌄⌄⌄⌄⌄
code = open("HelloWorld.sabo", 'r')
lines = code.readlines()
var = {}
for k in range(0, len(lines), 1):
conformation = 0
temp = ""
temp2 = ""
if lines[k][0:5] == "print":
r = 0
l = 0
p = False
f = ""
for i in lines[k]:
r += 1
if not p:
l += 1
if i == "(":
p = True
conformation += 1
if i == "\"" and conformation == 1:
conformation += 1
if conformation == 2:
break
if conformation == 1:
for i in range(l, len(lines[k]), 1):
if lines[k][i].isdigit() or lines[k][i].istitle():
f += lines[k][i]
if f in var:
print(var[f])
if conformation == 2:
for i in range(r, len(lines[k]), 1):
if not lines[k][i] == "\"":
f += lines[k][i]
else:
break
print(f)
elif lines[k][0:4] == "var ":
for i in range(4, len(lines[k]), 1):
if not lines[k][i] == " ":
temp += lines[k][i]
else: break
for i in range(4, len(lines[k])):
if lines[k][i] == "=":
conformation = 1
elif conformation == 1:
if not lines[k][i] == " ":
temp2 += lines[k][i]
elif not temp2 == "":
break
var[temp] = temp2.strip()
Code that is being read by the above script:
⌄⌄⌄⌄⌄⌄⌄⌄⌄⌄⌄⌄⌄⌄⌄⌄⌄⌄⌄⌄⌄⌄⌄⌄⌄⌄⌄⌄⌄⌄⌄⌄⌄⌄⌄⌄⌄⌄⌄⌄⌄⌄⌄⌄⌄⌄⌄⌄⌄⌄⌄⌄⌄⌄⌄⌄⌄⌄⌄⌄⌄⌄⌄⌄⌄⌄⌄⌄⌄⌄⌄⌄⌄⌄⌄⌄⌄⌄⌄⌄⌄⌄⌄⌄⌄⌄⌄⌄⌄⌄⌄⌄⌄⌄⌄⌄⌄⌄⌄⌄⌄⌄⌄⌄⌄
var val = hello
print(val)
So, I was being a bit dumb with this, but I found out that if I just account for Uppercase and Lowercase characters, then it will work.
if lines[k][i].islower() or lines[k][i].isdigit() or lines[k][i].isnumeric() or lines[k][i].istitle():
f += lines[k][i]
I might have gone overboard with the security though I'm just not sure about the difference isdigit and isnumeric.
Good afternoon! I'm a beginner in coding and i'm trying to do an exercise done for Python.
Building a nested While Loop, i'm with a bug in my little he last line of the code says elif continua == "N"or "n": i = -1 and it should exit all the while loop (the nested and the first one), since i=-1 and the condition for the while loop to work in this code is i > 0 (or at least this is my purpose doing this line of coding.). But all of the sudden the loop starts again and i dont know why.
Can someone help me to get out of this loop?
b = 0
i = 1
valorTotal = 0.00
Audiencia = True
listadevalores = []
while i >= 0:
a = int(input("Digite a quantidade de itens de audiência que serão calculados: "))
i=a+1
while i>1:
a=0
v = float(input ("Insira os valores: "))
valorTotal = valorTotal + v
b+=1
i-=1
listadevalores.append(v)
if b>1:
if listadevalores[b-1] < listadevalores[b-2]:
Audiencia = False
else:
if Audiencia == True
print ("Audiência sempre crescente. Média de audiência: ", (valorTotal/b))
elif Audiencia == False
print ("Audiência nem sempre crescente. Média de audiência: ",(valorTotal/b))
continua = input ("Deseja continuar? S/N")
if continua == "S"or "s":
b=0
valorTotal = 0.00
Audiencia = True
listadevalores = []
i=0
elif continua == "N"or "n":
i = -1
There were several errors in your code.
missing : at the end of if or elif statemennts
several incorrect intendations (maybe a formating issue while copy paste)
You cannot chain bool checks lile continua == "N" or "n" use continua == 'n' or continua == 'N' or in this case even better continua.lower() == 'n'
You are searching for break. Here is a working version of your code:
b = 0
i = 1
valorTotal = 0.00
Audiencia = True
listadevalores = []
while i >= 0:
a = int(input("Digite a quantidade de itens de audiência que serão calculados: "))
i=a+1
while i>1:
a=0
v = float(input ("Insira os valores: "))
valorTotal = valorTotal + v
b+=1
i-=1
listadevalores.append(v)
if b>1:
if listadevalores[b-1] < listadevalores[b-2]:
Audiencia = False
else:
if Audiencia == True:
print ("Audiência sempre crescente. Média de audiência: ", (valorTotal/b))
elif Audiencia == False:
print ("Audiência nem sempre crescente. Média de audiência: ",(valorTotal/b))
continua = input ("Deseja continuar? S/N")
if continua.lower() == "s":
b=0
valorTotal = 0.0
Audiencia = True
listadevalores = []
i=0
elif continua.lower() == "n":
break
The flow of your code is a bit hard to read. Especially it is difficult to understand what your i,a,b variables are doing. Here is a second version which showes how to make your code a bit easier to understand.
def floatInput(input_str):
number = None
while not number:
try:
number = float(input (input_str))
except:
print('not a float number in Portuguese')
return number
while True:
a = int(floatInput("Digite a quantidade de itens de audiência que serão calculados: "))
listadevalores = []
for i in range(a):
v = floatInput("Insira os valores: ")
listadevalores.append(v)
mean = sum(listadevalores) / len(listadevalores)
if sorted(listadevalores) == listadevalores:
print ("Audiência sempre crescente. Média de audiência: ", (mean))
else:
print ("Audiência nem sempre crescente. Média de audiência: ",(mean))
continua = input ("Deseja continuar? S/N")
if continua.lower() == "s":
continue
break
Here is some explanation to the improved parts.
Inputs
The input may be not a number although it is needed. This might create crashes. The exception for strings that cannot be parsed are handled by try: ... except: The second while loop is moved in a seperate function and out of the main flow to make it easier to read. Also it now can be called several times without the need for reapeating code. The while loop is self terminating when number gets a valid value.
Variabels
The meaning of i,a and b are not directly self explanatory. Also they are set at different positions in the code. You already have all information you need in the list.
Ascending lists by definition does not change when they get sorted. We can use this trick to check if the sorted list is the original list sorted(listadevalores) == listadevalores. So we don't need to work on the list elements.
The mean value can be calculated by dividing the sum of all list elements, using the build in sum by the lengt of the list sum(listadevalores) / len(listadevalores).
It seems that you have wrong indentation in question. Please fix this.
Also, it may help you:
create variable that tells your loops to proceed and set it to False when you need to stop the loops. An example:
loop = True
while your_condition and loop:
// Do some stuff here
while your_next_condition and loop:
// Do some stuff here
if something_happened:
loop = False
I'm trying to code a simple calculator.
Below is the Updated code. But still same error.
running = True
while running:
print("1 Addition \
2 Subtraction \
3 Multiplication \
4 Division \
5 remainder \
6 Power of \
7 Quit")
O = int(input('What Operaton you want to do ? '))
F = float(input('Enter first number: '))
S = float(input('Enter Second number: '))
if O == 1:
R = F + S
print(F,'+',S,'=',R)
elif O == 2:
R = F - S
print(F,'-',S,'=',R)
elif O == 3:
R = F * S
print(F,'*',S,'=',R)
elif O == 4:
R = F / S
print(F,'/',S,'=',R)
elif O == 5:
R = F % S
print(F,'%',S,'=',R)
elif O == 6:
R = F ** S
print(F,'**',S,'=',R)
else:
print('Quit')
running = False
And while running I'm facing the Below error.
$/usr/local/bin/python3.7 file1.py
File "file1.py", line 20
R = F - S ^
TabError: inconsistent use of tabs and spaces in indentation
You're indenting your while statement unnecessarily.
running = True
while running:
should be:
running = True
while running:
There is another problem though:
Instead of:
else O == 7:
print('Quit')
running = False
You should write:
else:
print('Quit')
running = False
else doesn't take any argument. It is simple the set of statements chosen when no if or elif condition is true.
during the execution of the code the program skips all ELIF conditions, going directly to ELSE, even if the ELIF condition is TRUE
a = 0
b = 0
c = 0
r = 0
soma = 1
sub = 2
div = 3
mult = 4
print('enter the number corresponding to the operation you want to do:\n')
print('Sum [1]')
print('Subtraction[2]')
print('Divisao [3]')
print('Multiplication [4]')
r = int(1)
while (r == 1):
operacao = 0
operacao = input('\n>')
if operacao == soma:
a = int(input('Enter the value of a:'))
b = int(input('Enter the value of b:'))
c = a + b
print ('\n A Soma de {} mais {} equivale a: {}'.format(a,b,c))
elif operacao == sub:
a = int(input('Enter the value of a:'))
b = int(input('Enter the value of b:'))
c = a - b
print ('\n A subtracao de {} menos {} equivale a: {}'.format(a,b,c))
elif operacao == div:
a = int(input('Enter the value of a:'))
b = int(input('Enter the value of b:'))
c = a / b
print ('\n A divisao de {} de {} equivale a: {}'.format(a,b,c))
elif operacao == mult:
a = int(input('Enter the value of a:'))
b = int(input('Enter the value of b:'))
c = a * b
print ('\n The multiplication of {} by {} is equivalent to: {}'.format(a,b,c))
else: #going direct to here...
print('\n Unrecognized operation')
EXPECTED that the ELIF conditions would work when true,but not working.
input returns a string, so you'll need to do operacao = int(input('\n>')), otherwise str == int will always be False:
x = input("\n>") # I've input 5
x
# '5'
# returns False because x is a string
x == 5
# False
# converts x to int, so returns True
int(x) == 5
# True
# returns True because we are comparing to a string
x == '5'
# True
So for your code:
# convert the return of input to int for comparing against other ints
operacao = int(input('\n>')) # I'll put 3
if operacao == 1:
print('got one')
elif operacao == 3:
print('got three')
# got three