473,405 Members | 2,167 Online
Bytes | Software Development & Data Engineering Community
Post Job

Home Posts Topics Members FAQ

Join Bytes to post your question to a community of 473,405 software developers and data experts.

Mapping values to strings using dictionaries [solved]

Hi all, Ive been searching everywhere, and dont understand why there isnt that much infomation on "inputing" answers and having the program evaluate the answer.

So far ive found raw_input, input, and sys.stdout.write(" ") --> sys.stdin.readline() commands. Ive found these work with numbers, but what if the input I put in is text???

Anyway, I want a program that will ask the user a question, and is able to read and evaluate the answer if it consists of letters, or letters and numbers.

Heres a example of what ive been trying:

#part4
#purpose: compute the distance of two planets, ask the user which two planets to compute

import sys

#variables

Earth = 80000
Mars = 500000
Venus = 67000
Sun = 0


sys.stdout.write("Enter the first planet: ")
x = sys.stdin.readline().capitalize()

sys.stdout.write("Enter the second planet: ")
y = sys.stdin.readline().capitalize()

z = abs(x - y)

print "The distance of the two planets are: ", z

Anyway, I am a big beginner of python, and yes this is homework!! However, the example i have up here isnt the real problem, I made it up, any help would be really appreciated!!!
Oct 14 '06 #1
2 1511
bartonc
6,596 Expert 4TB
Wow! You may be a beginner at programming in python, but you post shows a lot of maturity! Here are a couple of things right off the bat:

1) sys.stdout.write("Enter the first planet: ")
is generally equivalent to
print "Enter the first planet: "
so use print because it's easier to read and you can save import sys 'til you really need it.

2) You have done an awesome job of research string "methods" ( in python jargon, just about everything is an object of one "type" or another and methods are the functions that belong to that particulay type of object) as show by your use of:
x = sys.stdin.readline().capitalize()

Here you've asked an str type object to give you a capitalized copy of itself!
You can use:
print type(x)
to prove that you have an str type object.

sys.stdin.readline() and raw_input() both return str type objects.

if you type:
help(str)
you'll get all the methods and attributes of str type objects.
There are other ways, but I use this while I'm writing for quick reminders.

3) Once you have a string with only on word in it (no spaces, etc.), you can use str methods find out what kind of characters are in it:

print "1234".isdigit()
print "abcd".isdigit()
print "1a2b".isalpha()
If input_string.isdigit():
x = int(input_string)
etc.

If your string has spaces in it, you can get a list type object which hold the text between the spaces (list of str type objects) by using:

list_of_words = input_string.split() # There are arguments to split() like "\t", but that comes later.

4) The very cool python structure that you need to use to solve a "lookup" of text mapped to a value is the dictionary!

planet_dist_dict = {"earth":80000, "Mars":500000}

then you can
print planet_dist_dict.get("earth")
print planet_dist_dict.get("foo") # dict.get() handles non-existant items
x = planet_dist_dict["Mars"]
print x

or do things like
if input_string in planet_dist_dict:
# do stuff

5) That last line use more cool python syntax:
Lots of python's types a in a group iterators. Learning about these was key for me. Iterators let you do thing like look through the hole structure as if you had written a loop. That's what in does.

6) Have fun! I am so glad that you get this opertunity in school. Python is my develpment language of choice for very many reasons, but mostly because there is almost never a time when python says "you can't do that".



Hi all, Ive been searching everywhere, and dont understand why there isnt that much infomation on "inputing" answers and having the program evaluate the answer.

So far ive found raw_input, input, and sys.stdout.write(" ") --> sys.stdin.readline() commands. Ive found these work with numbers, but what if the input I put in is text???

Anyway, I want a program that will ask the user a question, and is able to read and evaluate the answer if it consists of letters, or letters and numbers.

Heres a example of what ive been trying:

#part4
#purpose: compute the distance of two planets, ask the user which two planets to compute

import sys

#variables

Earth = 80000
Mars = 500000
Venus = 67000
Sun = 0


sys.stdout.write("Enter the first planet: ")
x = sys.stdin.readline().capitalize()

sys.stdout.write("Enter the second planet: ")
y = sys.stdin.readline().capitalize()

z = abs(x - y)

print "The distance of the two planets are: ", z

Anyway, I am a big beginner of python, and yes this is homework!! However, the example i have up here isnt the real problem, I made it up, any help would be really appreciated!!!
Oct 15 '06 #2
Thanks so much! This helped me alot. :)
Oct 15 '06 #3

This thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

17
by: Gordon Airport | last post by:
Has anyone suggested introducing a mutable string type (yes, of course) and distinguishing them from standard strings by the quote type - single or double? As far as I know ' and " are currently...
7
by: Thomas Philips | last post by:
I want to print "1 spam 4 you" using a formatted string that gets its inputs from the dictionary d={'n1':1, 's1':'spam', 'n2':4}. To do so, I write >>> x="%('n1')d %('s1')s %('n2')d you" >>> x...
0
by: Chris | last post by:
I am using Castor to marshal and unmharshal some objects. I have an object that has a List of strings. I can marshal it without using a mapping file. However, when I try to unmarshal it without...
6
by: naruto | last post by:
Hi all, I have the following being defined in a A.cxx file. // define in source file. Not exported to the outside world (this cannot be // moved to the header file ) #define CHANNEL_0 0...
7
by: ProvoWallis | last post by:
I'm still learning python so this might be a crazy question but I thought I would ask anyway. Can anyone tell me if it is possible to join two dictionaries together to create a new dictionary using...
5
by: A.M | last post by:
Hi, I have a datetime value and want to format it to "June 1, 2006" shape. How can I do that? Thank you,
4
by: kdt | last post by:
Hi Trying to create a function that takes two dictionaries, and deletes key:values that are common in both dictionaries. So far I have the following; but I can only delete values in one dictionary...
5
by: alan | last post by:
Hello world, I'm wondering if it's possible to implement some sort of class/object that can perform mapping from class types to strings? I will know the class type at compile time, like so:...
10
by: ++imanshu | last post by:
Hi, Wouldn't it be nicer to have 'in' return values (or keys) for both arrays and dictionaries. Arrays and Dictionaries looked so similar in Python until I learned this difference. Thanks,...
13
by: sulyokpeti | last post by:
I have made a simple python module to handle SQL databases: https://fedorahosted.org/pySQLFace/wiki Its goal to separate relational database stuff (SQL) from algorythmic code (python). A SQLFace...
0
BarryA
by: BarryA | last post by:
What are the essential steps and strategies outlined in the Data Structures and Algorithms (DSA) roadmap for aspiring data scientists? How can individuals effectively utilize this roadmap to progress...
1
by: nemocccc | last post by:
hello, everyone, I want to develop a software for my android phone for daily needs, any suggestions?
0
by: Hystou | last post by:
There are some requirements for setting up RAID: 1. The motherboard and BIOS support RAID configuration. 2. The motherboard has 2 or more available SATA protocol SSD/HDD slots (including MSATA, M.2...
0
marktang
by: marktang | last post by:
ONU (Optical Network Unit) is one of the key components for providing high-speed Internet services. Its primary function is to act as an endpoint device located at the user's premises. However,...
0
Oralloy
by: Oralloy | last post by:
Hello folks, I am unable to find appropriate documentation on the type promotion of bit-fields when using the generalised comparison operator "<=>". The problem is that using the GNU compilers,...
0
jinu1996
by: jinu1996 | last post by:
In today's digital age, having a compelling online presence is paramount for businesses aiming to thrive in a competitive landscape. At the heart of this digital strategy lies an intricately woven...
0
tracyyun
by: tracyyun | last post by:
Dear forum friends, With the development of smart home technology, a variety of wireless communication protocols have appeared on the market, such as Zigbee, Z-Wave, Wi-Fi, Bluetooth, etc. Each...
0
agi2029
by: agi2029 | last post by:
Let's talk about the concept of autonomous AI software engineers and no-code agents. These AIs are designed to manage the entire lifecycle of a software development project—planning, coding, testing,...
0
isladogs
by: isladogs | last post by:
The next Access Europe User Group meeting will be on Wednesday 1 May 2024 starting at 18:00 UK time (6PM UTC+1) and finishing by 19:30 (7.30PM). In this session, we are pleased to welcome a new...

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.