Home » NO IDEA » string Part 2

string Part 2

Blog Stats

  • 14,863 hits
December 2012
M T W T F S S
« Sep   Jan »
 12
3456789
10111213141516
17181920212223
24252627282930
31  

#string Part 2.py

departement="Somputer science Engineering ";
print departement;
print"Enter the year";
year=input();
print"Enter you favourite topic";
topic=raw_input();
print ( topic + " this is interesting topic!!")
print ("Please give me a number:",)
response = raw_input()

number = int(response)
plusTen = number + 10

print ("If we add 10 to your number, we get " + str(plusTen))

some other string function we are going to see here

  • str(): turns an object into a string
  • int(): turns an object into an integer
print ("Please give me a number: ",)
number = raw_input()

plusTen = number + 10
print ("If we add 10 to your number, we get " + plusTen)

This program should take a number from the user, add 10 to it, and print out the result. But if you try running it, it won’t work! You’ll get an error that looks like this:

Traceback (most recent call last):
  File "test.py", line 7, in <module>
    print "If we add 10 to your number, we get " + plusTen
TypeError: cannot concatenate 'str' and 'int' objects
this is because python understand  the input as string not as a number .I remember one scolding  i got in Facebook” that computer is not a mind reader so you have specify everything what you do “
print ("Please give me a number:",)
response = raw_input()

number = int(response) 
plusTen = number + 10

print ("If we add 10 to your number, we get " + str(plusTen))
Note:
Another way of doing the same is to add a comma after the string part and then the number variable, like this:

print ("If we add 10 to your number, we get ", plusTen)

or use special print formatting like this:

print ("If we add 10 to your number, we get %s" % plusTen)
Advertisements

1 Comment

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: