turning variables that use 'str()' into numbers - python

I'm trying to apply the math.floor function to a some variables that use the str() function... what is the proper way to do this?
Here's my code:
import math
x = str(10.3)
y = str(22)
z = str(2020)
print "x equals " + x
print "y equals " + y
print "z equals " + z
#playing around with the math module here. The confusion begins...
#how do I turn my str() functions back into integers and apply the floor function of the math module?
xfloor = math.floor(x)
zsqrt = math.sqrt(z)
print "When we print the variable \"xfloor\" it rounds " + x + "down into " + xfloor + "."
print "When we print the variable \"zsqrt\" it finds the sqareroot of " + z + "which is " + zsqrt + "."
raw_input("Press the enter key to continue.")
Any and all assistance is welcome.

Cast them back :
xfloor = math.floor(float(x))
zsqrt = math.sqrt(float(z))
But this is not a recommended practice as you are converting it to str unnecessarily. To print use str.format
print "x equals {}".format(x)
For this you do not need to cast to str.

Related

How to separate strings multiplied by integer in Python?

Let's say we have a text "Welcome to India". And I want to multiply this string with 3, but to appear with comma delimitation, like "Welcome to India, Welcome to India, Welcome to India". The thing is I know this piece of code could work:
a = 'Welcome to India'
required = a * 3 # but this code is not comma-delimited.
Also, this piece of code doesn't work as well
required = (a + ", ") * 3 # because it puts comma even at the end of the string
How to solve this problem?
", ".join(["Welcome to India"]*3)
Based on the part of your code that you say doesn't work well because it adds a comma to the end, you can modify it like this:
required = (a + ", ") * 2 + a
Or if you don't like it, you can use sum instead of multiply, it's not the optimal way, for sure, but it will work:
a = 'Welcome to India'
required = a + ", " + a + ", " + a
Define Function and you can use it.
def commaFunc(value, count):
buffer = []
for x in range(count):
buffer[x] = value
return ",".join(buffer)

putting str and int together 4 times not working [duplicate]

This question already has an answer here:
How can I concatenate str and int objects?
(1 answer)
Closed 4 years ago.
I have this python program that adds strings to integers:
a = raw_input("Enter a: ")
b = raw_input("Enter b: ")
print "a + b as strings: " + a + b
a = int(a)
b = int(b)
c = a + b
str(c)
print "a + b as integers: " + c
I get this error:
TypeError: cannot concatenate 'str' and 'int' objects
How can I add strings to integers?
There are two ways to fix the problem which is caused by the last print statement.
You can assign the result of the str(c) call to c as correctly shown by #jamylak and then concatenate all of the strings, or you can replace the last print simply with this:
print "a + b as integers: ", c # note the comma here
in which case
str(c)
isn't necessary and can be deleted.
Output of sample run:
Enter a: 3
Enter b: 7
a + b as strings: 37
a + b as integers: 10
with:
a = raw_input("Enter a: ")
b = raw_input("Enter b: ")
print "a + b as strings: " + a + b # + everywhere is ok since all are strings
a = int(a)
b = int(b)
c = a + b
print "a + b as integers: ", c
str(c) returns a new string representation of c, and does not mutate c itself.
c = str(c)
is probably what you are looking for
If you want to concatenate int or floats to a string you must use this:
i = 123
a = "foobar"
s = a + str(i)
c = a + b
str(c)
Actually, in this last line you are not changing the type of the variable c. If you do
c_str=str(c)
print "a + b as integers: " + c_str
it should work.
Apart from other answers, one could also use format()
print("a + b as integers: {}".format(c))
For example -
hours = 13
minutes = 32
print("Time elapsed - {} hours and {} minutes".format(hours, minutes))
will result in output - Time elapsed - 13 hours and 32 minutes
Check out docs for more information.
You can convert int into str using string function:
user = "mohan"
line = str(50)
print(user + "typed" + line + "lines")
The easiest and least confusing solution:
a = raw_input("Enter a: ")
b = raw_input("Enter b: ")
print "a + b as strings: %s" % a + b
a = int(a)
b = int(b)
c = a + b
print "a + b as integers: %d" % c
I found this on http://freecodeszone.blogspot.com/
I also had the error message "TypeError: cannot concatenate 'str' and 'int' objects". It turns out that I only just forgot to add str() around a variable when printing it. Here is my code:
def main():
rolling = True; import random
while rolling:
roll = input("ENTER = roll; Q = quit ")
if roll.lower() != 'q':
num = (random.randint(1,6))
print("----------------------"); print("you rolled " + str(num))
else:
rolling = False
main()
I know, it was a stupid mistake but for beginners who are very new to python such as myself, it happens.
This is what i have done to get rid of this error separating variable with "," helped me.
# Applying BODMAS
arg3 = int((2 + 3) * 45 / - 2)
arg4 = "Value "
print arg4, "is", arg3
Here is the output
Value is -113
(program exited with code: 0)

How to fix TypeError: input expected at most 1 arguments but got 3

The following code raises TypeError: input expected at most 1 arguments but got 3. I am unsure how to fix this.
def leg_count(w):
x = input("How many legs does a", w, "have? ")
print("A", w, "has", x, "legs")
leg_count("crocodile")
The function input takes a single argument. It cannot be used the same way as print which will take and print multiple arguments. You will need to use str.format to do what you want.
def leg_count(w):
x = input("How many legs does a {} have? ".format(w))
print("A", w, "has", x, "legs")
def leg_count(w):
x = input("How many legs does a " + w + " have ?: ")
print ("A " + w + " has " + str(x) + " legs")
leg_count("crocodile")
if you look input documentation :
input has an optional parameter, which is the prompt string. So you need to pass as a string.

Python unexpected EOF while parsing : syntax error

I am trying to do a simple toto history with a dictionary and function however I have this funny syntax error that keeps appearing that states "unexpected EOF while parsing" on the python shell when I try to runs it. I re-looked over and over however I cannot find the error. I used input for input of integers therefore I do not think that the problem might lie with the input or raw_input. Please help me ! Below are my codes and the error on the python shell.
options()
choice = input ("Enter your choice: ")
print
while choice != -1:
if choice == 1:
print("Choice 1")
for key in toto_book:
print key + "\t" + "Day: " + toto_book[key][0] + '\t' + 'Winning Numbers: ' + str(toto_book[key][1] + 'Additional Number: ' + toto_book[key][2]
elif choice == 2:
print("Choice 2")
draw = raw_input("Enter draw date(dd/mm/yy): ")
if draw in toto_book:
print (draw + "\t" + "Day: " + toto_book[draw][0] + "\t" + "Winning Numbers: " + str(toto_book[draw][1]) + 'Additional Number: ' + toto_book[draw][2])
else:
print draw + ' cannot be found.'
There is a syntax error at the elif choice == 2: line.
Updated
As pointed out by #cricket_007, this answer is based on the false assumption that Python 3 is being used. Actually, Python 2 is being used and the only serious problem is that the call to str is missing a closing parenthesis.
You are using Python 3 in which print is a function, not a statement (as it is in Python 2).
This is the line causing the problem:
print key + "\t" + "Day: " + toto_book[key][0] + '\t' + 'Winning Numbers: ' + str(toto_book[key][1] + 'Additional Number: ' + toto_book[key][2]
Add parentheses to make print a function call, i.e. print(...):
print(key + "\t" + "Day: " + toto_book[key][0] + '\t' + 'Winning Numbers: ' + str(toto_book[key][1]) + 'Additional Number: ' + toto_book[key][2])
Also, the call to str() was missing the closing parenthesis.
There is a similar problem on line 15.
Other problems:
input() returns a string, not an integer so your if choice ==
statements will never be true. Either convert choice to an integer
with choice = int(choice) after the input(), or use a string in
the if statements, e.g. if choice == '1'.
The while loop is infinte, and unnecessary for the code shown (perhaps it is a work in progress?).

concatenation of strings and variables

What I need is for it to print "the sum of 1 and 2 is 3". I'm not sure how to add a and b because I either get an error or it says "the sum of a and b is sum".
def sumDescription (a,b):
sum = a + b
return "the sum of" + a " and" + b + "is" sum
You cannot concat ints to a string, use str.format and just pass in the parameters a,b and use a+b to get the sum:
def sumDescription (a,b):
return "the sum of {} and {} is {}".format(a,b, a+b)
sum is also a builtin function so best to avoid using it as a variable name.
If you were going to concatenate, you would need to cast to str:
def sumDescription (a,b):
sm = a + b
return "the sum of " + str(a) + " and " + str(b) + " is " + str(sm)
Use string interpolation, like this. Python will internally convert the numbers to strings.
def sumDescription(a,b):
s = a + b
d = "the sum of %s and %s is %s" % (a,b,s)
You are trying to concatenate string and int.
You must turn that int to string before hand.
def sumDescription (a,b):
sum = a + b
return "the sum of " + str(a) + " and " + str(b) + " is " + str(sum)

Categories