How to ignore certain strings from user input? - python

Beginner question:
How do I have my input code ignore certain strings of text?
What is your name human? I'm Fred
How old are you I'm Fred?
How do I ignore user input of the word "I'm"?
How old are you I'm Fred? I'm 25
Ahh, Fred, I'm 25 isn't that old.
How do I again ignore user input when dealing with integers instead?
This is the code I have so far:
name = input("What is your name human? ")
while True:
try:
age = int(float(input("How old are you " + name + "? ")))
if age >= 50:
print(str(age) + "! Wow " + name + ", you're older than most of the oldest computers!")
else:
print ("Ahh, " + name + ", " + str(age) + " isn't that old.")
break
except ValueError:
print("No, I asked how old you were... ")
print("Let us try again.")

You could use .replace('replace what','replace with') in order to acheive that.
In this scenario, you can use something like:
name = input("What is your name human? ").replace("I'm ","").title()
while True:
try:
age = int(input("How old are you " + name + "? ").replace("I'm ",""))
if age >= 50:
print(str(age) + "! Wow " + name + ", you're older than most of the oldest computers!")
else:
print ("Ahh, " + name + ", " + str(age) + " isn't that old.")
break
except ValueError:
print("No, I asked how old you were... ")
print("Let us try again.")
Similarly, you can use for the words you think the user might probably enter, this is one way of doing it.

Why not use the list of words that should be ignored or removed from the input, i suggest you the following solution.
toIgnore = ["I'm ", "my name is ", "i am ", "you can call me "]
name = input("What is your name human? ")
for word in toIgnore:
name = name.replace(word, "")
while True:
try:
age = int(float(input("How old are you " + name + "? ")))
if age >= 50:
print(str(age) + "! Wow " + name + ", you're older than most of the oldest computers!")
else:
print ("Ahh, " + name + ", " + str(age) + " isn't that old.")
break
except ValueError:
print("No, I asked how old you were... ")
print("Let us try again.")
The output is following

Related

I'm getting the wrong output in my if statment

I'm new to python and am trying to fix this and By defualt its running the else statment I don't understand and need help. I'm new so please dumb your answers down to my -5 iq
menu = "Baguette , Crossiant , Coffee , Tea , Cappuccino "
print(menu)
if "" > menu:
order = input("What Would you like? \n ")
amount = input("How many " + order + " would you like?")
print( name + " Your " + amount + " " + order + " will be ready soon!\n\n\n")
price = int(4)
#converts number into intenger to do math correctly (int)
total = price * int(amount)
#turns total into string intead of intenger to prevent error in terminal
print("Thank you, your total is: $" + str(total))
print("Your " + amount + " of " + order + " is ready!")
print("Please enjoy you " + order + "!")
print("Please come again!")
else:
#If not on menu stops running
print("Sorry Thats not on the menu")
quit()
I changed the if "" to on_menu and list the options but it didn't work, and I asked people on discord.
menu = ["Baguette" , "Crossiant" , "Coffee" , "Tea" , "Cappuccino "]
count = 0
for item in menu:
print(str(count) +" -> "+str(item))
count += 1
order = int(input("\n What Would you like? \n "))
if order > len(menu) or order < 0 or order == "" or not menu[order]:
print("Sorry Thats not on the menu")
quit()
orderCount = int(input("How many " + menu[order] + " would you like?"))
print("Your " + str(orderCount) + " " + menu[order] + " will be ready soon!\n\n\n")
amount = int(4) * int(orderCount)
print("Thank you, your total is: $" + str(amount))
print("Your " + str(amount) + " of " + str(menu[order]) + " is ready!")
print("Please enjoy you " + str(menu[order]) + "!")
print("Please come again!")
Currently you are not checking the user input, you are just checking for a False statement based on what you defined. You need to check if the user input is on the menu, else quit the program.
menu = "Baguette , Crossiant , Coffee , Tea , Cappuccino "
print(menu)
name = input("What your name? \n ")
order = input("What Would you like? \n ")
if not order.lower() in menu.lower(): # checking if user input is in the menu
#If not on menu stops running
print("Sorry Thats not on the menu")
quit()
amount = input("How many " + order + " would you like?")
print( name + " Your " + amount + " " + order + " will be ready soon!\n\n\n")
price = int(4)
#converts number into intenger to do math correctly (int)
total = price * int(amount)
#turns total into string intead of intenger to prevent error in terminal
print("Thank you, your total is: $" + str(total))
print("Your " + amount + " of " + order + " is ready!")
print("Please enjoy you " + order + "!")
print("Please come again!")
#input name
name = input("What is your name?\n")
#create menu
menu = "Baguette, Crossiant, Coffee, Tea and Cappuccino"
#display menu
print(menu)
#input order
order = input("What would you like?\n")
#if the order item is in the menu
if order in menu:
#input quantity
amount = input("How many " + order + "s would you like? ")
#display message
print( name + " Your " + amount + " " + order + " will be ready soon!\n\n\n")
#setting price of all items to 4
price = 4
#calculating total
total = price * int(amount)
#turns total into string intead of intenger to prevent error in terminal
print("Thank you, your total is: $" + str(total))
print("Your " + amount + " of " + order + " is ready!")
print("Please enjoy you " + order + "!")
print("Please come again!")
#if the item is not in menu
else:
#display message
print("Sorry Thats not on the menu")
Hope this helps! I have added the explanation as comments.

Having Issues with a recursive function (Python)

Hello this is for my into to computer science final, using python and Tweepy. The function works until the while loop, where the input automatically goes to the else statement. I don't understand why this is happening, but I am assuming that it has to do with comparing the question variable with the string 'yes'
#Search for a user
def usersearch():
fp=open('UserSearch.txt','w')
user_search=input("Please enter the name of the user you would like to look up")
user = api.get_user(user_search)
fp.write(user_search)
fp.write("\n")
fp.write("User details:")
fp.write("\n")
print("User details:")
print("User name:" + " " + user.name)
fp.write("User name:" + " " + user.name)
fp.write("\n")
print("User description:" + " " + user.description)
fp.write("User description:" + " " + user.description)
fp.write("\n")
print("User location:" + " " + user.location)
fp.write("User location:" + " " + user.location)
fp.write("\n")
#Issue recalling function
while True:
question = input("Would you like to look up another user? (yes/no)").lower
if question == 'yes':
usersearch()
continue
elif question == 'no':
break
else:
print('Please enter either (yes/no)')

Python is asking for me to indent, but when I do, the line doesn't work. What should I do?

I was wondering about a specific problem I was having while writing a program. The program is very simple. Ask for some info about the person with some input functions, and then compile the information into one paragraph, summarizing some info about the person.
Here's some code (I'll explain after):
def main():
userName = input("What's your name?")
userAge = input("How old are you?")
userNumber = input("What's your favorite number?")
userAnimal = input("What's your favorite animal?")
print("Hi, my name is" + userName + "and I'm" + userAge + ".")
print("My favorite number is" + userNumber + "and my favorite animal is" + userAnimal + ".")
main()
Python keeps asking me to indent the line "userName = input("What's your name?")", so I did that. But when I do that, the line just flat out disappears from when I run it.
You meant to write :
def main():
userName = input("What's your name?")
userAge = input("How old are you?")
userNumber = input("What's your favorite number?")
userAnimal = input("What's your favorite animal?")
print("Hi, my name is : " + userName + " and I'm " + userAge + ".")
print("My favorite number is : " + userNumber + " and my favorite animal is " + userAnimal + ".")
main()
You have to indent the content of the main function.
def main():
userName = input("What's your name?")
userAge = input("How old are you?")
userNumber = input("What's your favorite number?")
userAnimal = input("What's your favorite animal?")
print("Hi, my name is" + userName + "and I'm" + userAge + ".")
print("My favorite number is" + userNumber + "and my favorite animal is" + userAnimal + ".")
main()

python random numbers and comparison

I'm a new programmer and just starting off with Python. I have the following 2 questions, however, I decided to put them in one post.
When asking to input age, how do I force the program to only accept numbers?
The concept is that after the user has entered their age, the program would pick a random number between 1 and 100 and compare it to the user input, returning either "I'm older than you", "I'm younger than you" or "we are the same age".
# Print Welcome Message
print("Hello World")
# Ask for Name
name = input("What is your name? ")
print("Hello " + str(name))
# Ask for Age
age = input("How old are you? ")
print("Hello " + str(name) + ", you are " + str(age) + " years old.")
random.randint(1, 100)
Try the following
import random
# Print Welcome Message
print("Hello World")
# Ask for Name
name = input("What is your name? ")
print("Hello " + str(name))
# Ask for Age
while True: # only numbers
try:
age = int(input("How old are you? "))
except:
pass
print("Hello " + str(name) + ", you are " + str(age) + " years old.")
t=random.randint(1, 100)
if t==age:
print("we are the same age") #compare ages
if t<age:
print("I'm younger than you")
if t>age:
print("I'm older than you")
Hi you can try this simply.
import random
name = input("What is your name? ")
print("Hello " + str(name))
while True :
try :
age = int(input("How old are you? "))
break
except :
print("Your entered age is not integer. Please try again.")
print("Hello " + str(name) + ", you are " + str(age) + " years old.")
randNumber=random.randint(1, 100)
if randNumber > age :
print("I am older than you")
if randNumber < age :
print("I am younger than you")
else :
print("we are the same age")
Only made few changes to existing code with modifications asked.
import random
# Print Welcome Message
print("Hello World")
# Ask for Name
name = input("What is your name? ")
print("Hello " + str(name))
# Ask for Age
while True:
try:
age = int(input("How old are you? "))
except ValueError:
pass
print("Hello " + str(name) + ", you are " + str(age) + " years old.")
my_random = random.randint(1, 100)
if my_random > age:
print("Im older than you")
elif my_random < age:
print("I'm younger than you")
else:
print("We are the same age")
Includ a try block around the age part. If the user inputs an non-int answer then it will just pass. I then saved the random int that you generated it and compared it to the age to find if the random int was greater than the age.
To answer your first question, use int() as such:
age = int(input("How old are you? "))
This will raise an exception (error) if the value is not an integer.
To answer your second question, you may store the random number in a variable and use it in comparison to the user's age, using conditional statements (if, elif, else). So for instance:
random.seed() # you need to seed the random number generator
n = random.randint(1, 100)
if n < age:
print("I am younger than you.")
elif n > age:
print("I am older than you.")
else:
print("We are the same age.")
I hope this answers your question. You can refer to the official Python docs for more info on conditional statements.
My guess is that you should convert the variable age into integer. For example:
age = input("How old are you?")
age = int(age)
This should work.
The answer to the 1st question.
x = int(input("Enter any number: "))
To force the program to enter number add int in your input statement as above.

Reducing the number of conditionals in a small python script [duplicate]

This question already has answers here:
Date Ordinal Output?
(14 answers)
Closed 6 years ago.
I have been developing a small program.
It works perfectly how it is but I want to make the code a bit smaller.
import time, math
name= input("Enter Your Name: ")
age= int(input("Enter Your Age: "))
end= "th"
if age == 3 or age == 13 or age == 23 or age == 33 or age == 43 or age == 53 or age == 63 or age == 73 or age == 83 or age == 93:
end= "rd"
if age == 2 or age == 22 or age == 32 or age == 42 or age == 52 or age == 62 or age == 72 or age == 82 or age == 92:
end= "nd"
print ("Your Name Is "+ name + ", You Are " + str(age) + " Years Old.")
print ("Hi " + name + ", Happy " + str(age) + end + " birthday!")
time.sleep(5)
I would like to have an easier way to change the 'end' to other values without having to write them all, can I have it start at 3 then do it for everything 10 more than three.
Use the modulo operator:
if age % 10 == 3:
end = "rd"
elif age % 10 == 2:
end = "nd"
Or use a dict:
ends = {2: "nd", 3: "rd"}
end = ends[age % 10]
You can also use a default:
ends = {1: "st", 2: "nd", 3: "rd"}
end = ends.get(age % 10, "th)
Extract the digit at tenth's place. Then it's straightforward. Though this question belongs to the codereview counterpart of SO.
import time, math
name= input("Enter Your Name: ")
age= int(input("Enter Your Age: "))
tenth_place = age % 10
if tenth_place == 3:
end = "rd"
elif tenth_place == 2:
end = "nd"
else:
end = "th"
print ("Your Name Is "+ name + ", You Are " + str(age) + " Years Old.")
print ("Hi " + name + ", Happy " + str(age) + end + " birthday!")
time.sleep(5)
if age in range(3,93,10) :
end = "rd"
You can try this:
if int(age[-1]) == 3:
end= "rd"
if int(age[-1]) == 2:
end= "nd"
Might not be shorter necessarily, but it works (and keeps 12th and 13th proper).
import time, math
name = input("Enter Your Name:")
age = int(input("Enter Your Age:"))
end = "th"
# initializing age lists
list1 = []
list2 = []
# filling list1 with ages 3-93
for i in range(0,10):
list1.append(10*i+3)
# filling list2 with ages 2-92
for i in range(0,10):
list2.append(10*i+2)
# if block to include correct suffix
for ages in list1:
if ages == 13:
end = end;
elif ages == age:
end = "rd"
for ages in list2:
if ages == 12:
end = end
elif ages == age:
end = "nd"
print ("Your Name Is "+ name + ", You Are " + str(age) + " Years Old.")
print ("Hi " + name + ", Happy " + str(age) + end + " birthday!")
time.sleep(5)
Thanks For All Of It Guys,
I have also found another flaw and fixed it, here is my current code.
Thanks.
import time, math
name= input("Enter Your Name: ")
age= int(input("Enter Your Age: "))
end= "th"
if age % 10 == 3:
end = "rd"
elif age % 10 == 2:
end = "nd"
elif age % 10 == 1:
end = "st"
if age < 20 and age > 10:
end = "th"
print ("Your Name Is "+ name + ", You Are " + str(age) + " Years Old.")
print ("Hi " + name + ", Happy " + str(age) + end + " birthday!")
time.sleep(2)
Thanks,
Bilbo

Categories

Resources