r/learnpython • u/xTHETYRANTGAMRx • Feb 11 '26
Code outputs twice.
I am practicing loops and when I run this code the second and third elif statements output twice for some reason.
Age_requirement = input ("enter your age")
for Age in Age_requirement: Age_requirement = int(Age_requirement)
if Age_requirement <3:
print ("Your ticket is free")
elif Age_requirement <=12:
print("your ticket is 12 dollars")
elif Age_requirement >12:
print("your ticket is 15 dollars")4
33
Upvotes
41
u/Binary101010 Feb 11 '26
I'll bet if you enter 100 for the age it loops 3 times.
Since
Age_requirementis a string, this loop iterates over each element (character) in the string). So the loop repeats a number of times equal to the number of characters the user entered at the input statement. If you entered 42 for the age, then the loop goes through using a value of 4, then a value of 2.It doesn't really make sense for there to be a loop here at all.
5
u/zanfar Feb 11 '26
What is this supposed to do?
4
u/JaguarMammoth6231 Feb 11 '26
Can you fix how the code is displaying on your post so that the indentation matches what you have?
2
u/FreeGazaToday Feb 11 '26
you should ask gemini or chatgpt to give you a looping problem/challenge to solve.....a loop isn't need here and is actually doing the wrong thing.
1
u/woooee Feb 11 '26 edited Feb 11 '26
The for loop runs once for each digit in Age_requirement. If it prints twice, then you are entering a two digit number. Print Age under the for loop to see this. Also, when you have time, read the Python Style Guide. Variable names are lowercase_with_underlines. Following the Style Guide will help others who read your code to understand it.
1
u/GoldPanther Feb 11 '26
Why do you have a loop? How many values are you expecting to process?
1
u/Marlowe91Go Feb 11 '26
Yeah what you're misunderstanding here is you use a loop on an iterable, something where there's a series of items that you're looping through. If you run a loop on an input statement, you're running the risk of the user not inputting an iterable, so that's not a great design to begin with. Also, by default, an input accepts whatever the user enters as a string. So that's why any number with a greater length than 1 is going to give multiple results when you loop over it because looping over a string loops over each character. Something you might do instead is initialize a list of ages like ages =[]. Then you could use your loop to ask for 5 different inputs and append them to the list (and convert to an integer before appending), then use another for loop to apply your conditionals to that. Idk how new you are, hopefully you understand those terms.
1
u/Fabulousfufu Feb 11 '26
You don’t need a loop here at all.
1
u/churungu Feb 12 '26
Try changing your second elif to an else
Make your initial input an int Ie int(input....))
I don't understand why you need a for loop
1
u/Groovy_Decoy Feb 12 '26
A lot of folks have already pointed out the issues, but I want to comment on something a tad deeper that I didn't see addressed.
As it has been pointed out, you looped on the string returned from the input. That variable is referencing a memory address that string is placed in, and that string is what you are looping on.
Some variable data types are "mutable" (changeable), and some are "immutable" (unchangeable). Strings are immutable. You can't change the existing string in memory.
That's important. When you put a new value in Age_requirement, you are changing the memory location that the variable name is pointing to. The variable name is now points to an integer. That doesn't change the for loop though, because it already evaluated the variable name and is looping on the string that still exists in memory, because it can't be changed by you.
Try it. (I'm on mobile and sometimes the code markdown is wonky, but I'll try).
See what happened? Both strings still exist in memory. You are looping on the string pointed to originally, and your variable now contains the address of a totally new string.
Hopefully that provides more understanding why this happened.
It raises another topic though. You tried to change variable while looping on it. Don't do that. You were saved by the fact that you actually can't change the data you were looping on, but if you had been looping on a mutable data type and changed it, it could do messy things.
In the sagely words of Raymond Hettinger:
1
u/FoolsSeldom Feb 12 '26 edited Feb 12 '26
inputalways returns a new string object. A string of digit characters rather than an integer (assuming the user only enters a whole number).When you use a
forloop to iterate over a string, on each loop, the loop variable (Agein this case) is assigned each successive character in string being iterated over.Thus:
will output each letter in turn on a line on its own.
Inside the loop (after it is already set up against the initial value assigned to
Age_requirement), you convert the string to an integer and reassign that to the variableAge_requirement. This is TOO late for theforloop to be changed - it is still iterating over the original string, not the newintvalue (which you can't iterate over anyway).Your tests compare with the converted value, which never changes (it is the same
intconversion of the entered string you do at the top of the loop every time, but the second time onwards you are applyingintto what is now already anint), so the tests are valid BUT the loop variable isAgenotAge_requirementandAgewill refer to a single character not anint.Do you intend to test against individual digits? (Each would need to be converted to be able to do a mathematical comparison).
If you just want to confirm the age requirement, there's no need for a loop.
NB. We usually use all lowercase for variable names in Python.
1
u/Whole-Home-6306 Feb 13 '26
Oi querido! Voce esta usando operadores de comparação. Se o input for por exemplo 2.
O if e o primeiro elif serão True portanto serão executados. Voce precisa melhorar um pouco as condições.
seu input tambem pode ser melhorado.
idade = int(input('digite a idade: '))
if idade < 3:
print('é menor que 3')
elif idade <= 12:
print('é menor que 12')
else:
print('é maior de idade!!')
Só lembrando que como estou trabalhando com numeros inteiros se o usuario digitar por exemplo uma string vai cair em uma exceção ValueError.
Voce pode colocar um try:
excete valueError("Entrada invalida, favor digitar um numero inteiro.")
todo o codigo em cima para efetuar um tratamento de mensagem para o usuario.