Guys I tried a couple of ways to solve a problem I am having.
My program works well without decimal numbers.
I want to get an answer with decimal points.
So each time i type in the decimal point, there is an error.
This is what I tried:
from __future__ import division
def bmi (): ## bmi = body mass index
print " program to calculate person BMI"
name = raw_input(" Hi welcome , what is your name ? : ")
print " welcome %s " % name
weight = raw_input (" your weight(kg) : ")
height = raw_input ("your height (m): ")
bmi = int(weight)
bmi_1 = int(height)
if bmi/bmi_1**2 <= (25):
print " your ibm is : %d , you are not overweight "%( bmi/bmi_1**2)
elif bmi/bmi_1**2 >= 24:
print " your iibm is : %d , sorry you are overweight" % ( bmi/bmi_1**2)
else :
print " sorry mistake, try again "
float()
and
str()
Will do the trick.
Related
so im learning this program BMI calculator, and i want the answers to be written after the ':', not under it. can anyone help me pls? is it even possible to get that type of answer?
heres the code:
name = "hello"
height_m = 2
weight_kg = 110
bmi = weight_kg / (height_m ** 2)
print("bmi:")
print(bmi)
if bmi < 25:
print(name)
print("is not overweight")
else:
print(name)
print("is overweight")
#printed:
bmi:
27.5
hello
is overweight
#but what i want is this:
bmi: 27.5
hello is overweight
You need to put a comma in the same print statement instead of two separate ones.
print("bmi:",bmi)
instead of
print("bmi:")
print(bmi)
Try this
name = "hello"
height_m = 2
weight_kg = 110
bmi = weight_kg / (height_m ** 2)
print("bmi: {}".format(bmi)
if bmi < 25:
print("{} is not overweight".format(name))
else:
print("{} is overweight".format(name))
#prints:
bmi: 27.5
hello is overweight
Try this,
name = "hello"
height_m = 2
weight_kg = 110
bmi = weight_kg / (height_m ** 2)
print("bmi:", end=' ')
print(bmi)
if bmi < 25:
print(name, end=' ')
print("is not overweight")
else:
print(name, end=' ')
print("is overweight")
Or you can put everything in a single print statement like this,
print(name, "is overweight")
print("bmi:", bmi)
You can either do:
print("bmi:", bmi) # the simplest
or
print(f"bmi: {bmi}") # f string in Python 3
or
print("bmi: ", end="") # Your original code, modified
print(bmi)
or
print("bmi: %s " % bmi) # too extreme -- don't do it for this simple case
or
print("bmi: {}".format(bmi)) # too extreme
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 would like to understand why one program of mine is giving error and one not where as I am applying same concept for both of them.
The program that is giving error:
greeting = "test"
age = 24
print( greeting + age)
Which is true and it should give error because of incompatible variable types being concatenated. But this same behavior I was expecting from the below code as well where as it is giving proper result. Why is it so?
print("Please enter your name: ")
myname = input()
print("Your name is " + myname)
print("Please enter your age: ")
myage = input()
print("Your age is: " + myage)
print("Final Outcome is:")
print(myage + " " + myname)
By default the input function in Python returns a string type. So when you enter the age, it is not being returned to your program as an int but rather a string. So:
print("Your age is: " + myage)
Actually looks like:
print("Your age is: " + "24")
input() returns a string, even if the user enters a number.
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.
I created the simple code:
name = raw_input("Hi. What's your name? \nType name: ")
age = raw_input("How old are you " + name + "? \nType age: ")
if age >= 21
print "Margaritas for everyone!!!"
else:
print "NO alcohol for you, young one!!!"
raw_input("\nPress enter to exit.")
It works great until I get to the 'if' statement... it tells me that I am using invalid syntax.
I am trying to learn how to use Python, and have messed around with the code quite a bit, but I can't figure out what I did wrong (probably something very basic).
It should be something like this:
name = raw_input("Hi. What's your name? \nType name: ")
age = raw_input("How old are you " + name + "? \nType age: ")
age = int(age)
if age >= 21:
print "Margaritas for everyone!!!"
else:
print "NO alcohol for you, young one!!!"
raw_input("\nPress enter to exit.")
You were missing the colon. Also, you should cast age from string to int.
Hope this helps!
With python, indentation is very important. You have to use the correct indentation or it won't work. Also, you need a : after the if and else
try:
if age >= 21:
print #string
else:
print #other string
Firstly raw_input returns a string not integer, so use int(). Otherwise the if-condition if age >= 21 is always going to be False.:
>>> 21 > ''
False
>>> 21 > '1'
False
Code:
name = raw_input("Hi. What's your name? \nType name: ")
age = int(raw_input("How old are you " + name + "? \nType age: "))
The syntax error is there because you forgot a : on the if line.
if age >= 21
^
|
colon missing