Variables And Printing in Python
By: Zed A. Shaw
Now we’ll do even more typing of variables and printing them out. This time we’ll use something called a “format
stringâ€. Every time you put " (double-quotes) around a piece of text you have been making a string. A string is how
you make something that your program might give to a human. You print them, save them to files, send them to web
servers, all sorts of things.
Strings are really handy, so in this exercise you will learn how to make strings that have variables embedded in them.
You embed variables inside a string by using specialized format sequences and then putting the variables at the end
with a special syntax that tells Python, “Hey, this is a format string, put these variables in there.â€
As usual, just type this in even if you do not understand it and make it exactly the same.
1 my_name = 'Zed A. Shaw'
2 my_age = 35 # not a lie
3 my_height = 74 # inches
4 my_weight = 180 # lbs
5 my_eyes = 'Blue'
6 my_teeth = 'White'
7 my_hair = 'Brown'
8
9 print "Let's talk about %s." % my_name
10 print "He's %d inches tall." % my_height
11 print "He's %d pounds heavy." % my_weight
12 print "Actually that's not too heavy."
13 print "He's got %s eyes and %s hair." % (my_eyes, my_hair)
14 print "His teeth are usually %s depending on the coffee." % my_teeth
15
16 # this line is tricky, try to get it exactly right
17 print "If I add %d, %d, and %d I get %d." % (
18 my_age, my_height, my_weight, my_age + my_height + my_weight)
What You Should See
$ python ex5.py
Let's talk about Zed A. Shaw.
He's 74 inches tall.
He's 180 pounds heavy.
Actually that's not too heavy.
He's got Blue eyes and Brown hair.
His teeth are usually White depending on the coffee.
If I add 35, 74, and 180 I get 289.
$
Archived Comments
Comment on this tutorial
- Data Science
- Android
- AJAX
- ASP.net
- C
- C++
- C#
- Cocoa
- Cloud Computing
- HTML5
- Java
- Javascript
- JSF
- JSP
- J2ME
- Java Beans
- EJB
- JDBC
- Linux
- Mac OS X
- iPhone
- MySQL
- Office 365
- Perl
- PHP
- Python
- Ruby
- VB.net
- Hibernate
- Struts
- SAP
- Trends
- Tech Reviews
- WebServices
- XML
- Certification
- Interview
categories
Related Tutorials
How to install Jupyter in Ubuntu and make it accessible through Apache Reverse Proxy
Python Basics - Setting up your Python Development Environment
Schwartzian Transform in python
Multidimensional list (array) in python
Remove duplicates from a list in python
Convert number to string in python
Perl's chomp() equivalent for removing trailing newlines from strings in python