Python input issue? - python

name_list = []
command_list = ["Add" ,"Help"]
def start():
input("Hello please type in a command : ")
start()
if (input == "help" or "Help"):
print("Here are the following commands for this program : ")
i = 0
for i in command_list :
print("'" + i + "'")
start()
if (input == "Add" or "add" ):
name = input("Insert name please : ")
print("Welcome " + name)
name_list.append(name)
So this code is causing me a bit of trouble , upon starting the code everything works fine it asks me to type in a command as it should , and if i type in 'help' it does exactly what its supposed to do, which is list all the commands, after that its supposed to reset via the start() command and once again ask me to input a command , however this time no matter what i write it activates this block of code:
if (input == "Add" or "add" ):
name = input("Insert name please : ")
print("Welcome " + name)
name_list.append(name)
Can someone please help me fix this and or explain why this is happening??
Thank you in advanced.

You have to use a while loop here, also repr(i) more efficient than "'" + i + "'":
name_list = []
command_list = ["Add" ,"Help"]
def start():
return input("Hello please type in a command : ")
a=start()
while a.lower()=='help':
print("Here are the following commands for this program : ")
i = 0
for i in command_list :
print(repr(i))
a=start()
if a.lower()=='add':
name = input("Insert name please : ")
print("Welcome " + name)
name_list.append(name)
else:
print('invalid input')
Example output:
Hello please type in a command : help
Here are the following commands for this program :
'Add'
'Help'
Hello please type in a command : Help
Here are the following commands for this program :
'Add'
'Help'
Hello please type in a command : Add
Insert name please : Bob
Welcome Bob
and also:
print(name_list)
Returns:
['Bob']

Your code has several issues. Here's a version that works.
name_list = []
command_list = ["Add", "Help"]
def start():
return input("Hello please type in a command : ")
name = ""
while not name:
command = start()
if (command.lower() == "add"):
name = input("Insert name please : ")
print("Welcome " + name)
name_list.append(name)
# printing help for everything except add
else:
print("Here are the following commands for this program : ")
i = 0
for i in command_list:
print(repr(i))

if (input == "help" or "Help"):
print("Here are the following commands for this program : ")
i = 0
for i in command_list :
print("'" + i + "'")
start() # <--- your call to start() function does not reset where the interpreter left off reading you code.
Python interpreter simply reads each one of your lines and does something with it. In your if statement, the line start() is called, it ask for an user input and returns None. Then this if statement is complete, then the next line read is as you described:
if (input == "Add" or "add" ):
name = input("Insert name please : ")
print("Welcome " + name)
name_list.append(name)
Solution to your question:
name_list = []
command_list = ["Add" ,"Help"]
def start():
input("Hello please type in a command : ")
while True:
start()
if (input == "help" or "Help"):
print("Here are the following commands for this program : ")
i = 0
for i in command_list :
repr(i)
if (input == "Add" or "add" ):
name = input("Insert name please : ")
print("Welcome " + name)
name_list.append(name)
if input == "something for break condition":
break

name_list = []
command_list = ["Add" ,"Help"]
def start():
inpt = input("Hello please type in a command : ")
if (inpt == "help" or inpt == "Help"):
print("Here are the following commands for this program : ")
print(command_list)
start()
elif (inpt == "Add" or inpt == "add" ):
name = input("Insert name please : ")
print("Welcome " + name)
name_list.append(name)
yn = input("Do you want to add another person? ")
if yn in ['y','Y','yes','Yes','YES']:
start()
else:
print ("Quitting!! all the people entered are")
print(name_list)
return (None)
else:
print("Please type 'help' for help")
start()

Related

how to fix syntax error while if...else statement?

import webbrowser
Character_Name = "Random"
Character_Age = "14"
input("Name of the person you want the ID of.")
print("Here's The Information That I Have: Name:" + Character_Name + ", Age:" + Character_Age + ", Available socialmedia accounts: (insta) www.instagram.com/asenpai369")
a = input("Should i open the link in your web browser?")
if a : "Yes"
webbrowser.open("www.instagram.com/idksoumyadeep")
else:
print("okay, if its a mistype then please type it again")
and the error
else:
^
SyntaxError: invalid syntax
please help thanks in advance :))
It should be
if a == "Yes": webbrowser.open("www.instagram.com/idksoumyadeep")
else: print("okay, if its a mistype then please type it again")
Use indentation after the if and else:
import webbrowser
Character_Name = "Random"
Character_Age = "14"
input("Name of the person you want the ID of.")
print("Here's The Information That I Have: Name:" + Character_Name + ", Age:" + Character_Age + ", Available socialmedia accounts: (insta) www.instagram.com/asenpai369")
a = input("Should i open the link in your web browser?")
if a == "Yes":
webbrowser.open("www.instagram.com/idksoumyadeep")
else:
print("okay, if its a mistype then please type it again")

I am having trouble writing into a text file because it says my line should be an str and not an int

print("Welcome to English, please enter your name,age,and password.")
print("If you have previously signed in, enter using the same name,age,and password")
name = input("Please enter your name: ")
age = input("Now please enter you age: ")
username = name[0:3] + age
password = input("Now please create a password: ")
userpass = (username+","+password)
check = open("logins.txt")
string = check.read().strip().split()
if userpass in string:
print("You have logged in as",username,"The questions will now start. \n")
else:
newlog = input("Looks like you dont have an account with those details, Would you like to create a new one? Y/N: ")
if newlog == "Y" or newlog == "y" or newlog == "yes" or newlog == "Yes":
f = open("logins.txt","a+")
chosen = f.write(username+","+password+"\n")
print("The username",username,"and password",password,"have now been saved, the questions will now start \n")
f.close()
else:
print("Please either sign in or log in and try again.")
welcome()
import random
f = open("English.txt","r")
points = 0
for line in f:
currentLine = line.split(",")
q = currentLine[0]
answer = currentLine[1]
questions = currentLine[1:-1]
random.shuffle(questions)
print(q)
for i in range(len(questions)):
print (i+1,":",questions[i])
userAnswer = int(input("Make a selection :"))
if answer == questions[userAnswer-1]:
points = (points+1)
print ("CORRECT, You have",points,"points")
str(points)
else:
print ("INCORRECT")
f.close()
f = open("scores.txt","a+")
score = f.write(username+","+password+","+points+"\n") #It is giving a type error about this line and I cant seem to understand why
f.close()
The error shown is:
line 193, in english
score = (username+","+password+","+points+"\n")
TypeError: must be str, not int
Please let me know if you have a better way of writing the scores into a text file. THank you.
Replace the error line with: score = f.write(username+","+password+","+str(points)+"\n")

How to switch functions in a while loop python

I am trying to make a program that adds, delete and can view dishes a user enters. It seems very simple however, I run into issues with my while loop. When I type in add I am able to add items to my list, however, when I type view the addDish function keeps on looping. I thought I fixed it with my if statement but there's something missing ... !
dish_list = []
user_input = ''
def addDish(dish_list):
user_input = input("Please type the dish you want: ")
dish_list.append(user_input)
#def deleteDish(dish_list):
def viewDish(dish_list):
for i in range(len(dish_list)):
print(dish_list[i])
user_input = input("Please enter a command: ")
while True:
if user_input == '':
user_input = input("Please enter a command: ")
elif user_input == 'add':
addDish(dish_list, user_input)
elif user_input == 'view':
viewDish(dish_list)
Instead of having a while loop, you should call a function that asks for user input once previous input has been handled.
dish_list = []
def addDish(dish_list):
user_input = input("Please type the dish you want: ")
dish_list.append(user_input)
#def deleteDish(dish_list):
def viewDish(dish_list):
for i in range(len(dish_list)):
print(dish_list[i])
def get_input():
user_input = input("Please enter a command: ")
if user_input == 'add':
addDish(dish_list, user_input)
elif user_input == 'view':
viewDish(dish_list)
getInput()
getInput()
A bit cleaner:
dish_list = []
def add_dish(dish_list):
user_input = input("Please type the dish you want: ")
dish_list.append(user_input)
def view_dish(dish_list):
# for dish in dish_list:
# print(dish)
print('\n'.join(dish_list))
while True:
user_input = input("Please enter a command: ")
if user_input == 'add':
add_dish(dish_list)
elif user_input == 'view':
view_dish(dish_list)
else:
print("Unknown command %s" % user_input)
Your variable user_input never gets set back to empty, so you can never enter a new command since it just takes the last entry you input to user_input, which would be the dish type read in the addDish function. Also, your call to addDish has an extra parameter. I also recommend throwing everything in a main method.
def addDish(dish_list):
user_input = input("Please type the dish you want: ")
dish_list.append(user_input)
def viewDish(dish_list):
for i in range(len(dish_list)):
print(dish_list[i])
def main():
dish_list = []
while True:
user_input = ''
if user_input == '':
user_input = input("Please enter a command: ")
elif user_input == 'add':
addDish(dish_list)
elif user_input == 'view':
viewDish(dish_list)
main()
Here's a fixed version of the above code snippet:
def addDish(dish_list):
user_input = raw_input("Please type the dish you want: ")
dish_list.append(user_input)
#def deleteDish(dish_list):
def viewDish(dish_list):
for dish in dish_list:
print(dish)
dish_list = []
while True:
user_input = raw_input("Please enter a command: ")
if user_input == 'add':
addDish(dish_list)
elif user_input == 'view':
viewDish(dish_list)
elif user_input == 'exit':
print('Over!')
break
else:
print('Wrong entry. Retry...')
Execution output:
$python so.py
Please enter a command: add
Please type the dish you want: Bread
Please enter a command: add
Please type the dish you want: Burger
Please enter a command: view
Bread
Burger
Please enter a command: foo
Wrong entry. Retry...
Please enter a command: exit
Over!
$

Limit the amount of inputs in a Python list

I want to set a limit to which the user can input names. This is where I got to and got stuck. How would I set a limit of 10 to the names the user can input into the list and restrict them from entering anymore?
names = []
print ('1 = Add Name ')
print ('2 = Display List ')
print ('3 = Quit ')
while True:
option = input('What would you like to do: ')
if option == '1':
name= input('Enter name: ')
names.append(name)
you can do :
if option == '1':
names = [input('Enter name:') for _ in range(10)]
I hope that following script can help you:
# libraries
import sys
# list variable to store name
names = []
# limits to save name
limit = 10
# function to display menu
def menu():
print("Enter 1 to add Name")
print("Enter 2 to show list")
print("Enter 3 to quit")
choice = int(raw_input("Enter your choice : "))
return choice
# running for infinite times till user quits
while(True):
choice = menu()
if(choice == 1):
name = raw_input("Enter name to add in list : ")
if(len(names) > 10):
print("You cannot enter more names")
else:
names.append(name)
print(name + " - Name saved successfully.")
if(choice == 2):
print("List of names : ")
print(names)
if(choice == 3):
sys.exit()

"UnboundLocalError: local variable 'input' referenced before assignment"

I have this code:
def delete():
print("Welcome to the password delete system.")
file = open("pypyth.txt", "w")
output = []
linechoice = input("What password do you want to delete?:\n")
if linechoice == "email":
for line in file:
if "Hotmail" != line.strip():
output.append(line)
print("Password " + linechoice + " deleted.")
y_n = input = ("Do you want to save these changes?\ny/n\n")
if y_n == "y":
file.close()
print("Change saved.")
input("Press enter to go back to menu")
main()
else:
main()
elif linechoice == "skype":
for line in file:
if "Skype" != line.strip():
output.append(line)
print("Password " + linechoice + " deleted.")
y_n = input = ("Do you want to save these changes?\ny/n\n")
if y_n == "y":
file.close()
print("Change saved.")
input("Press enter to go back to menu")
main()
else:
main()
else:
Why do I get an error like so?
linechoice = input("What password do you want to delete?:\n")
UnboundLocalError: local variable 'input' referenced before assignment
You are assigning a string to the variable input in
y_n = input = ("Do you want to save these changes?\ny/n\n")
input now has the value of 'Do you want to save these changes?\ny/n\n'
However, you are also calling the built-in function input in
linechoice = input("What password do you want to delete?:\n")
Consider changing the name of your variable to avoid these conflicts.
Looking at the context of the program, you are probably expecting
y_n = input("Do you want to save these changes?\ny/n\n")
instead of
y_n = input = ("Do you want to save these changes?\ny/n\n")
If you got this error, due to calling input():
UnboundLocalError: local variable 'input' referenced before assignment
than you should check whether your runtime python interpreter is 3.x, if you were assuming it is 2.x.
This Error happened to me while executing on python 3.6:
if hasattr(__builtins__, 'raw_input'):
input = raw_input
input()
So I got rid of this, and instead used:
from builtins import input

Categories

Resources