I wrote this program but it is not executing when I print it:
age= int(input("How old is your dog?"))
if age>0:
print("Please input positive number")
elif age<=2:
dage= age*10.5
else age>2:
dage=21+((age-2)*4)
print("The dog is", dage, "years old")
print(age)
What am I missing to make it run?
I think you want to unindent the conditional statements. I think your conditional statements also need some work -- I've updated it a bit. See below.
Try
age = int(input("How old is your dog?" ))
dage = 0
if age < 0:
print("Please input positive number")
elif age <= 2:
dage = age*10.5
else:
dage = 21+((age-2)*4)
print("The dog is", dage, "years old")
print("age", age)
Related
I am working on a simple python exercise where I ask a series of questions and get input from the user. I prompt the user with "Enter your age" and I want the program to continue rather than be corrupt if the user enters a letter value for the age rather than int because I am converting to int to figure if the age is less than 18 or greater than and if it is between specific ages. I can't convert letters to an int.
age = input("Please enter your age: ")
if int(age) < 18 or int(age) > 120:
print("We're sorry, you are not old enough to be qualified for our program. We hope to see you in the future.")
end()
if int(age) > 18 and int(age) < 120:
print("You are " + age + "years old.")
if int(age) > 120:
print("You are not qualified for this program. ")
end()
#Somewhere in this script I am hoping to accept the letter input without sending an error to the program.
Use try/except.
age = input("Please enter your age: ")
try:
if int(age) < 18 or int(age) > 120:
print("We're sorry, you are not old enough to be qualified for our program. We hope to see you in the future.")
end()
if int(age) > 18 and int(age) < 120:
print("You are " + age + "years old.")
if int(age) > 120:
print("You are not qualified for this program. ")
end()
except:
print("Please enter a number")
If your int conversion fails the code will jump to except instead of crashing.
If you want the user to retry, you could write something like this instead. Be aware of the ranges you're using and negative numbers.
age = input("Please enter your age: ")
ageNum = 0
while(ageNum <= 0):
try:
ageNum = int(age)
if (ageNum) < 18 or ageNum > 120:
print("We're sorry, you are not old enough to be qualified for our program. We hope to see you in the future.")
end()
elif ...
except:
print("Please enter a valid number")
I'd use a while loop, e.g.
while int(age) != age:
input("Age must be an integer.\nPlease try again.")
And as #Barmar stated, you need to check your if statements.
I just started picking up python and I want to know how to do what I said in the title. The only background in programming I have is a semester long C++ class that I had in high school that I got a C in and forgot almost everything from. Here's my code:
while True:
try:
height_m = float(input("Enter your height in meters: "))
except ValueError:
print ("Please enter a number without any other characters.")
continue
else:break
while True:
try:
weight_kg = float(input("Enter your weight in kilograms: "))
except ValueError:
print ("Please enter a number without any other characters.")
continue
else:break
bmi = weight_kg / (height_m ** 2)
print ("Your bmi is",(bmi),".")
if bmi < 18.5:
print ("You are underweight.")
elif 18.5 <= bmi <=24.9:
print ("You are of normal weight.")
elif 25 <= bmi <= 29.9:
print ("You are overweight.")
else:
print ("You are obese.")
As you can see, it's just a basic BMI calculator. However, what I wanted to do was make it so that if someone were to input "1.8 m", "1.8 meters" or "1.8 ms" and the equivalent for kilograms, the program would remove the extra input and process it as if they hadn't added that. Also, any extra tips you have for me would be great. Thanks!
Replace the third line with this:
height_m = float(''.join([e for e in input("Enter your height in meters: ") if not e.isalpha()]))
It works by removing all alphabets before converting to float.
In general, this works
Height_List = []
Height = input("What is your height")
for i in Height:
if i in "1234567890.":
Height_List.append(i)
Actual_Height = float("".join(Height_List))
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.
print("Hello there")
name=input("What is your name?")
print("Welcome to the some game, " + name + "!")
print("I'm going to ask you some basic questions so that we could work together")
age=input("Your age")
if age >= 14 and age < 41:
print("K")
else:
print("Sorry bruh")
print("Thanks")
keeps showing me "Sorry bruh" at the end when entered 15. Why? What's wrong?
Cast your input to int:
age = int(input("Your age"))
You could add a try-except. Your condition should equally be evaluated on or not and
Either you use Python3 and you need to cast with int(input("Your age")) or you use Python2 and then you need to use raw_input to read the name: name=raw_input("What is your name?")
Ok , so you can try this code in python2.7 and it will work as you desired:
print("Hello there")
name=raw_input("What is your name?")
print("Welcome to the some game, " + name + "!")
print("I'm going to ask you some basic questions so that we could work together")
age=input("Your age")
if age >= 14 and age < 41:
print("K")
else:
print("Sorry bruh")
print("Thanks")
Teaching myself Python out of a book and I'm stuck on this exercise:
A movie theater charges different ticket prices depending on a person’s age. If a person is under the age of 3, the ticket is free; if they are between 3 and 12, the ticket is $10; and if they are over age 12, the ticket is $15. Write a loop in which you ask users their age, and then tell them the cost of their movie ticket.
I know how to make it work without using a loop but I am a uncertain how to make it work using a while loop. Any advice or examples would be greatly appreciated.
One way to do this would be an infinite loop. Don't forget to include a break condition, otherwise you won't be able to exit your program gracefully.
while True:
userinput = int(input())
if userinput < 0:
break
# your if logic goes here
I was able to figure it out on my own
prompt = "\nEnter 'quit' when you are finished."
prompt += "\nPlease enter your age: "
while True:
age = input(prompt)
age = int(age)
if age == 'quit':
break
elif age <= 3:
print("Your ticket is free")
elif age <= 10:
print("Your ticket is $10")
else:
print("Your ticket is $15")
One way of doing it would be creating an infinite loop like such:
price = -1
while price == -1:
try:
age=int(raw_input('Age: '))
except ValueError:
print "Not a number, try again."
continue
if age <= 3:
price = 0
elif age > 3 and age < 12:
price = 10
else:
price = 15
print "The price will be "+str(price)+"$."
Note:
Rename raw_input() to input() if you are using Python 3.
I know this is an old question but none of the answers seemed great. So here's my solution to 7-5/ 7-6
loop = True
#while loop = true run 'while loop'
while loop:
#Print message
print ('Please enter your age.')
#receive input from user
age = raw_input()
#check if the user input "quit" if so end loop. Break ends program but should be replaceable by
#if age == 'quit':
# loop = False
#resulting the the same effect (ending loop)
if age == 'quit':
break
#Convert age input by user to int so it is recognized as a number by python
age = int(age)
#If/ elif pretty self explanatory
if age < 3:
price = 5
elif age < 12:
price = 10
elif age > 12:
price = 15
else:
print('Input not recognized')
break
#Print ticket price based on age and ask user if they need another price/inform them how to exit program
print('Your ticked price is $' + str(price) + '.')
print('\n If you would like to check the price for another person please enter their age now or type "quit" to exit')
The formatting might be a little off since it pasted oddly. I tried to explain what everything does. Also I use 2.7 instead of 3 so if you're using python 3 replace raw_input() with input()
Hopefully this answer was helpful to some on. GL with programming.
prompt = "How old are you? "
prompt += "\nEnter 'quit' when you are finished. "
while True:
age = input(prompt)
if age == 'quit':
break
age = int(age)
if age < 3:
print("Your ticket is free. Congratulations")
elif age < 13:
print("Your ticket is $10 dollars")
else:
print("Your ticket is $15 dollars")
prompt = "\nPlease enter 'done' when finished! "
prompt += "\nPlease enter your age:"
while True:
try:
age = input(prompt)
if age == 'done':
break
age = int(age)
if age <= 3:
print("Free ticket")
elif age in range(4, 12):
print("You must pay 10$")
elif age >= 12:
print("You must pay 15$")
except ValueError:
continue