age = 0
joke = 'What do you call a cow with no legs? Ground beef.'
myName = raw_input('Hello! What is your name?')
myAge = raw_input('Tell me your age, ' + myName + ', to hear a joke!')
if age < 6:
print('You are too young to hear this joke.')
elif age > 12:
print('You are too old to hear this joke.')
elif age == range(6, 12):
print(joke)
The code, when run, only says that I am too young to hear the joke even if I put a number higher than 6 or even higher than 12. Could you help me fix this problem?
There's no need for the last elif. Just use else without a condition.
If both age < 6 and age > 12 evaluate to false, we know that 6 ≤ a ≤ 12. There's no need to check for it.
BTW, range() returns an iterable, not something you can compare with a number. The comparison will always fail because you're comparing two things that are incompatible.
You're assigning the input into variable "myAge" and are testing variable "age" in your if statement.
Replace
myAge = raw_input('Tell me your age, ' + myName + ', to hear a joke!')
with
age = input('Tell me your age, ' + myName + ', to hear a joke!')
Related
As an exercise in class, we are supposed to calculate the entry price for people in a night club, provided their age and gender. The under 25 get 20% off, and Females/NBs get 50% off, stacking multiplicatively.
While my code works, it repeats the gender check twice, which is poor form and could cause problems in a more complex application. How can I spare the repetition ?
(* OCaml Version *)
let entry_price age gender =
if age < 18
then (failwith "Must be over 18 to enter")
else let price = 12.0 in
if age <= 25
then let price = (price *. 0.8) in
if gender == 'f' || gender == 'x'
then (price *. 0.5)
else prix
else if gender == 'f' || gender == 'x'
then (price *. 0.5)
else price;;
Here is a Python version that does not repeat itself, thanks to ternary operators : (Could also be done with non-nested ifs, which Ocaml disallows)
# Python version
def entry_price(age : int, gender : str):
if age < 18:
raise ArgumentError("Must be over 18 to enter")
return (
12.0
*(0.8 if (age<25) else 1)
*(0.5 if gender in ['f', 'x'] else 1)
)
You can pretty much copy the python version:
let entry_price age gender =
if age < 18
then failwith "Must be over 18 to enter"
else
12.0
*. (if age < 25 then 0.8 else 1.0)
*. (if gender = 'f' || gender = 'x' then 0.5 else 1.0);;
There's only a slight difference in the if expression syntax, and you need to use the float-specific multiplication operator, *., instead of the int-specific *.
Also, to pick a nit, there are no statements in OCaml. Statements are an imperative/procedural construct, ie. do this, then do that. OCaml is an expression-based language, where each expression evaluates to a value. You can still discard the value of an expression, and thereby make it look like a statement, but the compiler will complain unless you are very explicit about discarding it since that is usually a user error.
#glennsl provides a nice direct translation of the Python code to OCaml, but there are other ways we can approach this.
If we create a variant type to describe ages, we can write a categorize_age function which will translate a numeric age to a descriptive term we can pattern match on. It also gives us a convenient place in the future to change what ages we use to make these determinations.
Then we can use a match on both age and gender to consider the four possible outcomes:
Under 18
Under 25 and either 'f' or 'x' gender
25 or older and either 'f' or 'x' gender
Anyone else 18 or older
type age_cat = Under_age | Legal | Adult
let categorize_age a =
if a < 18 then Under_age
else if a <= 25 then Legal
else Adult
let entry_price age gender =
let price = 12.0 in
match categorize_age age, gender with
| Under_age, _ -> failwith "Must be over 18 to enter"
| Legal, ('f' | 'x') -> price *. 0.8 *. 0.5 (* or just 0.4 *)
| Adult, ('f' | 'x') -> price *. 0.5 *. 0.5 (* or just 0.25 *)
| _ -> price
Looking at the logic here, we actually don't need to specify Adult, ('f' | 'x') because we know that we've already matched cases where when gender is 'f' or 'x', age is either Under_age or Legal. Thus we can use a wildcard _ for the pattern: _, ('f' | 'x').
The last pattern is a wildcard because we're matching any case that hasn't already been matched, and those values are not relevant to the outcome, so there's no point in binding name(s) to them.
let entry_price age gender =
let price = 12.0 in
match categorize_age age, gender with
| Under_age, _ -> failwith "Must be over 18 to enter"
| Legal, ('f' | 'x') -> price *. 0.8 *. 0.5 (* or just 0.4 *)
| _, ('f' | 'x') -> price *. 0.5 *. 0.5 (* or just 0.25 *)
| _ -> price
Keep getting syntax error.
I keep getting........
CODE:
answer = "b"
question = "1) Who made the game Grand Theft Auto 5??\nPlease choose from the following and write a letter: \n◘ A)Viral\n◘ B)Rockstar Games\n◘ C)Madfinger\n◘ D)Gameloft"
print(question)
guess=input().lower()
name=input("Please enter your answer: ")
if guess ==answer:
print("Correct")
score = score + 1
print("Score:")
print(score)
else:
print("Wrong")
You never use name, so why not removing it?
answer = "b"
question = "1) Who made the game Grand Theft Auto 5??\nPlease choose from the following and write a letter: \n◘ A)Viral\n◘ B)Rockstar Games\n◘ C)Madfinger\n◘ D)Gameloft\n"
print(question)
guess=input("Please enter your answer: ").lower()
if guess ==answer:
print("Correct")
score = score + 1
print("Score:")
print(score)
else:
print("Wrong")
Basically I'm trying to make a .vbs file that gives you ten random addition problems. Then, in an input box, you type the answer to the given problem. Everything works except the If/Else statement that tells you if you are right or wrong. If it says "What is 2 + 2" and I type "4" (without quotations), then it outputs "(You attack) TRIP! POW! ouchy wrong You could've gotten it right IF you typed: 4." Here's the code:
msgbox("Starting addition. Press OK to begin.")
dim i
i = 0
Do
i = i + 1
'i is for the question timer
Dim max,min
max=100 'max random
min=1 'min random
dim j, k, l 'part part total
Randomize
msgbox("What is")
j = Int((max-min+1)*Rnd+min)
msgbox(j)
msgbox("plus")
k = Int((max-min+1)*Rnd+min)
msgbox(k)
answer = Inputbox("I hope you got all of that... ^_^")
l = j + k
if answer = l then
msgbox("(You attack) BAM! Right on target")
else
msgbox("(You attack) TRIP! POW! ouchy wrong")
msgbox("You could've gotten it right IF you typed:")
msgbox(l)
end if
loop until i = 10
Read in Comparison Operators (VBScript) reference:
... how expressions are compared or what results from the comparison,
depending on the underlying subtype: ...
If one expression is numeric and the other is a string Then the numeric expression is less than the string expression.
j = Int((max-min+1)*Rnd+min)
k = Int((max-min+1)*Rnd+min)
answer = Inputbox("I hope you got all of that... ^_^" _
& vbCR & "What is " & j & " plus " & k)
l = j + k
If IsNumeric( answer) then
answer = Int( answer)
Else
answer = l - 1
End If
if answer = l then
msgbox("(You attack) BAM! Right on target")
else
msgbox("(You attack) TRIP! POW! ouchy wrong")
msgbox("You could've gotten it right IF you typed:")
msgbox(l)
end if
I'm not to confident that I am asking this question correctly but this is what I'd like to do.
In django admin, I would like to write an action that sorts the list of my contestants randomly and doesn't allow two people with the same first name to be within 4 records of eachother. So basically,
if you have John L. John C. Carey J, Tracy M. Mary T., the records would be listed like this:
John L.
Mary T.
Carey J.
Tracy T.
John C.
OR
How can I write an action that would create random groups where two people with the same name wouldn't be within the same group like so:
John L. John C. Carey J, Tracy M. Mary T. =
Group 1
John L.
Mary T.
Carey J.
Tracy T.
Group 2
John C.
Forgive me if it isn't very clear, let me know and I'll try to specify further but any help would be appreciated
EDIT:
Is this what you are referring to? I can't quite figure out how to compare the fields to see if they are the same
Model:
class people(models.Model)
fname = model.CharField()
lname = model.CharField()
group = model.IntegerField()
View:
N = 4
Num = randint(0, N-1)
for x in queryset:
x.group = Num
if group == group| fname == fname | lname == lname:
x.group = (Num + 1) % N
Your first question cannot be solved always. Just think of all contestants have the same name, then you actually cannot find a solution to it.
For the second question, I can suggest an algorithm to do that, though.
Since I do not see any restriction on the number of groups, I will suggest a method to create the least number of groups here.
EDIT: I assumed you don't want 2 people with same "First name" in a group.
The steps are
Count the appearance of each name
count = {}
for x in queryset:
if x.fname not in count:
count[x.fname] = 0
count[f.name] += 1
Find the name with the most appearance
N = 0
for x in queryset:
if count[x.fname] > N:
N = count[x.fname]
Create N groups, where N equals to the number of appearance of the name in step 2
For each name, generate a random number X, where X < N.
Try to put the name into group X. If group X has that name already, set X = (X + 1) % N and retry, repeat until success. You will always find a group to put the contestant.
from random import randint
groups = [[]] * N
for item in queryset:
X = randint(0, N-1)
while item.fname in groups[X]:
X = (X + 1) % N
groups[X].append(item.fname)
item.group = X
EDIT:
Added details in steps 1, 2, 4.
From the code segment in your edited, I think you do not actually need a definition of "group" in model, as seems you only need a group number for it.
A_quantity = 10
B_quantity = 20
the quantity amount
N = float (input('please enter the quantity of package: '))
X_total = float (N*99.00)
the fee from input
Q_discount = (0.2*X_total)
W_discount = (X_total*0.3)
discounts from input total
Y_total = (X_total-Q_discount)
M_total = (X_total-W_discount)
the fee with the discount
def main ():
if N >= A_quantity:
print ('the total cost is $', \
format (Y_total, ',.2f'))
else:
if N >= B_ quantity:
print ('the total cost is $', \
format (M_total, ',.2f'))
main ()
the results should be 10 packages for $792.00
and 20 packages for $1,380.00
yet the second statement gets the 20% discount also which total to $1549.00, when it should get only 30% discount
I don't know which language it is, but it's an algorithm problem : you should first try for the highest value cause the way it is designed now, if N = 30 , you will always enter the "if" , never the "else" , and if N=5 , you will enter the "else" , but the the if inside it...
let me try although I don't know the language:
def main ():
if N >= B_quantity:
print ('the total cost is $', \
format (M_total, ',.2f'))
else:
if N >= A_quantity:
print ('the total cost is $', \
format (Y_total, ',.2f'))
main ()
take the value of the product divided by 100 and multiplied by the discount
and then get this result and the value of the product subitrair
var SomaPercent = ValorUnit/100 * descont;
var result_fim = ValorUnit-SomaPercent;
you can change the if condition to
if N >= A_quantity && N < B_quantity ...
if N >= B_quantity
..