简体   繁体   中英

How to prevent If statement from converting input to Boolean?

I'm trying to get the user input value from the function ( enter_student_name ) and add it into my dictionary function ( add_student ). But when I print, I get a Boolean value instead of the string that was entered.


Console Example: Enter student name: john

[{'name': True}]

I want it to return [{'name': john}] instead.

students = []

def enter_student_name():
    while True:
        student_name = str.isalpha(input('Enter student name: '))

        if student_name:
        add_student(student_name)
        print(students)
        # enter_student_id()
    else:
        print('Please enter a name only')
        continue


def add_student(name):
    student = {"name": name }
    students.append(student)

str.isalpha() returns true or false if the string is alpha characters. See https://www.tutorialspoint.com/python/string_isalpha.htm

Instead get the value from input, THEN check for alpha characters:

students = []


def enter_student_name():
    while True:
        student_name = input('Enter student name: ')

        if str.isalpha(student_name):
            add_student(student_name)
            print(students)
            # enter_student_id()
        else:
            print('Please enter a name only')
            continue


def add_student(name):
    student = {"name": name }
    students.append(student)

Move the isalpha() to the if statement:

    student_name = input('Enter student name: ')

    if student_name.isalpha():

Just use str instead of str.isalpha , so instead of:

str.isalpha(input('Enter student name: '))

use

str(input('Enter student name: '))

this will convert any given value to string and make it work.

then use an if condition with the isalpha to check whether if the string contains all letters before making it call the add_student(student_name) function call.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM