why for loop test check only first item in dictionary - python

this user check only first item in dectionary
def update_details():# here the user choose which feild he want to update
input_details = input("please select which field you want to change: ")
for item in store_group_details: #check if feild exist in decionary
if item == input_details: # removed ['type']
update_all_feature(input_details) # send input_details to update_all_feature() function
break
else:
print ("your input dose not exist? ")
update_details()
following dictionry i want to eterate over it
'app_group2': ['slack', ' Discord', 'zoom', 'vs code'], 'Date': '2222-02-12'}

It's happening because you have the wrong if/else statement. When the first item is not in the list you break from the loop and run the whole function again without checking other items.
You have to put else one indentation before (to make for/else statement):
for item in store_group_details:
if item == input_details:
update_all_feature(input_details)
break
else:
print("your input does not exist? ")
update_details()

Related

Python infinite while loop issue

I am trying to make a script that asks for user input in Python, it is supposed to error with the response "Please enter first name", and then return the user back to the initial input question prompt.
This isn't working, instead after asking for both the first and last name if no name is given for both I am thrown into an infinite loop of the first error.
# User input for first name
first_name = input('Enter FIRST name here: ')
# User input for last name
last_name = input('Enter LAST name here: ')
def print_name():
# store user input in separate variable
fname = first_name
lname= last_name
while True:
# throw error if user enters no first name
if len(fname) == 0:
# error msg
print('No FIRST name entered...')
# loop back to prompt asking for first name
continue
else:
# if first name given move on to prompting for last name
# break loop
break
# loop into prompting user for last name
while True:
# throw error if user enters no last name
if len(lname) == 0:
print('No LAST name entered...')
# loop back to prompt asking for last name
continue
else:
# if last name given move on to running print command
# break loop
break
return fname, lname
print(f'your name is {fname} {lname}')
print_name()
Please can someone help me understand whats going wrong here? It should only loop back to asking for a first name (or last name) when nothing is given, other wise it should print the users name to console. both names should be given too, if first name is not given then id expect an error in the first while loop, like wise if last name is not given.
Also is there a better way to do this? using 2 while loops seems wrong?
Don't repeat yourself. If you copy and paste a section of code, stop and think. It should either be a function, or a loop.
def wait_for_input(prompt):
data = ""
while data == "":
data = input(prompt).strip()
return data
def print_name(fname, lname):
print(f'your name is {fname} {lname}')
first_name = wait_for_input('Enter FIRST name: ')
last_name = wait_for_input('Enter LAST name: ')
print_name(first_name, last_name)
Also, don't use comments to repeat what the code says.
The issue is with your infinite loops, you can simplify your function like:
def print_name():
first_name = ""
last_name = ""
# User input for first name
while first_name == "":
first_name = input('Enter FIRST name here: ')
# User input for last name
while last_name == "":
last_name = input('Enter LAST name here: ')
print(f'your name is {first_name} {last_name}')
I have the impression you are new at this:
While-loops generally look as follows:
while <condition>
...
<check_condition>
...
This means that in most cases, at every time the loop is executed, the condition is re-calculated and checked again by the while.
In your case, this would become something like:
while (len(fname) == 0)
<show_error_message>
<get fname again>
The case you have written here (while true) also exists and is used regularly, but in very different cases, like in multi-threaded event-based programs:
while true
<get_event>
This means that a part of the program (a so-called thread) is waiting for an event (like a buttonclick) to be catched and then something happens. This, however, is mostly done in multi-threaded applications, which means that the "main" program is doing something, while a subprogram is handling the events, which are coming in.
I am not fully understanding why you need so many loops. Something like this should do:
def print_name():
fname = input('Enter FIRST name here: ')
if len(fname) == 0:
raise Exception('No FIRST name entered...')
lname= input('Enter LAST name here: ')
if len(lname) == 0:
raise Exception('No LAST name entered...')
print(f"your name is {fname} {lname}")
And if all you wanted is to repeat this loop all you need to do is nest your print_name() function in a loop.
EDIT: Now that I seen other answers, I believe #Tomalak answer is better, was not getting what you really wanted.
Try this code:
def print_name():
# store user input in separate variable
first_name = input('Enter FIRST name here: ')
fname = first_name
while True:
fname = first_name
# throw error if user enters no first name
if len(fname) == 0:
# error msg
print('No FIRST name entered...')
first_name = input('Enter FIRST name here: ')
# loop back to prompt asking for first name
continue
else:
# if first name given move on to prompting for last name
# break loop
break
# loop into prompting user for last name
while True:
last_name = input('Enter LAST name here: ')
lname= last_name
# throw error if user enters no last name
if len(lname) == 0:
print('No LAST name entered...')
# loop back to prompt asking for last name
continue
else:
# if last name given move on to running print command
# break loop
break
return fname, lname
print(f'your name is {fname} {lname}')
print_name()

sharing a data between two functions in python

so i have a code which loops until the user types cancel and allows the user to input things into a list and then see the list if they want to. but i have a problem wherein if i want to see the list the user has to input again and the data i typed when i added to the list is gone. here is the code pls help me im pretty new to python.
answer=""
def addlist():
list=input("what would you like to add? ")
print("added successfully")
return list
def showlist():
list=addlist()
print(list)
while answer !="cancel":
answer=input("what would you like to do?, 1 for add to list, 2 for show list, cancel to close")
if answer=="1":
addlist()
elif answer=="2":
showlist()
else:
print("wrong value")
So we've got a few problems here:
addlist doesn't actually create a list, it creates a string.
showlist depends on addlist, when really we should be looking for a common list that we toss everything into (assuming you actually want to work with a list)
Your indentation in your while loop is incorrect
def addlist():
item = input("what would you like to add?")
return item
def showlist(mylist):
print(mylist)
mylist = []
answer = ""
while answer != "cancel":
answer = input("what would you like to do?, 1 for add to list, 2 for show list, cancel to close")
if answer == "1":
add_item = addlist()
mylist.append(add_item)
print("added successfully")
elif answer == "2":
showlist(mylist)
else:
print("wrong value")
That above seems to do the trick.
You seem to have a grasp on return statements, so how about you pass each of those functions a common list as I did mylist and have them do stuff with that.
I changed addlist to actually just get the item we want to add to the list and then return that item and append it outside of the function. In showlist I pass mylist to it via: showlist(mylist) and then print the list I get in that function.
You should create a list element in order to append your items in it. You can see more here. One way to do what you want is like this:
answer = ""
temp_list = []
def addlist():
item = input("what would you like to add? ")
temp_list.append(item)
print("added successfully")
def showlist():
print(temp_list)
while answer != "cancel":
answer = input(
"what would you like to do?, 1 for add to list, 2 for show list, cancel to close")
if answer == "1":
addlist()
elif answer == "2":
showlist()
else:
print("wrong value")

Appending a List at runtime in Python

I'm Creating a project in which i have two lists.
One list is user_ids where the user's usernames are stored.
Another is user_ratings where the user's ratings are stored.
At the corresponding index of username, user rating is stored.
If there's a new user, the list is appended dynamically at run-time.
Here's the code:
print("Welcome to Movie Predictor")
print("Enter your user id: ")
user_ids=["Vishnu"]
user_ratings=[3.5]
username=input()
print("Signing in...Please Wait!")
if username in user_ids:
user_index=user_ids.index(username)
avg_rating=user_ratings[user_index]
new_user=0
else:
user_ids.append(username)
user_ratings.append(3.5)
avg_rating=3.5
new_user=1
After my first run of the program, I have entered a username which is not there in the list and here are the arrays.
user_ids=["Vishnu","Power"]
user_ratings=["3.5","3.5"]
But here's the problem. The next time i run it again, My last element "Power" is getting replaced but a new item is not appended in the list.
Here's the list after 2nd run:
user_ids=["Vishnu","Ranger"]
user_ratings=["3.5","3.5"]
How to overcome this problem?
Try saving your data to disk after each run, and reading if back before next run:
import os.path
if not os.path.exists("mydatabase.txt"):
# initialize
user_ids=["Vishnu"]
user_ratings=[3.5]
else:
# read previous data from database file
user_ids=[]
user_ratings=[]
with open("mydatabase.txt", "r") as databasefile:
for line in databasefile:
userid, rating_str = line.split()
rating = float(rating_str)
user_ids.append(userid)
user_ratings.append(rating)
print("Welcome to Movie Predictor")
print("Enter your user id: ")
username=input()
print("Signing in...Please Wait!")
if username in user_ids:
user_index=user_ids.index(username)
avg_rating=user_ratings[user_index]
new_user=0
else:
user_ids.append(username)
user_ratings.append(3.5)
avg_rating=3.5
new_user=1
print("Current user ids: %s" % user_ids)
print("Current user ratings: %s" % user_ratings)
# write data to database file
with open("mydatabase.txt", "w") as databasefile:
for userid, rating in zip(user_ids, user_ratings):
databasefile.write("%s %.1f\n" % (userid, rating))
There is no loop here. You just overwrite the values each time.
try that:
A, B = [], []
while True:
A.append(3.5)
b = input('B value')
if b == '':
break
B.append(b)
print(A, B)
It is unclear which parts of the code you run again, but it seems that you are resetting your user ID and ratings lists in every run (3d and 4th line). Therefore "Powers" is not being replaced. Rather than that, a new list with Vishnu is created and your new input is added to it after the run.
You don't have a loop. The values in the list won't be saved between runs of the script
print("Welcome to Movie Predictor")
print("Enter your user id: ")
user_ids=["Vishnu"]
user_ratings=[3.5]
while True:
username=input()
print("Signing in...Please Wait!")
if username in user_ids:
user_index=user_ids.index(username)
avg_rating=user_ratings[user_index]
new_user=0
else:
user_ids.append(username)
user_ratings.append(3.5)
avg_rating=3.5
new_user=1
print("List of users: " + str(user_ids))
you probably want to use dicts and a while loop for input multiple users. This code keep iterating until user enters 'n' on the second input.
print("Welcome to Movie Predictor")
users = dict(Vishnu = 3.5)
a = 'y'
while a == 'y':
username=input("Enter your user id: ")
print("Signing in...Please Wait!")
if username in users:
print("do something if user exits")
else:
val = float(input(f"Enter value for {username}: "))
users[username] = val
print(users)
avg_rating = sum(users.values()) / len(users)
print(f"average rating: {avg_rating}")
a = ''
while a not in ['y','n']:
a = input("continue? (y/n)")
if a == 'n':
break
else:
continue

Adding items to shopping List Python

I'm learning Python and I'm trying to make shopping List
where you can add items
first it will ask you to add the items if the shopping list is empty
it will be added automatically if not it will ask you where you would like
to put the item (index)
but also I'm trying to make the program exit in certain condition like DONE
or HELP or SHOW but even that i put a condition for that but it's not working can anyone help me with this
hope I explained enough
import os
shopping_list =[]
# Function for clearing the screen
def clear_screen():
os.system("cls" if os.name == "nt" else "clear")
def show_help():
print("Enter 'Done' if you finish adding item \n Enter 'Show' to show your items \n Enter 'Help' toshow this help ")
# Function to show the items that you've entered to the list
def show_item():
clear_screen()
index = 1
for item in shopping_list:
print("{} {}.".format(index,item))
index += 1
# Function to add items to the list
def add_to_list():
while True:
new_item = input("Please enter the item that you would like to add to your shopping list ")
if shopping_list and ((new_item.upper() != "DONE") or (new_item.upper() != "HELP") or (new_item.upper() != "SHOW")):
position = input("Where you would like to add {} to the list \n press 'Enter' if you want to add to the end of the list".format(new_item))
position = abs(int(position))
shopping_list.insert(position - 1 , new_item)
show_item()
else:
if new_item.upper() == "DONE":
break
elif new_item.upper() == "SHOW":
show_item()
continue
elif new_item.upper() == "HELP":
show_help()
continue
else:
shopping_list.append(new_item)
show_item()
show_help()
add_to_list()
Welcome to stackoverflow. I think your logic statement is wrong, you need and instead of or. Right now all you need for the statement in the parentheses to be true, is that new_item.upper() is at least not one of those three words. It actually can't equate to False since two of the three are always true.
((new_item.upper() != "DONE") or (new_item.upper() != "HELP") or (new_item.upper() != "SHOW"))
If you have for example done the first statement is False ,but the other two are True, adding up to True in or-Statements.
>>> new_item = 'done'
>>> print((new_item.upper() != "DONE") or (new_item.upper() != "HELP") or (new_item.upper() != "SHOW"))
True

Break outside the loop

I am new to Python. I am trying to run the following code. But every time I try to run it, the IDE says that the break is outside the loop
catname = []
print("Enter the name of the cats")
name = input()
if name == '':
break
catname = catname+[name]
print("The cat Names are :")
for catname in name:
print(name)
Can you please help me?
Thanks
You use break when you want to break free from a loop, to exit the loop, to jump to the nearest code after the loop.
Your code doesn't contain a loop, so nothing to break free from, hence the error.
I think you meant exit() instead of break
You use "break" just inside the loop ("for" or "while"), you are trying use brake inside the "if"
How about this:
if name != '':
catname = catname+[name]
print("The cat Names are :")
for catname in name:
print(name)
Your break statement is not in a loop, it's just inside an if statement.
But maybe you want to do something like the following.
If you want to let the user enter an random number of names and print the names out, when the user entered nothing, you can do the following:
# Here we declare the list in which we want to save the names
catnames = []
# start endless loop
while True:
# get the input (choose the line which fits your Python version)
# comment out the other or delete it
name = input("Enter the name of a cat\n") # input is for Python 3
# name = raw_input("Enter the name of a cat\n") # raw_input is for Python 2
# break loop if name is a empty string
if name == '':
break
# append name to the list catnames
catnames.append(name)
print("The cat names are :")
# print the names
for name in catnames:
print(name)
What you are looking for is exit().
However, your code has also other problems, here is a piece of code that does what you probably want (when prompted, enter the names separated by spaces, like: Cat1 Cat2):
name = raw_input("Enter the name of the cats: ")
if len(name) == 0:
exit()
print("\nThe cat Names are:")
for c_name in name.split():
print(c_name)
If this is the entirety of your code, then it's telling you exactly what the problem is:
catname = []
print("Enter the name of the cats")
name = input()
if name == '':
break
You have a break statement in the code that's not contained inside a loop. What do you expect the code above to do?

Categories