Thread: Starting Python
View Single Post
Join Date: Oct 2004
Posts: 3,862
Reputation: vegaseat is just really nice vegaseat is just really nice vegaseat is just really nice vegaseat is just really nice vegaseat is just really nice 
Solved Threads: 870
Moderator
vegaseat's Avatar
vegaseat vegaseat is offline Offline
DaniWeb's Hypocrite

Re: Starting Python

 
0
  #9
Mar 30th, 2005
To get string input from the user you can use the raw_input() function with Python2 and the input() function with Python3. .

Here is an example of an input loop that checks the data you enter. The function get_list(prompt) is generic and can be used whenever you want to enter a series of numbers (accepts integer or float). It returns a list of the entered numbers. It's up to you to process the list of numbers ...
  1. print "The grade point average (GPA) calculator:"
  2.  
  3. def get_list(prompt):
  4. """
  5. loops until acceptable data or q (quit) is given
  6. returns a list of the entered data
  7. """
  8. data_list = []
  9. while True:
  10. sin = raw_input(prompt) # input(prompt) in Python3
  11. if sin == 'q':
  12. return data_list
  13. try:
  14. data = float(sin)
  15. data_list.append(data)
  16. except ValueError:
  17. print( "Enter numeric data!" )
  18.  
  19. print('')
  20. gp_list = get_list("Enter grade point (q to quit): ")
  21. print( gp_list ) # test
  22. # process the list ...
  23. # calculate the average (sum of items divided by total items)
  24. gpa = sum(gp_list)/len(gp_list)
  25.  
  26. print( "The grade point average is:", gpa )
Since Python2's raw_input() will not work with Python3, you can use try/except to make your program work with both versions ...
  1. # use module datetime to show age in days
  2. # modified to work with Python2 and Python3
  3.  
  4. import datetime as dt
  5.  
  6. prompt = "Enter your birthday (format = mm/dd/yyyy): "
  7. try:
  8. # Python2
  9. bd = raw_input(prompt)
  10. except NameError:
  11. # Python3
  12. bd = input(prompt)
  13.  
  14. # split the bd string into month, day, year
  15. month, day, year = bd.split("/")
  16.  
  17. # convert to format datetime.date(year, month, day))
  18. birthday = dt.date(int(year), int(month), int(day))
  19.  
  20. # get todays date
  21. today = dt.date.today()
  22.  
  23. # calculate age since birth
  24. age = (today - birthday)
  25.  
  26. print( "You are %d days old!" % age.days )
Click on "Toggle Plain Text" so you can highlight and copy the code to your editor.
Last edited by vegaseat; Aug 29th, 2009 at 5:11 pm. Reason: code=python tag remark, Python3 update
May 'the Google' be with you!
Reply With Quote