Function with two loops - python

I want to make a function what must have 2 loops:
must check that at least 2 characters (letters) are inserted
if the two characters are in the form that the variable must receive at the end, the variable receives the correct orthographic form.
Here is my code (but it throws me in infinite loop) [Please be indulgent im a begginer (: ] :
def sede():
while True:
import re
var_sede_0 = input("Sede : ")
if re.match("([a-zA-Z]+.*?){2,}", var_sede_0):
while True:
if var_sede_0.lower() in 'torino (to)':
var_sede_0 = 'Torino (TO)'
break
elif var_sede_0.lower() in 'reggio calabria (rc)':
var_sede_0 = 'Reggio Calabria (RC)'
break
else:
print("sbagliato")
continue
break
else:
print("formato sbagliato")
continue
return var_sede_0
var_sede = sede()

Your inner loop is the problem:
while True:
if var_sede_0.lower() in 'torino (to)':
var_sede_0 = 'Torino (TO)'
break
elif var_sede_0.lower() in 'reggio calabria (rc)':
var_sede_0 = 'Reggio Calabria (RC)'
break
else:
print("sbagliato")
continue
Consider that nowhere in this loop do you take in new input, so var_sede_0 can never possibly change. Given that, if the first two predicates (if statements) evaluate to false, then you will be in an infinite loop printing out sbagliato. You can probably simply remove the while True (the inner one) and get to what you want.
It is key to note that break and continue really only affect the immediate while context that they are in - they will not 'speak to' the outer while loop.
You also probably do not want to be importing re on every loop. Move import re to the top of your file.

Related

Syntax error on else: statement in code + idk why it keeps saying I have a bad title

So, my problem is I need to put mondayAssign right where I have it cause it appears it will just ask the question everywhere else and I don't want it too so I have to do this and I have an error on elif: any one wanna help?
__import__("replit").clear()
whatReturn = "monday"
f = open('hold.txt', 'r')
g = f.seek(0)
h = f.readlines()
for line in h:
pass
def monday():
if whatReturn in line:
mondayAssign = input("Assign a task for monday: ")
else:
print("error has occured.")
monday()
def mondayy():
if whatReturn in line:
mondayAdd = input("Anything else you would like to add, 'yes' or 'no': ")
mondayAdd == 'yes'
mondayDoubleAssign = input("Assign a task for monday: ")
elif:
print("Error!!!")
else:
mondayAssign = input("Assign a task for monday: ")
#the last else is just a place to store the mondayAssign cause it appears I cant put it anywhere else without it just printing itself and I don't want to ask same question twice
mondayy()
print(mondayAssign, mondayDoubleAssign)
It's very simple, you use the unconditional elif construct. Either add some condition or replace elif with else. In the event that you want to handle the exception, you need to use the try except construction.
Here is a variant using "else":
__import__("replit").clear()
whatReturn = "monday"
f = open('hold.txt', 'r')
g = f.seek(0)
h = f.readlines()
for line in h:
pass # This is extra code
def monday(h):
for line in h:
if whatReturn in line:
mondayAssign = input("Assign a task for monday: ") # to use "line" you must first define it
else:
print("error has occured.")
monday(h)
def mondayy(h):
for line in h:
if whatReturn in line:
mondayAdd = input("Anything else you would like to add, 'yes' or 'no': ")
mondayAdd == 'yes' #it's not very clear why there is a comparison
mondayDoubleAssign = input("Assign a task for monday: ")
elif some_condition:
print("Error!!!")
else:
mondayAssign = input("Assign a task for monday: ")
#the last else is just a place to store the mondayAssign cause it appears I cant put it anywhere else without it just printing itself and I don't want to ask same question twice
mondayy(h)
print(mondayAssign, mondayDoubleAssign)
If you look at the code in general, I think you should get a better understanding of loops and conditional statements, since you seem to have problems with them. Do not grab onto everything at once :) It is better to first study each of the topics in detail, and then try to combine them. This also applies to functions, by the way. Here's a little scribbled on using it all:
#lets begin from loops
#simple usage:
for some_variable in some_sequence:
print(some_variable) # some variable access only in loop it means that you can use it only in loop body(4 spaces)
#now briefly about conditional operators:
if some_statement:
print("something")
elif some_other_statement:
print("do something else") # it means optional condition
else:
print("do something different in any way that does not fit the above")
#again, you need to remember about the scope, that is, something will work inside the condition only if it is written after 4 spaces
#now briefly about functions:
#a function is an algorithm that we have named by some name and, as a rule, we use repeatedly. In parentheses, we pass the arguments to the function, that is, external data that needs to be used inside the algorithm.
def simple_func(arg_one, arg_two):
print(arg_one, arg_two)
simple_variable_one = "hello"
simple_variable_two = "world!"
simple_func(simple_variable_one, simple_variable_two) #output: hello world
Good luck learning Python, I hope you succeed!

try/except while true in a for loop

The following code will gather data from an API and the try/except clause will help to handle several errors (from authentication, index, anything).
There's only one error (an authentication error) that I'm using the while True to repeat the API call to make sure I get the data and it will after a try or two. However if by any means I get another error, it'll be infinitely looping and I can't break it so it goes to the next iteration. I tried to create a counter and if the counter reaches to a number then (pass or continue or break) but it's not working.
## Create a array to loop to:
data_array_query = pd.date_range(start_date,end_date,freq='6H')
#This is my idea but is not working
#Create a counter
counter = 0
#Loop through the just created array
for idx in range(len(data_array_query)-1):
## If counter reaches move on to next for loop element
while True:
if counter>=5:
break
else:
try:
start_date = data_array_query[idx]
end_date = data_array_query[idx+1]
print('from',start_date,'to',end_date)
df = api.query(domain, site_slug, resolution, data_series_collection, start_date=str(start_date), end_date=str(end_date), env='prod', from_archive=True, phase='production').sort_index()
print(df.info())
break
except Exception as e:
print(e)
counter +=1
print(counter)
So the output of running this code for a couple of days show that when it runs 5 times (that's the counter max I set up) it does break but it breaks the whole loop and I only want it to move to the next date.
Any help will be appreciated,
You need to use a break statement to get out of a while True loop. pass and continue work for for loops that have a fixed number of iterations. While loops can go on forever (hence the different names)

Python UnboundLocalError: Problems with a function for choosing words from a dictionary

I've written a function for choosing a single key (=word) from a dictionary. If the key has already been used, another key should be chosen. This is my function:
nom_acc = {"qeso":"qes", "os":"os", "sondra":"sondre", "mawizzi":"mawizze", "khewo":"khewe", "alegra":"alegre", "kendra":"kendre", "zhalia":"zhalie", "achrakh":"achrakh", "ador":"ador", "hoggi":"hogge", "soqwi":"soqwe"}
usedWords = []
def wordChoice():
global usedWords
print(usedWords) ### DELETE LATER
word = random.choice(list(nom_acc)) ### randomly pick a key from a dictionary (which is the nominative form)
print(word) ### DELETE LATER
if word in usedWords:
print("gotta pick another word") ### DELETE LATER
wordChoice()
else:
usedWords.append(word)
accusative = nom_acc[word]
return word, accusative
The function is embedded into a main program. When I run the code like this, it gives me an error message as soon as a word is chosen that has already been used:
UnboundLocalError: local variable 'accusative' referenced before assignment
If I add a dummy value for the word and accusative variable it seems to work:
if word in usedWords:
print("gotta pick another word") ### DELETE LATER
word="DUMMY"
accusative="DUMMY"
But what I want is that another word is chosen from the dictionary if the word has already been used. How do I implement this?
This is the part of the code where the wordChoice() function is called up:
def writeAcc():
'''Minigame: User has to enter the correct accusative form, after three correct answers he passed'''
global isPlaying, usedWords
isPlaying = True
# asking the user to enter the right accusative form of the word
print("Please enter the accusative form of the following words\n")
# player passed when he reached 3 correct answers
right = 0
while right < 4:
word, accusative = wordChoice()
print("Nominative ", word)
print("Need help? Enter 'y' to see the menu again or press the enter-key to continue.")
choice = input("\t\t\tChoice: ")
if choice == 'y':
continueGame = displayMenu()
if not continueGame:
return
print("Nominative ", word)
answer=input("Accusative ")
if answer==accusative:
right+=1
print("Guessed right:", right)
if right < 4 and (len(usedWords) == len(list(nom_acc))):
print("Sorry you don't seem to have what it takes to learn the accusative.")
break
if right == 4:
print("Congratulations! You passed the first step, you will now enter the next challenge.")
The error happens because there is a problem in your recursiveness. Below I will try to explain the problem in your recursion. Suppose this is your input in the terminal with your current code:
wordChoice()
Python interpreter will then evaluate the expression by running the code within def wordChoice() block. Everything will run smoothly until your if block. Your current if block is like this:
if word in usedWords:
print("gotta pick another word") ### DELETE LATER
wordChoice() # Python must evaluate this before continuing
When your word is used, Python will get to that new wordChoice() and it will evaluate that expression before continuing. Suppose that when running this second wordChoice() the randomised word is not used, and the code reaches your else block.
else:
usedWords.append(word)
accusative = nom_acc[word]
No problem here either, everything smooth, it will return word, accusative just like you wanted. This return statement is telling Python how it should evaluate the last called wordChoice(). Which means that it will go back from where it stopped the last time wordChoice() was called, which is that if statement. So it will proceed like this:
if word in usedWords:
print("gotta pick another word") ### DELETE LATER
some_word, some_accusative_value # the interpreter will continue the code from this point
else:
usedWords.append(word)
accusative = nom_acc[word]
return word, accusative
Which means that the if block is executed and it will proceed to the return word, accusative again, but in the scope of this current wordChoice() they are not set because this wordChoice() did not get to the else statement. To correct your recursiveness, you must return wordChoice() until the code gets to executes the else statement. Below is the correct solution for what you want:
nom_acc = {"qeso":"qes", "os":"os", "sondra":"sondre", "mawizzi":"mawizze", "khewo":"khewe", "alegra":"alegre", "kendra":"kendre", "zhalia":"zhalie", "achrakh":"achrakh", "ador":"ador", "hoggi":"hogge", "soqwi":"soqwe"}
usedWords = []
def wordChoice():
global usedWords
print(usedWords) ### DELETE LATER
word = random.choice(list(nom_acc)) ### randomly pick a key from a dictionary (which is the nominative form)
print(word) ### DELETE LATER
if word in usedWords:
print("gotta pick another word") ### DELETE LATER
return wordChoice() # return correct recursive result
else:
usedWords.append(word)
accusative = nom_acc[word]
return word, accusative # This return statement should be inside the else statement for clearness

Why is this function creating an infinite loop?

Why is this creating an infinite loop? And if it isn't creating one, why does the program freeze up? Not like IDLE stops responding, It just stops like I created a infinite loop and the only thing it does is input(). Try the code out to see what I mean.
(also, tell me if the for's are correct in the comments please)
Accounts = {}
def create_account(x,y,z,a):
global Accounts
Checked = False
while Checked == False:
if x in Accounts:
print("Sorry, that name has already been taken")
print("Please choose a new name")
x = input()
for dictionary in Accounts:
for key in dictionary:
if a in key:
print("Sorry, password is invalid or not avalible")
print("Please choose a new password")
a = input()
Accounts[x] = {"Proggress":y,"Points":z,"Pass":a}
print(Accounts[x])
Your code creates an infinite loop because there is nothing to stop it.
while checked == False will do exactly what it sounds like, it will loop over the code over and over until checked = True OR until you break
break will simply stop the loop, allowing the program to finish.
checked = True will also stop the loop
I think that what you are trying to do is something like this:
This code is untested
Accounts = {}
def create_account(x,y,z,a):
global Accounts
Checked = False
while Checked == False:
if x in Accounts:
print("Sorry, that name has already been taken")
print("Please choose a new name")
x = input()
else:
passwordOk = True
for dictionary in Accounts:
for key in dictionary:
if a in key:
passwordOk = False
break
if not passwordOk:
break
if not passwordOk:
print("Sorry, password is invalid or not avalible")
print("Please choose a new password")
a = input()
else:
Checked = True # this is the important part that you missed
Accounts[x] = {"Proggress":y,"Points":z,"Pass":a}
print(Accounts[x])
Just for you to know, your code can be optimized. I tried to solve your issue by modifying as minimum code as possible, so that you could understand the problem
There are two issues causing this.
As you say,
the print() is before the input(), and the print never outputs, so it doesn't get that far
However, let's take a step back: the print statements are inside the block if x in Accounts:. At the very first line, you set Accounts to be an empty dictionary (Accounts = {}), so no matter what x is, at that point, x in Accounts will never be true - there's nothing in it.
Now, you do have a line that adds items to Accounts:
Accounts[x] = {"Proggress":y,"Points":z,"Pass":a}
However, as other people have pointed out, you'll never get here - it's outside the loop, and the loop never exits because Checked is never set to True, nor is a break called.
Your program then is essentially just going through the same few steps that don't do anything:
Does Checked == False? Yep, continue the loop.
Is x in Accounts? Nope, skip this block.
For every dictionary in Accounts, do some stuff, but Accounts is empty, so I don't need to do anything.
Does Check == False? Yep, continue the loop.

Is the `else:` correct/necessary in this Python program?

Is the line of else: correct/necessary in this Python program?
from random import randrange
for n in range(10):
r = randrange(0,10) # get random int in [0,10)
if n==r: continue # skip iteration if n=r
if n>r: break # exit the loop if n>r
print n
else:
print "wow, you are lucky!\n"
if n<9:
print "better luck next time\n
From the documentation:
Loop statements may have an else clause; it is executed when the loop terminates through exhaustion of the list (with for) or when the condition becomes false (with while), but not when the loop is terminated by a break statement
So yes, it's correct in your example. Although I've never been a fan of it, using an else clause on a loop makes code confusing at first, I'd rather use a boolean flag for achieving the same effect. IMHO else should be used only for conditionals.
from random import randrange
for n in range(10):
r = randrange(0,10)
if n=r: continue # there should be ==
if n>r: break
print n # should be "\n" ?
else:
print "wow, you are lucky!\n" # Yes, you are! Your python interpreter can make miracles :). Try to run me.append(SexyChick(10)) and let's see what happens!
for...else construct is actually valid. else branch is executed if the loop has not been terminated by break. Look here.

Categories