Creating a list of tuples from a function - python

I am fairly new to python but already i am a very big fan of the language, i am currently working with some tutorials as well as doing a lot of reading and trying to apply what i read.
Been using this site for a while but this my first time posting
I am working on a problem that requires me to modify a function so that a list of tuples are returned. I have tried everything that i know and i am not having any success, this is as far as i have got.
this is my function:
def ask_age ():
newList=[]
count = int (input( "Enter Count "))
if count >7:
count=7
for n in range (count):
age = int(input( "Please Enter age = " ))
if age > 0:
newList.append(age)
print ("You are", age, "years old")
if age < 16:
print ("This is a child")
elif age >= 18:
print ("This is an Adult")
else:
print ("This is a youth")
print(newList)
when I run:
ask_age()
and this is the result
Enter Count 4
Please Enter age = 15
You are 15 years old This is a child
Please Enter age = 17
You are 17 years old This is a youth
Please Enter age = 18
You are 18 years old This is an Adult
Please Enter age = 25
You are 25 years old This is an Adult
[15, 17, 18, 25]
As I mentioned, I now need to modify the function so that instead a list of tuples is returned that looks like so:
[(15, 'This is a child'), (17, 'This is a youth'), (18, 'This is an Adult'), (25, 'This is an Adult')]
Any help would be greatly appreciated

change the part that's now
if age > 0:
newList.append(age)
print ("You are", age, "years old")
if age < 16:
print ("This is a child")
elif age >= 18:
print ("This is an Adult")
else:
print ("This is a youth")
to be instead:
if age > 0:
if age < 16:
newList.append((age, "This is a child"))
elif age >= 18:
newList.append((age, "This is an Adult"))
else:
newList.append((age, "This is a youth"))
and the print(newList) at the end to be return newList instead.

Related

Program not printing

I wrote this program but it is not executing when I print it:
age= int(input("How old is your dog?"))
if age>0:
print("Please input positive number")
elif age<=2:
dage= age*10.5
else age>2:
dage=21+((age-2)*4)
print("The dog is", dage, "years old")
print(age)
What am I missing to make it run?
I think you want to unindent the conditional statements. I think your conditional statements also need some work -- I've updated it a bit. See below.
Try
age = int(input("How old is your dog?" ))
dage = 0
if age < 0:
print("Please input positive number")
elif age <= 2:
dage = age*10.5
else:
dage = 21+((age-2)*4)
print("The dog is", dage, "years old")
print("age", age)

advice needed on `Or` function

if(name == "Lu") or (age == 26):
print("Hello Lu")
elif(name == "lu" or age != 26):
print("Welcome back")
else:
print("Hello")
On my understanding about the or on the if statement, if I did not write "Lu" but write the number 26 it should print "Hello Lu" because from what I've come to understand that if the first variable is false it will then direct to the second variable and if that is true then it will print the code.
However when I run my code and write a different name aside from Lu but write the correct number 26 it doesn't print "Hello Lu" rather it prints the "Welcome back".
Your code works as you think it should work for example if you took input from the user and remembered to typecast age to an int since you want to compare it with 26 not "26":
name = input("Enter your name:")
age = int(input("Enter your age:"))
if(name == "Lu") or (age == 26):
print("Hello Lu")
elif(name == "lu" or age != 26):
print("Welcome back")
else:
print("Hello")
Example Usage with name something other than "Lu" or "lu" and age equaling 26:
Enter your name: Ku
Enter your age: 26
Hello Lu
As you can see it does not print "Welcome Back" but rather "Hello Lu" like you thought it should :)
Play around with other inputs here!
You should you be checking for a string or (age == '26') unless age has been converted from a string input to a number.

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

How do i print an output if the value entered is not an integer

I am trying to do two things here.
I want to print "value entered is not a valid age" if the input is not a number in this code:
age = float(input (' enter your age: '))
if 0 <age < 16:
print "too early for you to drive"
if 120 >= age >= 95:
print 'Sorry; you cant risk driving'
if age <= 0:
print 'Sorry,' ,age, 'is not a valid age'
if age > 120:
print 'There is no way you are this old. If so, what is your secret?'
if 95 > age >= 16:
print 'You are good to drive!'
Also, how can I repeat this program once it is done?
You could check whether input is a valid digit with isdigit method of str. For multiple times you could wrap your code to a function and call it as much as you want:
def func():
age = input (' enter your age: ')
if age.isdigit():
age = float(age)
if 0 <age < 16:
print "too early for you to drive"
if 120 >= age >= 95:
print 'Sorry; you cant risk driving'
if age <= 0:
print 'Sorry,' ,age, 'is not a valid age'
if age > 120:
print 'There is no way you are this old. If so, what is your secret?'
if 95 > age >= 16:
print 'You are good to drive!'
else:
print "value entered is not a valid age"
func()
For make this code runnig every time you should add a loop , like while loop , and add a break whenever you want end this loop or add a condition for example run 10 times,and if you want check the input is float , you can add a try section:
counter = 0
while counter < 10:
age = raw_input (' enter your age: ')
try :
age = float(age)
if 0 <age < 16:
print "too early for you to drive"
if 120 >= age >= 95:
print 'Sorry; you cant risk driving'
if age <= 0:
print 'Sorry,' ,age, 'is not a valid age'
if age > 120:
print 'There is no way you are this old. If so, what is your secret?'
if 95 > age >= 16:
print 'You are good to drive!'
counter -= 1
except ValueError:
print "value entered is not a valid age"
It is also a good idea to arrange your cases in order, to make it easier to see what is happening (and to make sure you didn't leave an unhandled gap):
while True:
age = input("Enter your age (or just hit Enter to quit): ").strip()
if not age:
print("Goodbye!")
break # exit the while loop
try:
# convert to int
age = int(age)
except ValueError:
# not an int!
print("Value entered is not a valid age")
continue # start the while loop again
if age < 0:
print("Sorry, {} is not a valid age.".format(age))
elif age < 16:
print("You are too young to drive!")
elif age < 95:
print("You are good to drive!")
elif age <= 120:
print("Sorry, you can't risk driving!")
else:
print("What are you, a tree?")

Simple Python "if", "elif", "else"

Making a "Mad Libs" style thing in Python for class, it's my first day, I've already picked up most of what I needed to know, but I'm not sure how to go about using the "if", "elif", "else" things. Here's what I have so far, basically, when the age is input I want it to choose if the person is an adult or a kid.
print "welcome to your short story"
name = raw_input("Input your name: ")
age = raw_input("Input your age: ")
if age > 21:
age = "adult"
elif age < 21:
age = "kid"
print "My name is ",name,"and I am a " ,age,"year old ",age
1) You are overriding the inputted age with strings adult of kid.
2) You have to handle the case when age equals 21.
3) The age input needs to be converted to an integer.
Let's rewrite your code, and see how we can improve:
print "welcome to your short story"
name = raw_input("Input your name: ")
# Convert the input to an integer.
age = int(raw_input("Input your age: "))
# This is the status variable being either adult or child
# before you were overriding age variable with adult or kid
status = ""
# Also, you have to handle the case where the age equals 21, before
# you were just checking if it is less or greater than 21
if age >= 21:
status = "adult"
elif age < 21:
status = "kid"
print "My name is ", name ," and I am a " , age ," year old " , status
I realized I needed a different value and have changed it.
print "welcome to your short story"
name = raw_input("What is your name?: ")
age = raw_input("How old are you?: ")
sex = raw_input("Are you a boy or a girl?: ")
if age > 21:
targetAge = "adult"
elif age < 21:
targetAge = "kid"
print "My name is ",name,"and I am a " ,age,"year old ",targetAge,"."
So, basically, when it is printed, it should read as "My name is _____ and I am a __ year kid/adult." Depending on the number they've input. The reason I'm not using the int() function is because that was never mentioned, this is literally the first day of class, so I'm going by what the instructor has gone over.
As suggested by foxygen, the int function is needed to convert your input from a string to an int
age = int(raw_input("Input your age: "))
There is a difference between the characters "1", "2", "3" and so forth, and the numbers 1, 2, 3, and so forth. Some languages try to convert for you, but python will not do this, so you end up comparing "32" to 21, which is an apples-to-oranges comparison.
Also, while you're safe in this particular instance, you'll notice how you're reassigning age while you're still computing based on its original value. This is not generally safe, and you would be better off assigning to a new variable:
if age > 21:
age_label = "adult"
elif age < 21:
age_label = "kid"
else:
age_label = "person" # in case a 21 year old uses your program
You're safe in this case because the if/else construction will only ever execute one branch, but it's best not to get in the habit of rewriting the input value while you're still consulting it.
print "Welcone to your Story"
name = raw_input("Please enter yout name: ")
age = int(raw_input("please enter your age: "))
if age >= 21:
status = "an adult"
else:
#enter code here
status = "a kid"
print "My name is %r , I am %r and I am %r years old" %(name,status,age)

Categories

Resources