How do I find the len() of multiple strings? - python

I need to find the len() of multiple strings.
current_year = input ("What year is it?")
current_year = int(current_year)
birth_year = input ("What year were you born in?")
birth_year = str(birth_year)
if len(birth_year) != 4:
print ("Please make your year of birth 4 digits long.")
else:
birth_year = int(birth_year)
print("You are " + str(current_year - birth_year) + " years old.")
I would like to include the len() of birth_year.

Use an elif statement to check the current year input.
current_year = input ("What year is it?")
birth_year = input ("What year were you born in?")
if len(birth_year) != 4:
print ("Please make your year of birth 4 digits long.")
elif len(current_year) != 4:
print ("Please make the current year 4 digits long.")
else:
birth_year = int(birth_year)
current_year = int(current_year)
print("You are " + str(current_year - birth_year) + " years old.")
There's no need for birth_year = str(birth_year), since input() always returns a string.
You should probably include try/except code around the calls to int(), so you can print an error if they enter a year that isn't actually a number.

Here is a way to get what you want that is somewhat more dynamic. With this basic function, if a user inputs an inappropriate string, they will be asked to retry. You could even add a line to check if the year was after the current year.
Note that there is a loop in here with an exit that doesn't have a constraint. If you were going to implement this, I'd add a counter as well which would kill the process to prevent infinite loops.
def get_year(input_string):
# Set loop control Variable
err = True
# while loop control variable = true
while err == True:
# get input
input_year = input(input_string + ' ')
# Ensure format is correct
try:
# Check length
if len(input_year) == 4:
# Check Data type
input_year = int(input_year)
# if everything works, exit loop by changing variable
err = False
# if there was an error, re-enter the loop
except:
pass
# return integer version of input for math
return input_year
# set variables = function output
birth_year = get_year('What year were you born? Please use a YYYY format!\n')
current_year = get_year('What is the current year? Please use a YYYY format!\n')
# print output displaying age
print("You are " + str(current_year - birth_year) + " years old.")

Related

How would I make an infinite loop in Python until a user inputs otherwise?

To clarify, this is similar to another question but I feel the answer is easier to understand.
I am making a very simple program for saying what year you will turn "x" years old. (It's a practice from Practice Python... Starting to relearn Python after a while) I would like the program to ask the user what age they want to know, and it does so. This works fine, but I do not remember how to have it keep asking until they write "n" and otherwise keep asking. Any ideas?
Thanks for the help! Code Below:
I've tried using a Java-esque loop, but this isn't Java, and I don't know what I'm doing. Up to any ideas.
# Libraries
import time
# Initial Code
name = input("What's your name? ")
print("Thank you " + name + "!")
age = int(input("How old are you? "))
year = int(input("Now, just for clarification, what year is it? "))
new_age = input("Now enter what age you would like to know! ")
print("Thank you! Now, I'll tell you the year you will turn " +new_age+ "!")
time.sleep(3)
print("Great, that calculation will only take a second or so!")
time.sleep(1.5)
math_year = year - age
answer = int(math_year) + int(new_age)
print(name + ", you will turn " + str(new_age) + " years old in " + str(answer) +"!")
time.sleep(3)
# Loop Code
again = input("Would you like to know another age? Y/n ")
if again == 'Y':
new_age = input("Awesome! What age would you like to know? ")
print("Great, that calculation will only take a second or so!")
time.sleep(1.5)
math_year = year - age
answer = int(math_year) + int(new_age)
print(name + ", you will turn " + str(new_age) + " years old in " + str(answer) +"!")
All results work, it just can't loop after the second time.
You can use while instead of if. Whereas if executes its block of code once, while will execute it again and again until the condition becomes false.
# Loop Code
again = 'Y'
while again == 'Y':
new_age = input("Awesome! What age would you like to know? ")
print("Great, that calculation will only take a second or so!")
time.sleep(1.5)
math_year = year - age
answer = int(math_year) + int(new_age)
print(name + ", you will turn " + str(new_age) + " years old in " + str(answer) +"!")
again = input("Would you like to know another age? Y/n ")
As of python 3.8 (so, sometime after late October this year), you'll be able to use the assignment operator := to take care of those first two lines at once:
# Loop Code
while (again := 'Y'):
...
again = input("Would you like to know another age? Y/n ")
hello try something like
while True:
"""
your code
"""
answer = input("again"?)
if answer == 'Y':
continue
elif answer == 'N':
break
else:
# handle other input as you want to
pass

how to print string variable in python

name = input("What is your name: ")
age = int(input("How old are you: "))
year = str((2014 - age)+100)
print(name + " will be 100 years old in the year " + year)
I am trying this code in python, but it is not executing, what corrections needs to be done?
From your question
name = input("What is your name: ")
age = int(input("How old are you: "))
year = str((2014 - age)+100)
print(name + " will be 100 years old in the year " + year)
Your code is just fine, change your input to raw_input for name variable.
NOTE: raw_input returns a string, input tries to run as Python expression.

How do I change my list element types from 'NoneType' to just Integers? [duplicate]

This question already has answers here:
Why do these list operations (methods: clear / extend / reverse / append / sort / remove) return None, rather than the resulting list?
(6 answers)
Closed 5 months ago.
The following here is my code and the section where there is the issue I'm encountering is on line 19.
#Check It Out Python 3.5.2 program
import datetime
import CheckItOutprogram
counter = 1
currentYear = datetime.date.today().year
currentMonth = datetime.date.today().month
dayOfMonth = datetime.date.today().day
name = input("Please input your name: ")
postCode = input("Please enter your postcode: ")
expiryYear = int(input("Please enter the year your card expires: "))
expiryMonth = int(input("Please enter the month your card expires: "))
expiryDay = int(input("Please enter the day of the month your card expires: "))
cardNo = input("Please enter your card number: ")
checkDigit = int(cardNo[7]) / 10
cardNo = list(cardNo)
cardNo = cardNo.reverse()
cardNoOdd = int(cardNo[0]) + int(cardNo[2]) + int(cardNo[4]) + int(cardNo[6])
#The three following IF statements check the expiry date.
if expiryYear > currentYear:
print("I'm sorry, your card has expired.")
again = input("Would you like to start again? Press enter to exit or type anything to start again: ")
if again != "":
exit()
else:
CheckItOutprogram.start()
if (expiryMonth >= currentMonth) and (expiryDay > dayOfMonth):
print("I'm sorry, your card has expired.")
again = input("Would you like to start again? Press enter to exit or type anything to start again: ")
if again != "":
exit()
else:
CheckItOutprogram.start()
if (expiryYear != isinstance(expiryYear, int)) or (expiryMonth != isinstance(expiryMonth, int)) or (expiryDay != isinstance(expiryDay, int)):
print("I'm sorry, your card has expired.")
again = input("Would you like to start again? Press enter to exit or type anything to start again: ")
if again != "":
exit()
else:
CheckItOutprogram.start()
#This IF statement checks the amount of characters the card number contains and makes sure that it has 8 elements.
if (len(cardNo) > 8) or (len(cardNo) * 8):
print("Please try again...\n")
CheckItOutprogram.start()
#This checks if the card is avaliable for a 10% discount using the last number.
if checkDigit == isinstance(checkDigit, int):
print("This card is valid! This means that you may have a 10% discount off everything!")
print("Here are the customer and loyalty card details. Name: " + name + ". Post Code: " + postCode + ". Expiry Date: " + str(expiryDay) + "/" + str(expiryMonth) + "/" + str(expiryYear) + ". Card Number: " + cardNo)
else:
print("I'm sorry, your card isn't qualified for a 10% discount.")
again = input("Would you like to start again? Press enter to exit or type anything to start again: ")
if again != "":
exit()
Is there any way to change the list type from 'NoneType' to an Integer because I'm getting a frustrating error saying the following:
Traceback (most recent call last):
File "Z:\Computer Science\Check It Out program\CheckItOutprogram.py", line 3, in <module>
import CheckItOutprogram
File "Z:\Computer Science\Check It Out program\CheckItOutprogram.py", line 20, in <module>
cardNoOdd = int(cardNo[0]) + int(cardNo[2]) + int(cardNo[4]) + int(cardNo[6])
TypeError: 'NoneType' object is not subscriptable
Is it possible to receive any extra information on how to improve my code, in what way as well as how to convert the 'cardNo' list from a 'NoneType' to something that IS subscriptable because I have tried everything possible. Also, if there is any room for feedback to improve the code efficiency, that would be very favourable.
Thanks in advance!
I got a result with the addition doing the following:
cardNo = str(input("Please enter your card number: "))
cardNo = list(cardNo)
cardNo = cardNo[::-1]
print(cardNo)
cardNoOdd = int(cardNo[0]) + int(cardNo[2]) + int(cardNo[4]) + int(cardNo[6])
print(cardNoOdd)
my input: Please enter your card number: 1548315414
out: ['4', '1', '4', '5', '1', '3', '8', '4', '5', '1']
out: 17
edit (sorry, forgot to explain): I did not use reverse itself, but I used indexing to reverse the list. Additionally, I defined the input as a string.
Hope this is what you were looking for!

How can I make a loop in order to ask the user a number when he enter a text for his age [duplicate]

This question already has answers here:
Python check for integer input
(3 answers)
Closed 5 years ago.
I am trying to do a program that asks the user his name, age, and the number of times he wants to see the answer. The program will output when he will turn 100 and will be repeated a certain number of times.
What is hard for me is to make the program asks a number to the user when he enters a text.
Here is my program:
def input_num(msg):
while True:
try :
num=int(input(msg))
except ValueError :
print("That's not a number")
else:
return num
print("This will never get run")
break
name=input("What is your name? ")
age=int(input("How old are you? "))
copy=int(input("How many times? "))
year=2017-age+100
msg="Hello {}. You will turn 100 years old in {}\n".format(name, year)
for i in range(copy):
print(msg)
When you're prompting your user for the age: age=int(input("How old are you? ")) you're not using your input_num() method.
This should work for you - using the method you wrote.
def input_num(msg):
while True:
try:
num = int(input(msg))
except ValueError:
print("That's not a number")
else:
return num
name = input("What is your name? ")
age = input_num("How old are you? ") # <----
copy = int(input("How many times? "))
year = 2017 - age + 100
msg = "Hello {}. You will turn 100 years old in {}\n".format(name, year)
for i in range(copy):
print(msg)
This will check if the user input is an integer.
age = input("How old are you? ")
try:
age_integer = int(age)
except ValueError:
print "I am afraid {} is not a number".format(age)
Put that into a while loop and you're good to go.
while not age:
age = input("How old are you? ")
try:
age_integer = int(age)
except ValueError:
age = None
print "I am afraid {} is not a number".format(age)
(I took the code from this SO Answer)
Another good solution is from this blog post.
def inputNumber(message):
while True:
try:
userInput = int(input(message))
except ValueError:
print("Not an integer! Try again.")
continue
else:
return userInput
break

Beginner Python - Printing 3 different responses based on age using a while loop

Teaching myself Python out of a book and I'm stuck on this exercise:
A movie theater charges different ticket prices depending on a person’s age. If a person is under the age of 3, the ticket is free; if they are between 3 and 12, the ticket is $10; and if they are over age 12, the ticket is $15. Write a loop in which you ask users their age, and then tell them the cost of their movie ticket.
I know how to make it work without using a loop but I am a uncertain how to make it work using a while loop. Any advice or examples would be greatly appreciated.
One way to do this would be an infinite loop. Don't forget to include a break condition, otherwise you won't be able to exit your program gracefully.
while True:
userinput = int(input())
if userinput < 0:
break
# your if logic goes here
I was able to figure it out on my own
prompt = "\nEnter 'quit' when you are finished."
prompt += "\nPlease enter your age: "
while True:
age = input(prompt)
age = int(age)
if age == 'quit':
break
elif age <= 3:
print("Your ticket is free")
elif age <= 10:
print("Your ticket is $10")
else:
print("Your ticket is $15")
One way of doing it would be creating an infinite loop like such:
price = -1
while price == -1:
try:
age=int(raw_input('Age: '))
except ValueError:
print "Not a number, try again."
continue
if age <= 3:
price = 0
elif age > 3 and age < 12:
price = 10
else:
price = 15
print "The price will be "+str(price)+"$."
Note:
Rename raw_input() to input() if you are using Python 3.
I know this is an old question but none of the answers seemed great. So here's my solution to 7-5/ 7-6
loop = True
#while loop = true run 'while loop'
while loop:
#Print message
print ('Please enter your age.')
#receive input from user
age = raw_input()
#check if the user input "quit" if so end loop. Break ends program but should be replaceable by
#if age == 'quit':
# loop = False
#resulting the the same effect (ending loop)
if age == 'quit':
break
#Convert age input by user to int so it is recognized as a number by python
age = int(age)
#If/ elif pretty self explanatory
if age < 3:
price = 5
elif age < 12:
price = 10
elif age > 12:
price = 15
else:
print('Input not recognized')
break
#Print ticket price based on age and ask user if they need another price/inform them how to exit program
print('Your ticked price is $' + str(price) + '.')
print('\n If you would like to check the price for another person please enter their age now or type "quit" to exit')
The formatting might be a little off since it pasted oddly. I tried to explain what everything does. Also I use 2.7 instead of 3 so if you're using python 3 replace raw_input() with input()
Hopefully this answer was helpful to some on. GL with programming.
prompt = "How old are you? "
prompt += "\nEnter 'quit' when you are finished. "
while True:
age = input(prompt)
if age == 'quit':
break
age = int(age)
if age < 3:
print("Your ticket is free. Congratulations")
elif age < 13:
print("Your ticket is $10 dollars")
else:
print("Your ticket is $15 dollars")
prompt = "\nPlease enter 'done' when finished! "
prompt += "\nPlease enter your age:"
while True:
try:
age = input(prompt)
if age == 'done':
break
age = int(age)
if age <= 3:
print("Free ticket")
elif age in range(4, 12):
print("You must pay 10$")
elif age >= 12:
print("You must pay 15$")
except ValueError:
continue

Categories

Resources