Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 9 years ago.
Improve this question
number1 = float
number2 = float
number1 = raw_input("Please input the first number: ")
number2 = raw_input("Please input the second number: ")
if number1 > number2:
print number1 + ' is bigger than ' + number2
elif number2 < number1:
print number2 + ' is bigger than ' + number1
else:
print 'You did not follow the instructions properly. Goodbye!'
print "\n"
raw_input("Please press enter to exit.")
These lines:
number1 = float
number2 = float
do not make the inputs into floats. Instead, all they do is assign the variables to the built-in float.
This is what you should be doing:
number1 = float(raw_input("Please input the first number: "))
number2 = float(raw_input("Please input the second number: "))
Also, inside your if-statements, you cannot add strings and floats together (trying to do so will raise a TypeError). There are two ways to solve this problem. The first is with str.format:
print '{} is bigger than {}'.format(number1, number2)
The second is to separate the values with commas:
print number1, 'is bigger than', number2
Finally, your logic is a little off. The second if-statement should be like this:
elif number1 < number2:
Otherwise, it does the same thing as the first if-statement.
Below is a fixed version of your script:
number1 = float(raw_input("Please input the first number: "))
number2 = float(raw_input("Please input the second number: "))
if number1 > number2:
print '{} is bigger than {}'.format(number1, number2)
elif number1 < number2:
print '{} is bigger than {}'.format(number2, number1)
else:
print 'You did not follow the instructions properly. Goodbye!'
print "\n"
raw_input("Please press enter to exit.")
You are comparing strings, which means they are compared lexicographically.
Cast the return value of raw_input to float:
number1 = float(raw_input("Please input the first number: "))
number2 = float(raw_input("Please input the second number: "))
The lines:
number1 = float
number2 = float
merely store references to the float() constructor. Python doesn't have type declarations, and those lines do not mean that the two names should only hold floating point values.
You do then need to turn the floating point numbers back to strings when printing; you could use the fact that print accepts multiple values to have this done for you:
if number1 > number2:
print number1, 'is bigger than', number2
elif number2 < number1:
print number2, 'is bigger than', number1
Alternatively, you could store the raw_input() results as strings and only turn the values to float() when comparing:
number1 = raw_input("Please input the first number: ")
number2 = raw_input("Please input the second number: ")
if float(number1) > float(number2):
print number1 + ' is bigger than ' + number2
elif float(number2) < float(number1):
print number2 + ' is bigger than ' + number1
Related
first_num, second_num = input("Enter the first number: "), input("Enter the second number: ")
if first_num > second_num :
print(first_num, ' is the greatest number.')
else :
print(second_num, ' is the greatest number.')
You are comparing two strings, not integer or float.
you must convert input to int or any other format you want then compare them. So the complete code should be:
first_num, second_num = int(input("Enter the first number: ")),
int(input("Enter the second number: "))
if first_num > second_num :
print(first_num, ' is the greatest number.')
else :
print(second_num, ' is the greatest number.')
I am new to python and trying to learn the best way to learn to code. I am practicing with some simple code that asks for 2 numbers and multiples them and I want to add a a function to ask if you are done or if you want to multiply some more numbers. Below is the code I started with. I want to know what is the best way to have it loop back to asking for 2 more numbers with a yes or no question?
#Ask for number to be multiplied
num1 = input("\nEnter the first number you want to multiply: ").strip()
num2 = input("\nEnter the second number you want to multiply: ").strip()
#Convert input to interger
num1 = int(num1)
num2 = int(num2)
#Multiply the numbers
results = num1 * num2
#Print the results
print("Your answer is: " + str(results))
You can set a reminder like when the user is finish then make you can make the reminder is False to make it finish or take a input and check if user want to exit then just simply break the loop.
# set reminder for while loop
done = False
while not done:
#Ask for number to be multiplied
num1 = input("\nEnter the first number you want to multiply: ").strip()
num2 = input("\nEnter the second number you want to multiply: ").strip()
#Convert input to interger
num1 = int(num1)
num2 = int(num2)
#Multiply the numbers
results = num1 * num2
#Print the results
print("Your answer is: " + str(results))
ask = input('Do you want to try again y/n: ')
if ask == 'n':
done = True # set the reminder is true or break the loop
# break
While loop is the most used one:
repeat = 'yes'
while repeat.lower() == 'yes':
#Ask for number to be multiplied
num1 = input("\nEnter the first number you want to multiply: ").strip()
num2 = input("\nEnter the second number you want to multiply: ").strip()
#Convert input to interger
num1 = int(num1)
num2 = int(num2)
#Multiply the numbers
results = num1 * num2
#Print the results
print("Your answer is: " + str(results))
print('If you want to continue type yes or no')
repeat = input()
You can do that by wrapping the whole code in a while True loop with a break statement to exit. Essentially, we will want to repeat the process forever, until the user types n or N. The check condition can be refined as desired.
while True:
# Ask for number to be multiplied
num1 = input("\nEnter the first number you want to multiply: ").strip()
num2 = input("\nEnter the second number you want to multiply: ").strip()
# Convert input to interger
num1 = int(num1)
num2 = int(num2)
# Multiply the numbers
results = num1 * num2
# Print the results
print("Your answer is: " + str(results))
# Ask to continue or not
res = input("\nWould you like to continue? (y/n) ").strip()
if res.lower() == 'n':
break
Just simple use while loop and declare a variable named choice and ask the user to enter his choice.
while(True):
choice = input("Would you like to continue? (y/n) ")
if(choice.lower=='y'):
num1 = int(input("\nEnter the first number you want to multiply: "))
num2 = int(input("\nEnter the second number you want to multiply: "))
results = num1 * num2
print("Your answer is: ",results)
else:
break
def termination():
_noexit=str(raw_input())
if _noexit.lower() == 'y':
return True
else:
return False
#Cal the termination condition
while termination:
num1 = input("\nEnter the first number you want to multiply: ")
num2 = input("\nEnter the second number you want to multiply: ")
num1 = int(num1)
num2 = int(num2)
results = num1 * num2
print results
#Checking termination
termination()
The code is supposed to be a simple maths quiz, however, when I enter the correct answer, it says it's wrong. My code is:
import random
name = input("What is your name? ")
question = 0
correct = 0
while question < 10:
question = question + 1
number1 = random.randint(1, 50)
number2 = random.randint(1, 50)
print("What is", number1, "+", number2)
answer = number1 + number2
print(answer)
student = input()
if student == answer:
print("Correct! Well Done!")
correct = correct + 1
else:
print("Wrong!")
Any ideas?
You forgot to cast the user input to int, so replace student = input() with student = int(input()), as at the moment you are comparing str to int.
Assuming that you are using Python 3, you need to type cast input() to int() in order to compare it with answer which is an integer:
student = int(input())
Assuming python3. The following is not valid for python2, as input treats an integer input as integer.
input() in python2 evaluates the expression with eval() function after reading from stdin, thus returning an integer.
The problem relies on the fact you are comparing strings to answer that is an integer.
import random
name = input("What is your name? ")
question = 0
correct = 0
while question < 10:
question = question + 1
number1 = random.randint(1, 50)
number2 = random.randint(1, 50)
print("What is", number1, "+", number2)
answer = number1 + number2
print(answer)
student = input()
#Cast the input to an integer for comparison
if int(student) == answer:
print("Correct! Well Done!")
correct = correct + 1
else:
print("Wrong!")
As many have already said, you need to cast the user input to int, replace student = input()
Also, you can do question += 1, rather than question = question + 1. This can help speed you up.
Alright, so I am new with python at the moment and I am absolutely confusing myself with such a simple task. I have to write a function to calculate the average of two numbers, but the user must input the numbers so the average should print out.
I keep getting a a name error, name 'number2' is not defined.Below is my code.
number1 = raw_input("Enter number1")
number2 =raw_input("Enter number2")
def average(number1, number2):
return (number1 + number2) / 2
avg=average = (number1,number2)
print avg
I'm doing something wrong and I know its obvious but I can't quite put my finger on it.
You are making incorrect call to your function. You should do:
# v type-cast value to `int` as `raw_input` returns `str` object
avg = average(int(number1), int(number2))
# ^ ^ make a call to `average()` and store the returned value as `avg`
Below is the complete code sample:
>>> number1 = raw_input("Enter number1: ")
Enter number1: 12
>>> number2 =raw_input("Enter number2: ")
Enter number2: 45
>>> def average(number1, number2):
... return (number1 + number2) / 2.0 # `2.0` to get floating precision
...
>>> avg = average(int(number1), int(number2))
>>> avg
28
Note: In Python 2.x, division of two int returns an int value. If you want the response as float, use 2.0 instead of 2 for division
You have defined average as a function, and you must use it as a function. Something like this:
number1 = raw_input("Enter number1")
number2 =raw_input("Enter number2")
def average(number1, number2):
return (int(number1) + int(number2)) / 2.0
avg=average(number1,number2)
print avg
There were two other things too. You must convert string to integer, and to get a good average you have to divide them by 2.0 instad of 2. Onother way to solve it is to convert the string to float directly.
You can try something like this:
#get number 1, number2 as integers
number1 = int(raw_input("Enter number1"))
number2 =int(raw_input("Enter number2"))
#your function as it was
def average(number1, number2):
return (number1 + number2) / 2
#function `average` returns an int. Store that result in `avg`
avg = average(number1,number2)
#print the result
print(avg)
What you are doing wrong is taking raw_input and not converting it to an integer before arithmetical operation.
When using numbers in python, always use input() other than raw input, to save yourselves from converting raw_iniput to an integer because the input command already takes it as an int.
def avg(a=input('Pls enter val 1: '),b=input('Pls entr val 2: ')):
return ((a / b) / 2.0)
a=avg()
And when using python 2.7 always use float values while dividing cause dividing two integers will always return int whether or not the answer is float.
So , you can use something like this as well:
number1 = float(input("Enter number1"))
number2 = float(input("Enter number2"))
def average(number1, number2):
return (number1 + number2) / 2.0
avg=average = (number1,number2)
print avg
When I run the code below, I get the following error: eval() arg 1 must be a string or code object
Anyone know why? This is code i'm learning from a book, so I assumed that it would be correct.
# Prompt the user to enter three numbers
number1 = eval(input("Enter the first number: "))
number2 = eval(input("Enter the second number: "))
number3 = eval(input("Enter the third number: "))
# Compute average
average = (number1 + number2 + number3) / 3
print("The average of", number1, number2, number3, "is", average)
You are using input() on Python 2, which already runs eval() on the input. Just remove the eval() call, or replace input() with raw_input().
Alternatively, use Python 3 to run this code, it is clearly aimed at that version. If your book uses this syntax, then you want to use the right version to run the code samples.
Most of all, don't use input() on Python 2 or eval() on Python 3. If you want integer numbers, use int() instead.
Python 2 example:
# Prompt the user to enter three numbers
number1 = int(raw_input("Enter the first number: "))
number2 = int(raw_input("Enter the second number: "))
number3 = int(raw_input("Enter the third number: "))
# Compute average
average = (number1 + number2 + number3) / 3
print "The average of", number1, number2, number3, "is", average
Python 3 version:
# Prompt the user to enter three numbers
number1 = int(input("Enter the first number: "))
number2 = int(input("Enter the second number: "))
number3 = int(input("Enter the third number: "))
# Compute average
average = (number1 + number2 + number3) / 3
print("The average of", number1, number2, number3, "is", average)