advice needed on `Or` function - python

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.

Related

Why is this simple code wrong?

print("Hello there")
name=input("What is your name?")
print("Welcome to the some game, " + name + "!")
print("I'm going to ask you some basic questions so that we could work together")
age=input("Your age")
if age >= 14 and age < 41:
print("K")
else:
print("Sorry bruh")
print("Thanks")
keeps showing me "Sorry bruh" at the end when entered 15. Why? What's wrong?
Cast your input to int:
age = int(input("Your age"))
You could add a try-except. Your condition should equally be evaluated on or not and
Either you use Python3 and you need to cast with int(input("Your age")) or you use Python2 and then you need to use raw_input to read the name: name=raw_input("What is your name?")
Ok , so you can try this code in python2.7 and it will work as you desired:
print("Hello there")
name=raw_input("What is your name?")
print("Welcome to the some game, " + name + "!")
print("I'm going to ask you some basic questions so that we could work together")
age=input("Your age")
if age >= 14 and age < 41:
print("K")
else:
print("Sorry bruh")
print("Thanks")

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

Creating a list of tuples from a function

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.

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)

Simple raw_input and conditions

I created the simple code:
name = raw_input("Hi. What's your name? \nType name: ")
age = raw_input("How old are you " + name + "? \nType age: ")
if age >= 21
print "Margaritas for everyone!!!"
else:
print "NO alcohol for you, young one!!!"
raw_input("\nPress enter to exit.")
It works great until I get to the 'if' statement... it tells me that I am using invalid syntax.
I am trying to learn how to use Python, and have messed around with the code quite a bit, but I can't figure out what I did wrong (probably something very basic).
It should be something like this:
name = raw_input("Hi. What's your name? \nType name: ")
age = raw_input("How old are you " + name + "? \nType age: ")
age = int(age)
if age >= 21:
print "Margaritas for everyone!!!"
else:
print "NO alcohol for you, young one!!!"
raw_input("\nPress enter to exit.")
You were missing the colon. Also, you should cast age from string to int.
Hope this helps!
With python, indentation is very important. You have to use the correct indentation or it won't work. Also, you need a : after the if and else
try:
if age >= 21:
print #string
else:
print #other string
Firstly raw_input returns a string not integer, so use int(). Otherwise the if-condition if age >= 21 is always going to be False.:
>>> 21 > ''
False
>>> 21 > '1'
False
Code:
name = raw_input("Hi. What's your name? \nType name: ")
age = int(raw_input("How old are you " + name + "? \nType age: "))
The syntax error is there because you forgot a : on the if line.
if age >= 21
^
|
colon missing

Categories

Resources