Jordan
Jordan

Reputation: 1

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)

Upvotes: 0

Views: 66

Answers (3)

EricC
EricC

Reputation: 11

Move the isalpha() to the if statement:

    student_name = input('Enter student name: ')

    if student_name.isalpha():

Upvotes: 1

SShah
SShah

Reputation: 1082

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.

Upvotes: 1

Pintang
Pintang

Reputation: 438

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)

Upvotes: 2

Related Questions