Strings in python - python

I want to write a program to display birth date using strings. Please check the code:
dob = int(input("enter your birth day"))
if dob > 31 or dob < 1:
print("invalid")
mob = int(input("enter your birth month"))
if mob > 12 or mob < 1:
print("invalid")
yob = int(input("enter your birth year"))
date = [dob, mob, yob]
bday = "Your birthday is on: {0}/{1}/{2}".format(date[0], date[1], date[2])
print(bday)
Output:
I want to make this program in a way that a valid date can be printed eg:
32/23/2020 is invalid and therefore must not be printed.

You can do
while True:
dob = int(input("enter your birth day"))
if not 1 <= dob <= 31:
print("invalid")
continue
break
while True:
mob = int(input("enter your birth month"))
if not 1 <= mob <= 12:
print("invalid")
continue
break
yob = int(input("enter your birth year"))
date = [dob, mob, yob]
bday = "Your birthday is on: {0}/{1}/{2}".format(date[0], date[1], date[2])
print(bday)
This code will ask for day and month until they will be valid and then insert the year and you will get the print statement to print validate date.

Try to understand it, it's simple:
dob = int(input("enter your birth day"))
if dob not in range(1,32):
print("invalid")
mob = int(input("enter your birth month"))
if mob not in range(1,13) :
print("invalid")
yob = int(input("enter your birth year"))
if yob not in range(1900,2021):
print("invalid")
date = [dob, mob, yob]
bday = "Your birthday is on: {0}/{1}/{2}".format(date[0], date[1], date[2])
print(bday)

You have to use or operator, your value will never be greater than 31 and lower than 1 at the same time
if dob > 31 or dob < 1
print("Invalid")
Also you may want to ask again until the value is valid, not just telling the use, use a while loop for that
dob = 0
while dob > 31 or dob < 1:
dob = int(input("enter your birth day: "))
mob = 0
while mob > 12 or mob < 1:
mob = int(input("enter your birth month: "))
yob = int(input("enter your birth year: "))
date = [dob, mob, yob]
bday = "Your birthday is on: {0}/{1}/{2}".format(*date) # * operator is for unpacking the list
print(bday)
Demo
enter your birth day: 32
enter your birth day: 35
enter your birth day: 15
enter your birth month: 55
enter your birth month: 20
enter your birth month: 10
enter your birth year: 1950
Your birthday is on: 15/10/1950

Related

How to calculate sum of numbers in a list?

I am trying to write a program in which the user enters the age of 8 guests. Each guest's age is priced differently. How can I add each cost together to come up with the total cost for each guest? This is what I have written.
def main():
guest1= int(input("Enter the age of guest 1(in years): "))
guest2 = int(input("Enter the age of guest 2(in years): "))
guest3 = int(input("Enter the age of guest 3(in years): "))
guest4 = int(input("Enter the age of guest 4(in years): "))
guest5 = int(input("Enter the age of guest 5(in years): "))
guest6 = int(input("Enter the age of guest 6(in years): "))
guest7 = int(input("Enter the age of guest 7(in years): "))
guest8 = int(input("Enter the age of guest 8(in years): "))
ages = [guest1, guest2, guest3, guest4, guest5, guest6, guest7, guest8]
getCost(ages)
def getCost(ages):
for age in ages:
if age <=2:
cost = 0
print(cost)
elif age <= 3>12:
cost = 14
print(cost)
elif age >= 65:
cost = 18
print(cost)
else:
cost = 23
print(cost)
main()
You can put all the ages into a list up front by calling input() in a loop instead of copying and pasting it eight times:
ages = [int(input(f"Enter the age of guest {i}(in years): ")) for i in range(1, 9)]
I'd suggest having your getCost function just return the cost for a single age (hint: make this simpler by arranging the age brackets in ascending order, and eliminating them one at a time according to their upper bound):
def getCost(age):
if age < 3:
return 0
elif age < 12:
return 14
elif age < 65:
return 23
else:
return 18
This makes the job of getCost much easier -- then after you've gotten ages you can compute the total cost just by calling getCost(age) for each age and taking the sum of the result:
print(sum(getCost(age) for age in ages))
Splitting the logic into parts like this makes it easy to do other things with the costs; for example, you could show how the total was computed by joining the costs before you sum them:
print(
" + ".join(str(getCost(age)) for age in ages),
"=",
sum(getCost(age) for age in ages)
)
Enter the age of guest 1(in years): 2
Enter the age of guest 2(in years): 9
Enter the age of guest 3(in years): 13
Enter the age of guest 4(in years): 27
Enter the age of guest 5(in years): 44
Enter the age of guest 6(in years): 52
Enter the age of guest 7(in years): 66
Enter the age of guest 8(in years): 81
0 + 14 + 23 + 23 + 23 + 23 + 18 + 18 = 142
You can start by defining a totalCost variable, as a running total that you can keep incrementing after you calculate the cost for each customer. For instance:
def getCost(ages):
totalCost = 0
for age in ages:
if age <=2:
cost = 0
elif age >= 3 and age < 12:
cost = 14
elif age >= 65:
cost = 18
else:
cost = 23
totalCost += cost
return totalCost
Do note that I've assumed age <= 3>12 refers to ages between 3 and 11, inclusive.
It seems that you use function getCost to calculate each cost. A little bit modification of adding a variable to sum up all values will help you get what you want.
def sumCost(ages):
total = 0
for age in ages:
if age <=2:
cost = 0
elif age <= 3>12: # your original code may have some problems here. I just keep it.
cost = 14
elif age >= 65:
cost = 18
else:
cost = 23
total = total + cost
return total
Or you can construct a list of cost then use sum.
def sumCost(ages):
costs = []
for age in ages:
if age <=2:
cost = 0
elif age <= 3>12: # your original code may have some problems here. I just keep it.
cost = 14
elif age >= 65:
cost = 18
else:
cost = 23
costs.append(cost)
total = sum(costs)
return total

Python: How do I find age from an inputted date of birth and current date?

I have made a programme where the user it asked to input their date of birth as integers and then I've tried to convert the date of birth to a format to then compare to the current date which is imported. However I'm struggling to identify the different formats of date that can be used in python.
Here is my code:
from datetime import datetime
print("This programme calculates your age from your date of birth")
dd=int(input("What day were you born? "))
mm=int(input("What month were you born, enter the month number:" ))
yyyy=int(input("What year were you born? Enter the full year: "))
today = datetime.today()
b1 = dd,mm,yyyy
newdate1 = datetime.strptime(b1, "%d/%m/%Y")
age = today.year - b1.year - ((today.month, today.day) < (b1.month, b1.day))
print(age)
import datetime
#asking the user to input their birthdate
birthDate = input("Enter your birth date (dd/mm/yyyy)\n>>> ")
birthDate = datetime.datetime.strptime(birthDate, "%d/%m/%Y").date()
print("Your birthday is on "+ birthDate.strftime("%d") + " of " +
birthDate.strftime("%B, %Y"))
currentDate = datetime.datetime.today().date()
#some calculations here
age = currentDate.year - birthDate.year
monthVeri = currentDate.month - birthDate.month
dateVeri = currentDate.day - birthDate.day
#Type conversion here
age = int(age)
monthVeri = int(monthVeri)
dateVeri = int(dateVeri)
# some decisions
if monthVeri < 0 :
age = age-1
elif dateVeri < 0 and monthVeri == 0:
age = age-1
#lets print the age now
print("Your age is {0:d}".format(age))

Admission Price based on age and coupons

Im attempting to write a code where the user if prompted for todays date and their birthdate in order to determine their age. The age will determine how much their ticket price will be. If they are 14 and younger the price would be five dollars. If they are 15 to 64 the price would be nine dollars and if they are 65 and older the price would be 7.50. It would ask if the customer has a coupon, which would take off one dollar off their price. What I have so far:
print ("Hello, welcome to Hopper's Computer Museum! To determine your enterance fee, please enter the following:")
print ('Your Date of Birth (mm dd yyyy)')
Date_of_Birth = input("--->")
print ('Todays Date: (mm dd yyyy)')
Todays_Date = input("--->")
age = (tYear-bYear)
if (bMonth > tMonth):
age == age-1
if (bMonth == tMonth and
bDay > tDay):
age == age-1
if age < 14:
price==5.00
elif age > 15 and age < 64:
price==9.00
elif age > 65:
price==7.50
print ('Do you have a coupon (y/n)?')
Discount = input("--->")
if Discount == "y" or Discount == "Y":
price = price-1
elif Discount == "n" or Discount == "N":
price = price
print ('Your admission fee is $4.00 enjoy your visit!')
I know that I need define my variables such as tYear, bYear, bDay, ect, but I'm not sure what I should assign them to.
You can use map to assign values to tYear, bYear etc. You can do following instead of Date_of_birth = input('--->')
bDay,bMonth,bYear = map(int,raw_input('--->').split())
This will assign bDay, bMonth and bYear as per requirement if the input format is 'dd mm yyyy'. Similarly for today's date you can write:
tDay,tMonth,tYear = map(int,raw_input('--->').split())
Alternate option is to calculate age using datetime. Follow this - Age from birthdate in python

An error appears saying a function was referenced before it was assigned but only when I enter the year above 2005 or 2004

x = 2
while x>1:
from random import randint
import time
fn = input("Hello, what is your first name?")
while any (ltr.isdigit() for ltr in fn):
fn = input("Sorry an integer was entered, please try again")
firstname = (fn[0].upper())
ln = input("Hello, what is your last name?")
while any (ltr.isdigit() for ltr in ln):
ln = input("Sorry an integer was entered, please try again")
lastname = (ln.lower())
def main():
dob = input("Please enter the year you were born")
if dob > ("2005"):
main()
elif dob < ("2004"):
main()
else:
def mob():
if dob == ("2005"):
age = 11
elif dob == ("2004"):
month = input("Please enter the first three letters of the month you were born")
while month not in ("Jan","JAN","jan","Feb","FEB","feb","Mar","MAR","mar","Apr","APR","apr","May","MAY","may","Jun","JUN","jun","Jul","JUL","jul","Aug","AUG","aug","Sep","SEP","sep","Oct","OCT","oct","Nov","NOV","nov","Dec","DEC","dec"):
month = input("Sorry that was incorrect, please enter the first three letters of the month you were born")
if month in ("Jan","JAN","jan","Feb","FEB","feb","Mar","MAR","mar","Apr","APR","apr","May","MAY","may","Jun","JUN","jun","Jul","JUL","jul"):
age = 12
elif month in ("Aug","AUG","aug"):
day = input("Please input the day you were born")
while day not in("31","30","29","28","27","26","25","24","23","22","21","20","19","18","17","16","15","14","13","12","11","10","9","8","7","6","5","4","3","2","1"):
day = input("Please input the day you were born")
if day == ("28","27","26","25","24","23","22","21","20","19","18","17","16","15","14","13","12","11","10","9","8","7","6","5","4","3","2","1"):
age = 12
elif day in ("29","30","31"):
age = 11
else:
age = 12
else:
age = 11
else:
age = 11
usernames = []
age = int(age)
age2 = age + randint(1,9)
age2 = str(age2)
print("Thank you for taking the time to enter your details, your username is now being generated")
time.sleep(1)
print("Generating...")
time.sleep(2)
username = (dob[2]+''+dob[3]+''+firstname+''+lastname+''+age2)
print("This is your username:" +''+username)
usernames.append(username)
age = str(age)
with open("Import Usernames.txt", "w") as text_file:
print("The usernames are: {}".format(usernames), file=text_file)
mob()
main()
An error only appears when I enter a year higher than 2005 or lower than 2004 but I don't know why, my question is, what have I done wrong?
This is the error that pops up:
UnboundLocalError: local variable 'mob' referenced before assignment
This whole programs is structured wrong...
Anyway, mob is declared only inside the else scope and is called right after the if-elif-else statements.
You should declare it in each these scopes, or right before them.
Beside that, I really suggest you read about Python identation.

TypeError: data() missing 4 required positional arguments: 'n', 'p', 'gn', and 's'

I have this assignment for school work, this is pretty basic stuff i gather but I'm new to this language so I'm still a little nooby. I get the aforementioned error upon testing each module with the error being specific to this line and this line alone.
def data(n, p, gn, s):
name[x] = input("Please enter the customer's name.")
n.append(name[x])
phone = int(input("Please enter the customer's Phone Number."))
if len.str(phone[x]) == 11:
p.append(attendance[x])
else : phone[x] = int(input("Please enter the customer's Phone Number."))
if len.str(phone[x]) == 11:
p.append(attendance[x])
groupno[x] = int(input("Please enter the number of diners in the group - length must be 11 characters."))
if 1 >= groupno[x] <=20:
gn.append(groupno[x])
else: groupno[x] = int(input("Please enter the number of diners in the group - between 1 & 20."))
gn.append(groupno[x])
score[x] = int(input("Please enter the rating of the meal."))
if 1 >= score[x] <=3:
s.append(score[x])
else: score[x] = int(input("Please enter the rating of the meal - between 1 & 10."))
if 1 >= score[x] <=3:
s.append(score[x])
data()
It looks like you are trying to store information about multiple customers, I suggest you use a dictionary instead:
def data():
name = input("Please enter the customer's name.")
temp_phone = int(input("Please enter the customer's Phone Number."))
while len.str(temp_phone) != 11:
temp_phone = int(input("Please enter the customer's Phone Number."))
phone = temp_phone
temp_groupno = int(input("Please enter the number of diners in the group (maximum 20 diners)"))
while not (1 <= groupno <=20):
temp_groupno = int(input("Please enter the number of diners in the group (maximum 20)"))
group = temp_groupno
temp_score = int(input("Please enter the rating of the meal (between 1 and 10)"))
while not (1 <= temp_score <= 3):
temp_score = int(input("Please enter the rating of the meal - between 1 & 10."))
score = temp_score
return {'name': name, 'phone': phone, 'group': group, 'score': score}
customers = []
customers.append(data())
customers.append(data())
print(customers)
Your function require 4 parameters and you have given it none.
When you define a function like so: def foo(a,b,c,d), you need to supply it with a,b,c and d.
name[x] = input("Please enter the customer's name.")
n.append(name[x])
This will also give you an error as x is undefined.

Categories