Asking python for a breakfast menu - python-3.x

'meals = ("Juice", "Milk", "Bread")
name = input("What do you want in a breakfast? ")
if meals =='bread''milk''juice':
print("I love it ")
else:
print(" I don't want it ")'

You need to compare the user input, which is a string stored in the variable name with meals which is a tuple of strings. To compare the two, you need to include a in logical operator:
name = input("What do you want in a breakfast? ")
if name in meals:
print("i love it")
else:
print("i dont want it")
However, for this code to work, the user input must always be capitalized. Next time, ask a question and state your desired outcome instead of just posting code.

Related

Python Error message for entering a number instead of a letter

I just started my programming education with python in school. One of the programs I started with simply asks you your name and then repeats it back to you. I'd like some help with getting an error message to show up if you put in a number rather than letters.
This is what I have:
while True:
name = input("What is your full name? ")
try:
n = str(name)
except ValueError:
print("Please enter your name in letters, not", repr(name))
continue
else:
break
print(name)
You can check the name if only contains letters by using string.isalpha()
in your case you name it n so n.isalpha() will return True or False
for more information:
How can I check if a string only contains letters in Python?

My Five - stores five names and five numbers before being promoted for a number need input

For class I need to create a code that stores five names of your friends and five numbers in two separate arrays and then outputs the list of your five friends. The user would then be prompted for a number between 1 and 5, and the program will determine the person and the number to dial.
it should look something like -
1. Jack Black
2. Robert Downey Jr.
3. Chris Evens
4. Scarlett Johansson
5. Harry Potter
Please enter a number (1-5): *4*
Calling Scarlett Johansson at 416-568-8765
right now I have:
name = ["Paige"]
number = ["519-453-4839"]
#populate with a while loop
while True:
#add an element or q for quit
addname = input("Enter a name, or q to quit ").lower()
if addname == "q":
break
else:
theirnumber = input("Enter their number ")
#adds to the end of the list
name.append(addname)
number.append(theirnumber)
#when they break the loop
#print the lists side by side
print()
print("Name \t\t\t Number")
print("----------------------------------")
for x in range(len(name)):
print(f"{name[x]} \t\t\t {number[x]}")
#search for a gift and who gave it
searchItem = input("What name are you looking for? ")
if searchItem in name:
nameNumber = name.index(searchItem)
print(f"{name[nameNumber]} is the number {number[nameNumber]}")
else:
print("that is not a saved name, please enter a different name")
I'm not sure how to do it without asking for the numbers, if anyone has any ideas I would love to hear them.
#Mitzy33 - try to this and see if you follow, or have any other questions:
# two array for names, and the numbers
names = []
numbers = []
#populate with a while loop
while True:
# get the name and numbers:
name = input("Enter a name, or q to quit ")
if name == "q":
break
else:
number = input("Enter his/her number ")
#adds to the end of the list
names.append(name)
numbers.append(number)
#when they break the loop
#print the lists side by side
print(names)
print(numbers)
searchPerson = input("What name are you looking for? ").strip()
#print(searchPerson)
index = names.index(searchPerson)
print(f' {searchPerson} at {numbers[index]} ')
Output:
Enter a name, or q to quit John
Enter his/her number 9081234567
Enter a name, or q to quit Mary
Enter his/her number 2121234567
Enter a name, or q to quit Ben
Enter his/her number 8181234567
Enter a name, or q to quit Harry
Enter his/her number 2129891234
Enter a name, or q to quit q
['John', 'Mary', 'Ben', 'Harry']
['9081234567', '2121234567', '8181234567', '2129891234']
What name are you looking for? Harry
Harry at 2129891234
Instead of using two arrays you can do it using Python Dictionaries.
Use the name as the key and the number as the corresponding value.
peoples = {"Paige": "519-453-4839"}
You can add an item like that:
poeples["newName"] = "111-111-1111"
Then you can access the number like that:
peoples["Paige"]
So you can ask the name and return the number:
searchName = input("What name are you looking for? ")
print(f"{searchName} is the number {peoples[searchName]}")
If you have to use only arrays then you can find the index from the name:
searchName = input("What name are you looking for? ")
index = name.index(searchName)
print(f"{name[index]} is the number {number[index]}")

If statements with true or false in python 3.7.1 Tanner Short

my name is Tanner Short.
I'm a beginning developer, and have recently started to use python.
For a simple project I wanted to create a basic calculator, but I wanted to be creative and add some if statements and such. Here is my code.
name = input("Please enter your name: ")
age = input("Please enter your age: ")
Yes = True
No = False
print("Hello " + name + "!" " You are "+age+ " years old!" )
welcome_question = input("Would you like to go to the calculator? ")
if Yes:
print("Moving on..")
else:
print("Thank you for your time!")
So when I ran the file, it was supposed to ask for your name, age, then ask if you'd like to go to the calculator.
But the if statement isn't working. When I type Yes, it works, then when I type No, it outputs what was supposed to happen if you said yes.
Sorry if this made no sense! I a beginner and just need a little help. Thank you.
You are comparing the wrong values. What you want to do is, you want to compare user's input with Yes. If the user enters Yes then if should work, otherwise else should work.
So, basically, you need to compare welcome_question with "Yes" or "No". The Line 3 and 4 from your code are not required as per. And yes, your indentation is also broken.
name = input("Please enter your name: ")
age = input("Please enter your age: ")
print("Hello " + name + "!" " You are "+age+ " years old!" )
welcome_question = input("Would you like to go to the calculator? ")
if welcome_question == "Yes":
print("Moving on..")
else:
print("Thank you for your time!")
I hope it works. Cheers!

Python: String similar to everything

I need to use string (or int, bool, etc.) which will be same as everything. So this code:
user_input = input()
if user_input in *magic_string_same_as_everything*:
return True
should return True everythine, no matter what will user type into console.
Thanks for your help
Edit:
I see, that I've asked verry badly.
I'm trying to get 3 user input in this for cycle:
user_input = ["", "", ""] # Name, class, difficulty
allowed_input = ["", ["mage", "hunter"], ["e", "m", "h"]]
difficulty = {"e": 1, "m": 2, "h": 3}
message = ["Please enter your heroic name",
"Choose character (mage/hunter)",
"Tell me how difficult your journey should be? (e / m / h)"]
print("Welcome to Dungeons and Pythons\n" + 31 * "_")
for i in range(3):
while True:
print(message[i], end=": ")
user_input[i] = input()
if user_input[i] in allowed_input[i]:
break
Choose of name is without restrictions.
I hope, that now my question makes a sense.
You could just get rid of the if-statement and return True without the check or (if you really want to use the if-statement) you type if(True) and it will always be true.
You want True for non empty string?
Just use user_input as bool.
user_input = input()
if user_input:
return True
In your question Name is special case, just check it like this and for the rest of input you can use range(1,3).
Alternatively switch to using regular expressions
allowed_input = ["\A\S+", "\A(mage|hunter)\Z", "\A[emh]\Z"]
for i in range(3):
while True:
print(message[i], end=": ")
user_input[i] = input()
if re.match(allowed_input[i], user_input[i]) :
break
Initial response
This one liner should work.
If user inputs anything, it counts as an input & prints 'True', but if user just hits 'Enter' without typing anything, it returns 'No input'
print ("True" if input("Type something:") else 'No input')
After your edited question
To achieve what you want, you can define a function that checks for the user input values & corrects them if incorrect.
import re
# for user input, a single line of code is sufficient
# Below code takes 3 inputs from user and saves them as a list. Second and third inputs are converted to lowercase to allow case insensitivity
user_input = [str(input("Welcome to Dungeons & Pythons!\n\nPlease enter username: ")), str(input("Choose character (mage/hunter): ").lower()), str(input("Choose difficulty (e/m/h):").lower())]
print (user_input) # Optional check
def input_check(user_input):
if user_input[0] != '':
print ("Your username is: ", user_input[0])
else:
user_input[0] = str(input("No username entered, please enter a valid username: "))
if re.search('mage|hunter', user_input[1]):
print ("Your character is a : ", user_input[1])
else:
user_input[1] = str(input("Incorrect character entered, please enter a valid character (mage/hunter): ").lower())
if re.search('e|m|h',user_input[2]):
print ("You have selected difficulty level {}".format('easy' if user_input[2]=='e' else 'medium' if user_input[2]=='m' else 'hard'))
else:
user_input[2] = str(input("Incorrect difficulty level selected, please choose from 'e/m/h': "))
return (user_input)
check = input_check(user_input)
print (check) # Optional check
In each of the if-else statements, the function checks each element and if no input/ incorrect input (spelling mistakes, etc.) are found, it asks the user to correct them & finally returns the updated list.
Test Output
With correct entries
[Out]: Welcome to Dungeons & Pythons!
Please enter username: dfhj4
Choose character (mage/hunter): mage
Choose difficulty (e/m/h):h
['dfhj4', 'mage', 'h']
Your username is: dfhj4
Your character is a : mage
You have selected difficulty level hard
['dfhj4', 'mage', 'h']
With incorrect entries
[Out]: Welcome to Dungeons & Pythons!
Please enter username:
Choose character (mage/hunter): sniper
Choose difficulty (e/m/h):d
['', 'sniper', 'd']
No username entered, please enter a valid username: fhk3
Incorrect character entered, please enter a valid character (mage/hunter): Hunter
Incorrect difficulty level selected, please choose from 'e/m/h': m
['fhk3', 'hunter', 'm']

Checking if a variable contains spaces and letters

I am trying to make a program that asks for a name but will reject the input if it doesn't contain letters/spaces. However, it seems to reject spaces as well as numbers and symbols.
print("Welcome to the Basic Arthmetics Quiz.")
print("What is your name?")
name=input()
if not name.isalpha()or name not in(str(" ")):
print('Please only enter letters for your name!')
while not name.isalpha()or name in(str(" ")):
v=1
print('Please enter your name again.')
name=input()
if name.isalpha()or name not in(str(" ")):
v=0
else:
v=1
Where have I gone wrong?
This looks an awful lot like homework.
Your test name not in(str(" ")), which should be written name not in " ", tests whether name is one of {"", " "}.
It would be easiest to test the name one char at a time, with a per-char condition like
char.isalpha() or char == ' '
Combine this with all and a generator expression to test all chars of name.
The actual implementation, as well as proper code flow (you don't use v, you perform the test thrice, and call input() twice, all of which is unacceptable) are left as exercise.

Resources