def die():
first = str(randint(1, 6))
second = str(randint(1, 6))
total = first + second
print "You have rolled a " + first + " and a " + second + ", for a total score of " + total + "."
Standard die throwing game, but I'm struggling to print the values for individual die as well as the total. Treating as a string for individual, but then sum leads to concatenation rather than actual sum.
Thanks
Keep your variables as numbers and let print do the formatting:
def die():
first = randint(1, 6)
second = randint(1, 6)
total = first + second
print "You have rolled a", first, "and a", second, ", for a total score of", total, "."
Or you could do some formatting using str.format to have more control over the default inter-parameter spacing in the above:
print "You have rolled a {} and a {}, for a \
total score of {}.".format(first, second, total)
There are two ways to address your problem (and more still!). Firstly, you need to make sure you keep your integers as type int when adding them together, and then cast them to a string when you print them out.
You can do this like the below, using the str() casting method and + concatenation.
def die1():
"""Roll and print two dice using concat."""
first = randint(1, 6) # keep these as integers
second = randint(1, 6)
total = first + second # so addition works
# but now cast to str when printing
print "You have rolled a " + str(first) + " and a " + str(second) + ", for a total score of " + str(total) + "."
But a handier way is to use the str.format() method to put placeholders in your string, and then let python cast and format the integer values for you. If you have big numbers with 4 or more digits, an advantage of this would be that you can use a string formatting code like "my big number: {0:d,}".format(1000000) to make your string output like "my big number: 1,000,000", which is much more readable.
def die2():
"""Roll and print two dice using str.format()."""
first = randint(1, 6)
second = randint(1, 6)
total = first + second
# or use the str.format() method, which does this for you
print "You have rolled a {0} and a {1}, for a total score of {3}.".format(first, second, total)
You can use casting to change the structure of the var. You can either use them as strings and for total use this line:
total = int(first) + int(second)
or use them as int and cast them to string in the print by using str(first) and str(second)
Best
print "You have rolled a " + str(first)
This would convert the int to a string, hence concatenating it.
Also, you can do
total = int(first) + int(second) to address the first issue.
You have two solutions:
Convert the numbers back to int before adding them:
def die():
first = str(randint(1, 6))
second = str(randint(1, 6))
total = str(int(first) + int(second))
print ("You have rolled a " + first + " and a " + second + ", for a total score of " + total + ".")
Convert the numbers into str before printing them:
def die():
first = randint(1, 6)
second = randint(1, 6)
total = first + second
print ("You have rolled a " + str(first) + " and a " + str(second) + ", for a total score of " + str(total) + ".")
Either solution will work perfectly fine.
This would also work. Don't convert first and second to str until after you perform sum on them. Then remember to cast them as str in your print statement.
def die():
first = randint(1, 6)
second = randint(1, 6)
total = str(first + second)
print ("You have rolled a " + str(first) + " and a " + str(second) + ", for a total score of " + total + ".")
Related
This question already has answers here:
Comparing numbers give the wrong result in Python
(4 answers)
Closed 11 months ago.
I coded a small project that you can enter two numbers in and it will tell you what's smaller and what's bigger, what's the difference between them and if they're equal, but the code thinks that 100 is smaller than 50.. I've also entered numbers like 50;70 and 60;70, but then it says the correct thing which is that the first number is smaller than the second one. I don't understand what's wrong, and how can I fix it? Here's my code, you can run it yourself so you can see what will happen.
import math
import time
num1 = int(input("Enter the first number: "))
num2 = int(input("Enter the second number: "))
difference = num1 - num2
if str(num1) > str(num2):
print("--" + str(num1) + " is greater than " + str(num2) + ".")
print("--The difference between " + str(num1) + " and " + str(num2) + " is " + str(difference) + "." )
elif str(num1) < str(num2):
pass
print("--" + str(num1) + " is smaller than " + str(num2))
print("--The difference cannot be calculated because " + str(num1) + " is smaller than " + str(num2) + ".")
else:
print(str(num1) + " and " + str(num2) + " are equal.")
The problem, as several commenters have pointed out, is that you're doing a string conversion on the input numbers.
As integers, 50 < 100, but for strings, ordering is done alphabetically - and "1" comes before "5", so "100" < "50".
Drop the str() calls and you should be good.
I'm making an economic simulator type thing in python and when trying to calculate total cost when buying something i keep getting either an int error or a float error please help.
can only concatenate str (not "float") to str
import time
money = 1
moneyfo = "{:.2f}".format(money)
woodinv = 0
woodsalea = 1
woodprice = (woodsalea / 2)
woodpricefo = "{:.2f}".format(woodprice)
amntw = 0
float(amntw)
buywcost = 0
print ("Prducts are wood food and stone")
print ("Prices are wood(" + woodpricefo + ")")
bos = input("""Buy Or Sell
""")
if bos == ("Buy"):
btyp = input("""Wood, Food, Or Stone?
""")
if btyp == ("Wood"):
amntw = input("0-100")
buywcost = float(amntw) * woodprice
buywcostfo = "{:.2f}".format(buywcost)
print ("That will be" + float(buywcostfo) + "you have" + money + "would you like to buy")
It's just like the error says--you can only concatenate strings to other strings--i.e. when combining strings using the + operator, you must actually combine strings.
Here is my edited version of the code. I think you avoid the error in question, though I would also recommend making it more readable by adding comments and using more descriptive variable names.
import time
money = 1
moneyfo = "{:.2f}".format(money)
woodinv = 0
woodsalea = 1
woodprice = (woodsalea / 2)
woodpricefo = "{:.2f}".format(woodprice)
amntw = 0
float(amntw)
buywcost = 0
print ("Prducts are wood food and stone")
print ("Prices are wood(" + woodpricefo + ")")
bos = input("""Buy Or Sell""")
if bos == ("Buy"):
btyp = input("""Wood, Food, Or Stone?""")
elif btyp == ("Wood"):
amntw = input("0-100")
buywcost = float(amntw) * woodprice
buywcostfo = "{:.2f}".format(buywcost)
print ("That will be" + str(float(buywcostfo)) + "you have" + str(money) + "would you like to buy")
Your errors are here:
print ("That will be" + float(buywcostfo) + "you have" + money + "would you like to buy")
You need to convert numbers to strings before adding them to other strings:
print ("That will be" + str(float(buywcostfo)) + "you have" + str(money) + "would you like to buy")
Also, this isn't doing what you probably intend:
float(amntw)
You have to save the result of the conversion to a float - it doesn't change the number in-place:
amntw = float(amntw)
However, as you do this:
amntw = 0
float(amntw)
Assuming your intent was to make amntw the float equivalent of 0 you can simply set it directly as a float value:
amntw = 0.0
In your print statement you are casting the type to a float and so you are trying to concatenate a string and a float in 2 different places, python does not allow this.
Change this line:
print ("That will be" + float(buywcostfo) + "you have" + money + "would you like to buy")
Option 1:
print ("That will be" + buywcostfo + "you have" + str(money) + "would you like to buy")
Option 2, Python also has a feature called f strings which allow you to put variables directly inside the string:
print(f"That will be {buywcostfo} you have {money} would you like to buy")
only you have to change the last line as follows
print ("That will be " + str(float(buywcostfo)) + " you have " + str(money) + " would you like to buy")
you can choose print formattings as given here
Not sure why you're initializing variables before they're being used. That's not necessary in python.
amntw = 0 # You don't need any of this
float(amntw) # float() isn't doing anything here without assignment
buywcost = 0 # It's just making your code messy
And don't do str(float(buywcostfo)) as others are suggesting. That would be redundant. Since buywcostfo is already a string, you would be casting a string to a float and back to a string again.
buywcost = float(amntw) * woodprice # buywcost is now a float
buywcostfo = "{:.2f}".format(buywcost) # buywcostfo is a string
print("That will be" + float(buywcostfo) ...) # now it's a float again - can't add to string
You should read up on f-strings. They can make your life easier and really clean up your code a lot.
# This way unless the variables buywcostfo and moneyfo are needed elsewhere,
# they can be removed completely.
print(f"That will be {buywcost:.2f} you have {money:.2f} would you like to buy")
This question already has answers here:
How can I read inputs as numbers?
(10 answers)
Closed 7 months ago.
name = input("Say your name: ")
integerr = input(name + " pick an integer ")
numberr = input(name + " pick another integer ")
This is where I get my error
if (integerr % numberr) >= 1:
print(integerr + " is divisible by " + numberr)
else:
print(integerr + " is not divisible by " + numberr)
You have two mistakes.
input always returns a string, as Simsteve7 mentioned. You can convert to an integer using int(), and convert to a string using str().
You need to check if integerr % numberr == 0, because that means that numberr divides into integerr evenly; thus integerr is divisible by numberr.
Below is a solution for Python 2:
name = input("Say your name: ")
integerr = int(input(name + " pick an integer "))
numberr = int(input(name + " pick another integer "))
if (integerr % numberr) == 0:
print(str(integerr) + " is divisible by " + str(numberr))
else:
print(str(integerr) + " is not divisible by " + str(numberr))
If you're using Python 3, you can use f-strings. That would look like this:
if (integerr % numberr) == 0:
print(f"{integerr} is divisible by {numberr}")
else:
print(f"{integerr} is not divisible by {numberr}")
Learning the basics of python and I am running across a problem. I'm sure it is a simple fix. I'm trying to get my program to get 20 different inputs before calculating the min, max, etc.
def main():
number = valueInput()
display(number)
def valueInput():
print("Please enter 20 random numbers")
values = []
for i in range(20):
value1 =(int(input("Enter a random number " + str(i + 1) + ": ")))
values.append(value1)
return values
def display(number):
print("The lowest number is:", min(number))
print("The highest number is:", max(number))
print("The sum of the numbers is:", sum(number))
print("The average number is:", sum(number)/len(number))
main()
I can get it to work by repeating this line:
value1 =(int(input("Enter a random number " + str(i + 1) + ": ")))
to the 20th number but there must be a way that makes it shorter and cleaner. Again I am a beginner so any explanation would be much appreciated.
All you have to do to fix your program is remove four spaces:
def valueInput():
print("Please enter 20 random numbers")
values = []
for i in range(20):
value1 =(int(input("Enter a random number " + str(i + 1) + ": ")))
values.append(value1)
return values
The last line in the block above has been unindented by one level. Instead of returning after the first time through the loop, it lets the loop complete, and then returns the resulting list.
Also you can change your:
values = []
for i in range(20):
value1 =(int(input("Enter a random number " + str(i + 1) + ": ")))
values.append(value1)
return values
part with:
values = [int(input("Enter a random number " + str(x + 1) + ": ")) for x in list(range(20))]
return values
You can check out build in functions
I'm new to programming. I have a bit of problem with python coding (with def function).
So basically the code has to give the smaller number out of 2 numbers.
Question:
Write codes to perform the following tasks:
Define a function smaller_num that takes in two numbers to
determine and return the smaller number of the two.
Ask user for two numbers
Use the function to determine the smaller number and display the result
So I had user input instead of calling the function and adding value inside the variable.
This is how my code looks like:
def smaller_num(x,y):
if x>y:
number= y
else:
number= x
return number
smaller_num(x= input("Enter first number:-") ,y= input("Enter second number:-"))
print("The smaller number between " + str(x) + " and " + str(y) + " is " + str(smaller_num))
How do I correct it? For now it's not working because "x" is not defined. But I feel that I defined them clearly both in def function and input function. So how do I fix this?
Thanks for those who respond to this question.
You never actually defined x and y globally. You only defined it in the function when you did def smaller_num(x, y).
When you do smaller_num(x= input("Enter first number:-") ,y= input("Enter second number:-"))
, you aren't creating variables called x and y, you are just creating parameters for your function.
In order to fix your code, create the variable x and y before you call your function:
def smaller_num(x, y): ## Can be rephrased to def smaller_num(x, y):
if x > y: ## if x > y:
number = y ## return y
else: ## else:
number = x ## return x
return number
x = input("Enter first number:-")
y = input("Enter second number:-")
result = smaller_num(x, y)
print("The smaller number between " + str(x) + " and " + str(y) + " is " + str(result))
The other reason your code is not working is because you're not assigning the returned value of the function back into a variable. When you return something from a function, and again when you call the function, you need to assign the value to a variable, like I have: result = smaller_num(x, y).
When you called your function, you never assigned the value to a variable, so it has been wasted.
Also, are you using Python 3 or 2.7? In python 3 using input() will return a string, and to convert this to an integer, you can call int() around the input() function.
This will work:
def smaller_num(x,y):
if x>y:
number= y
else:
number= x
return number
x = input("Enter first number:-")
y = input("Enter second number:-")
smaller = smaller_num(x,y)
print("The smaller number between " + str(x) + " and " + str(y) + " is " + str(smaller))
this should work:
def smaller_num(x,y):
if x>y:
number = y
else:
number = x
return number
x = input("Enter first number:-")
y = input("Enter second number:-")
print("The smaller number between " + str(x) + " and " + str(y) + " is " + str(smaller_num(x,y)))
def smaller_num(x,y):
if x>=y:
number = y
else:
number = x
return number
x = input("Enter first number:-")
y = input("Enter second number:-")
print("The smaller number between " + str(x) + " and " + str(y) + " is " + str(smaller_num(x,y)))
def smaller_num(x,y):
if x>y:
number= y
else:
number= x
return number
k=smaller_num(x= input("Enter first number:-") ,y= input("Enter second number:-"))
print("The smaller number between x & y is ", k)
def smaller_num():
x=int(input('Enter the first number: '))
y=int(input('Enter the second number: '))
if x<y:
return x
else:
return y
print('The smaller number is: ',smaller_num())