#🔒 Checking character length of string

208 messages · Page 1 of 1 (latest)

rose harborBOT
#

@past sphinx

Python help channel opened

Remember to:

  • Ask your Python question, not if you can ask or if there's an expert who can help.
  • Show a code sample as text (rather than a screenshot) and the error message, if you've got one.
  • Explain what you expect to happen and what actually happens.

:warning: Do not pip install anything that isn't related to your question, especially if asked to over DMs.

deft bane
#

!code

rose harborBOT
#
Formatting code on Discord

Here's how to format Python code on Discord:

```py
print('Hello world!')
```

These are backticks, not quotes. Check this out if you can't find the backtick key.

For long code samples, you can use our pastebin.

past sphinx
#

can you see my code?

#

for some reason it is not working

deft bane
#

What's the problem?

past sphinx
#

I want to check when the user inputs a character that exceeds 40 characters and if it does, it re-prompts them to enter in a character less than 40.
When they enter in the menu_list that equals add

kind zenith
past sphinx
#

here is a more detailed explanation...
For option “Add”, the program searches the list to see whether the selected year is already there. If it isn’t, the
user is prompted to enter a title, and category, then adds the [year, title, category] to the list. If already there, the
user is asked if they want to replace it with a new title and category. If yes, the program prompts for a title and
category and replaces it. The movie list is kept in year order.

The values are validated by your program as follows:
year – must be an integer between 1927 and 2022, inclusive
title – must be a string of size less than 40 (What i am currently stuck with)
category – must be one of these values: (‘drama’, ‘western’, ‘historical’, ‘musical’, ‘comedy’, ‘action’,
‘fantasy’, ‘scifi’, ‘suspense’, ‘comedy-drama’)
Option “Scat” lists the valid categories.

past sphinx
past sphinx
#

i attempted using while and if, rearranged the order of the code but can't seem to figure it out.

kind zenith
#

well, title is entered by a user, right?

past sphinx
#

yes

kind zenith
#

and it is stored in a variable

past sphinx
#

movie_1 to be exact

#

yes

kind zenith
#

len(movie_1) will get the length of that string

past sphinx
#

yeah i did that

kind zenith
#

which you can inside of if statement to compare it against your limit length

past sphinx
#

well i had it as an if statement before and changed it to a while

kind zenith
#
while True:
    if len(movie_1) > 40:
        print('length must be less than 40, please try again')
        continue # Skips all code below and goes back to while True
    break # Ends the loop
#   ^ note the amount of spaces. This break is outside the if statement (just to make sure u know that sorry)
#

also instead of continue u can use else: ... block

while True:
    if len(movie_1) > 40:
        print('length must be less than 40, please try again')
    else:
        break # Ends the loop
kind zenith
past sphinx
#

ok i see

#

yeah it still doesn't work

kind zenith
#

anyway, last thing i gotta say about len(...), is that it can be used for a lot of objects, that u can measure the length of.

>>> some_list = [10, 20, 50, 150, 999]
>>> len(some_list)
5

for example u can use len(...) on a list, tuple, etc
makes sense i guess 🗣️

kind zenith
#

show the code once again

past sphinx
#

ok

kind zenith
#

that way of writing a program isnt the best practice, but its alright for now
but u can easily make a mistake and confuse the if statements, for and while loops

#

by using wrong amount of spaces or something

#

or putting else statements in wrong places

past sphinx
#

i think maybe the indentations is the problem here possibly.

kind zenith
#

also im gonna say a few things apart from the problem

past sphinx
#

sure

#

btw i didnt do this all in one sitting, but i came back occassionally to view my code to make sure i wasnt missing anything.

#

but im all ears tho

kind zenith
#

wait...

#
            while True:
                year_1 = int(input('Type in a year (between 1927 and 2022), or type "0" to quit: '))
                if year_1 == 0:
                    break
                if year_1 > 2022:
                    print("\nIt must be between 1927 and 2022")
                    year_1 = int(input('\nType in a year (between 1927 and 2022), or type "0" to quit: '))
                if year_1 < 1927:
                    print("\nIt must be between 1927 and 2022")
                    year_1 = int(input('\nType in a year (between 1927 and 2022), or type "0" to quit: '))
                found = False
                for s in movies:
                    if year_1 == s[0]:
                        replace = input(str(s[0]) + ' is in the list, do you want to replace ' + s[1] + ' (y/n)?')
                        found = True
#

that looks like a logic mistake

#

when u ask for year_1

past sphinx
#

hmm?

kind zenith
#

if its outside of range, u enter one of if statements

#

year_1 = int(input('\nType in a year (between 1927 and 2022), or type "0" to quit: '))

#

inside you have this

#

and for example, u enter 1920 again, which is outside of range

#

and because there are no more if statements down below

#

the program will continue with that wrong year_1 value

#

that needs to be a while loop by itself

past sphinx
#

no is its outside of the range it tells the user that its outside of the range.

#

of 1927 and 2022

kind zenith
#

yeah and then it hits the line year_1 = int(input('\nType in a year (between 1927 and 2022), or type "0" to quit: '))

#

and then it goes down to found = False

#

etc

past sphinx
#

oh i see

#

it prompts them to add it to the list or not

#

good catch

kind zenith
#

so, yeah, it has to be while True loop by its own

#

u remember that example right?

#
while True:
    if len(movie_1) > 40:
        print('length must be less than 40, please try again')
    else:
        break # Ends the loop
past sphinx
#

yes.

kind zenith
#

it should look somewhat like this

#

anyways

#

next up is just a simplification

past sphinx
#

even with the "while true" it takes 2023 regardless.

#

here an ss

#

here's

kind zenith
#

thats the problem with if statements!

#

the way u did them to be exact

#
year_1 = int(input('Type in a year (between 1927 and 2022), or type "0" to quit: '))
if year_1 == 0:
    break
if year_1 > 2022:
    print("\nIt must be between 1927 and 2022")
    year_1 = int(input('\nType in a year (between 1927 and 2022), or type "0" to quit: '))
if year_1 < 1927:
    print("\nIt must be between 1927 and 2022")
...(other code)
#

lets go line by line

#

we enter year_1

past sphinx
#

ok

kind zenith
#

we enter 2023

past sphinx
#

yes

kind zenith
#

so year = 2023

#

if year_1 == 0: doesnt work

#
>>> if year_1 > 2022:
    print("\nIt must be between 1927 and 2022")
    year_1 = int(input('\nType in a year (between 1927 and 2022), or type "0" to quit: '))

then we're in the first if statement, which worked, because 2023 > 2022

#

and we enter year_1 again

past sphinx
#

mhm

kind zenith
#
# year_1 = 2023
# if year_1 == 0:
#     break
>>> if year_1 > 2022:
#     print("\nIt must be between 1927 and 2022")
>>>    year_1 = 2023
if year_1 < 1927:
    print("\nIt must be between 1927 and 2022")
#

we entered 2023 again

#

whats the next line?

#

if year_1 < 1927: if its less than 1927

#

and, 2023 < 1927 is False

past sphinx
#

hmmm

kind zenith
#

so we skip over that if statement and go down

#

and down below is all the other code

#

here's the fix tho

#

u can combine those two if statements together

#

into a single condition

past sphinx
#

i guess i should change the print statements to be more concise and logically it needs to make sense

#

yeah i could use "or"

#

but

#

just for step by step purposes

#

i intentionally left it like that

kind zenith
#

its worse like that

#

cuz it allows for such "hack"

past sphinx
#

yep

kind zenith
#

and its also a repitition of code

#
                if year_1 > 2022:
                    print("\nIt must be between 1927 and 2022")
                    year_1 = int(input('\nType in a year (between 1927 and 2022), or type "0" to quit: '))
                if year_1 < 1927:
                    print("\nIt must be between 1927 and 2022")
                    year_1 = int(input('\nType in a year (between 1927 and 2022), or type "0" to quit: '))

like you have to write those two lines two times in a rows

#

and imagine if there was 10 lines

#

or 50

past sphinx
#

yeah was abt to put that lol

#

or

if year_1 > 2022 or year_1 < 1927:
    print("\nIt must be between 1927 and 2022")
     year_1 = int(input('\nType in a year (between 1927 and 2022), or type "0" to quit: '))
found = False
kind zenith
#

so yep

#

mhm

past sphinx
#

something like that

kind zenith
#

and as i said that would be put inside of while loop

#

the one that i showed u

#

so it would be something like

past sphinx
#

oh so
while true:
etc

kind zenith
#
while True:
    year_1 = int(input('\nType in a year (between 1927 and 2022), or type "0" to quit: '))
    if year_1 > 2022 or year_1 < 1927:
        print("\nIt must be between 1927 and 2022")
        continue
    break
#

if u remember, continue just goes to next iteration, so that break is skipped

#

and it goes back to year_1 = int(...

#

but if that if statement didnt work

#

it goes straight into break which ends this loop

#

and the program continues

past sphinx
#

so i need two while trues ?

#

one for when menu_list == "Add"
and for the year_1

kind zenith
#

well, while True for each... for every single input.. 💀

past sphinx
#

heh

kind zenith
#

oh, also

#

another thing

#

if u enter 0 u need to just close the program?

past sphinx
#

yeah

kind zenith
#

if u do a while True like that

#

it will become... a bit hard to end all while True loops

#

cuz this is a while True inside of another While True

#

easiest way to exit the program, even though, you would lose that text

#

like

#

end of a program
press Enter...

#

but there is exit() function, that does exactly that

#
while True:
    year_1 = int(input('\nType in a year (between 1927 and 2022), or type "0" to quit: '))
    if year_1 == 0:
        exit()
    if year_1 > 2022 or year_1 < 1927:
        print("\nIt must be between 1927 and 2022")
        continue
    break
past sphinx
#

i wish

kind zenith
#

but as u can see

#

if year_1 will be equal to 0

#

exit() will just close the program

#

u can put the text u want inside the if statement, tho

past sphinx
#

yeah, i understand but i haven't learned that yet.

kind zenith
#

but you'd need to do it in a lot of places... which is annoying

past sphinx
#

year_1 will equal 0 but it closes the program

kind zenith
#

but i guess with your knowledge it has to be like that

kind zenith
#

also, just a tip

#

better to not name stuff like year_1

#

cuz its not clear what is year_1 supposed to represent

#

first year?

past sphinx
#

ik butttttt

kind zenith
#

in ur case, i guess, its like input_year

past sphinx
#

i already have a variable called year

kind zenith
#

input_ cuz u get it from user input

#

and year cuz year

past sphinx
#

ok

kind zenith
#

other variations would be fine as well, like user_year etc

#

but i prefer the first one

past sphinx
#

yeah ill do input_year

kind zenith
#

by the way

#

this is a very interesting way of doing it 😅

if replace in 'nN':
past sphinx
#

how so

kind zenith
#

but it will get very bad once you will want to check for something longer

#

like, yes can be spelled yes, Yes, YEs, YES, yES, ... you get it

past sphinx
#

yea

#

btw

kind zenith
#

here's the fix if u wanna know:

>>> 'aAA'.lower()
'aaa'
>>> 'BFwsiFF'.lower()
'bfwsiff'

str.lower() gives u a new string where all characters are lowercase

#
if replace.lower() == 'yes':
    ...
#

sorry that this is out of the topic tho

past sphinx
#

nah it def helps makes things simple

#

knowledge is good lol

kind zenith
#

🗣️

past sphinx
#

or information?

#

hm

kind zenith
#

i guess both

past sphinx
#

yeah

kind zenith
past sphinx
#

oh yeah

#

it still doesn't prompt the user to re-enter after 40 characters have been entered even after implementing the while True 😬

kind zenith
past sphinx
#

alright

#
while True:
                    if input_year > 2022 or input_year < 1927:
                        print("\nIt must be between 1927 and 2022")
                        input_year = int(input('\nType in a year (between 1927 and 2022), or type "0" to quit: '))
                    found = False
                    for s in movies:
                        if input_year == s[0]:
                            replace = input(str(s[0]) + ' is in the list, do you want to replace ' + s[1] + ' (y/n)?')
                            found = True
                            if replace in 'nN':
                                break
                            if replace in 'yY':
                                movie_1 = input('Type in a new movie: ')
                            while len(movie_1) > 40:
                                movie_1 = input('Type in a movie less than 40 characters: ')
                            else:
                                category_1 = input('Type in a new category: ')
                            if category_1 not in valid_categories:
                                print('\nEnter in a valid category')
                                category_1 = input('Type in a new category: ')
                            s[1] = movie_1
                            s[2] = category_1
                            break
kind zenith
#
while True:
                    if input_year > 2022 or input_year < 1927:
                        print("\nIt must be between 1927 and 2022")
                        input_year = int(input('\nType in a year (between 1927 and 2022), or type "0" to quit: '))

that must be a fully separated loop

#

i'll write an example where u have to enter age and name, with similiar limitations to ur program

#
while True:
    age = int(input('Enter your age (from 0 to 100) > '))
    if age < 0 or age > 100:
        print('Age must be a number from 0 to 100. Try again.')
        continue
    break

while True:
    name = input('Enter your name (no more than 20 chars.) > ')
    if len(name) > 20 or len(name) == 0:
        print('Name must not be empty and cannot be longer than 20 characters. Try again.')
        continue
    break

print(f'Hello {name}, looks like you are {age} years old!!!')
#

as u can see... for each single input u must re-ask if that input doesnt satisfy the requirements

#

so each input is inside its own while True loop

past sphinx
#

yes lemme check mines rq

kind zenith
#

and obviously, if u have different commands

#

it becomes insanely difficult!

#

i'll write an example with two commands, too

#

hol' up a minute

past sphinx
#

ok

kind zenith
#
print('Available commands:\n'
      'say_hi\n'
      'add_numbers\n'
      'exit\n')

while True:
    command = input('Command > ').lower()

    if command == 'say_hi':
        while True:
            name = input('Enter your name (no more than 20 chars.) > ')
            if len(name) > 20 or len(name) == 0:
                print('Name must not be empty and cannot be longer than 20 characters!')
                continue
            break
        print(f'Hello there, {name}!\n')

    elif command == 'add_numbers':
        while True:
            num_1 = int(input('Enter any number (from 1 to 100) > '))
            if num_1 < 1 or num_1 > 100:
                print('Please enter a number from 1 to 100!')
                continue
            break
        while True:
            num_2 = int(input('Enter any number (from 1 to 100) > '))
            if num_2 < 1 or num_2 > 100:
                print('Please enter a number from 1 to 100!')
                continue
            break
        print(f'Sum of {num_1} and {num_2} is {num_1 + num_2}!\n')

    elif command == 'exit':
        print('Goodbye.')
        exit()

    else:
        print(f'Invalid command {command}.')
#

i see that you haven't used elif in ur code, so if u dont know what it does, it stands for else if

if condition:
    ...
else:
    if another_condition:
        ...

can be replaced by elif:

if condition:
    ...
elif another_condition:
    ...
#

u can also try copying the code and running it for yourself, but as u can see, even such a simple thing as having 3 commands gets... quite long and difficult

past sphinx
#

ok

kind zenith
#

but basically i hope u understand now

#

an outer while loop that checks for a command

#

and while loops inside of each command when needed

past sphinx
#

yepp!

kind zenith
#

and also i hope the examples are understandable

rose harborBOT
#
Python help channel closed

This help channel has been closed and it's no longer possible to send messages here. If your question wasn't answered, feel free to create a new post in #1035199133436354600. To maximize your chances of getting a response, check out this guide on asking good questions.