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 ...
print "The grade point average (GPA) calculator:"
def get_list(prompt):
"""
loops until acceptable data or q (quit) is given
returns a list of the entered data
"""
data_list = []
while True:
sin = raw_input(prompt) # input(prompt) in Python3
if sin == 'q':
return data_list
try:
data = float(sin)
data_list.append(data)
except ValueError:
print( "Enter numeric data!" )
print('')
gp_list = get_list("Enter grade point (q to quit): ")
print( gp_list ) # test
# process the list ...
# calculate the average (sum of items divided by total items)
gpa = sum(gp_list)/len(gp_list)
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 ...
# use module datetime to show age in days
# modified to work with Python2 and Python3
import datetime as dt
prompt = "Enter your birthday (format = mm/dd/yyyy): "
try:
# Python2
bd = raw_input(prompt)
except NameError:
# Python3
bd = input(prompt)
# split the bd string into month, day, year
month, day, year = bd.split("/")
# convert to format datetime.date(year, month, day))
birthday = dt.date(int(year), int(month), int(day))
# get todays date
today = dt.date.today()
# calculate age since birth
age = (today - birthday)
print( "You are %d days old!" % age.days )
Click on "Toggle Plain Text" so you can highlight and copy the code to your editor.
A note on importing modules:
Python is a modular language and comes with many thoroughly tested and optimized modules. To code in Python means you have to use those modules to your advantage. Python syntax may be easy, but remembering all those modules may use all the power of your brain!
Last edited by vegaseat; 13 Days Ago at 11:04 am. Reason: code=python tag remark, Python3 update
May 'the Google' be with you!