search
HomeBackend DevelopmentPython TutorialIs Python case-sensitive or case-insensitive?

Is Python case-sensitive or case-insensitive?

Aug 31, 2023 pm 02:33 PM
Python keywords are not case sensitive.

Is Python case-sensitive or case-insensitive?

In this article, we will learn whether Python is case-sensitive or case-insensitive.

What is case sensitivity?

If a programming language distinguishes between uppercase and lowercase characters, then it is said to be case-sensitive.

Have you ever tried to mix uppercase and lowercase letters in your password when logging into a website? For example, use TutorialsPOINT instead of tutorialspoint as the password. You may observe that uppercase letters and lowercase letters are considered different and changing case will prevent you from logging in.

This is an example of case sensitivity in action. Case-sensitive programming languages ​​distinguish between uppercase and lowercase letters. Therefore, we must use the exact case of the syntax, since changing case, for example from print to Print, will cause an error.

Is Python a case-sensitive language?

Yes, Python is a case-sensitive programming language. This means it distinguishes between uppercase and lowercase letters. Therefore, in Python we cannot use two terms with the same characters but different cases interchangeably.

Code 1-Error case

The following program throws NameError as error because the print statement is invalid (capital P) −

The Chinese translation of

Example

is:

Example

length = 5
breadth= 2

area_rectangle = length*breadth
Print("Area of Rectangle = ", area_rectangle)

Output

When executed, the above program will generate the following output -

Traceback (most recent call last):
  File "main.py", line 5, in 
    Print("Area of Rectangle = ", area_rectangle)
NameError: name 'Print' is not defined
The Chinese translation of

Code 2-Right Case

is:

Code 2-Right Case

The Chinese translation of

Example

is:

Example

The following program returns the area of ​​a rectangle and is executed without any errors -

length = 5
breadth= 2

area_rectangle = length*breadth
Print("Area of Rectangle = ", area_rectangle)

Output

When executed, the above program will generate the following output -

Area of Rectangle =  10

Have you ever noticed that the difference in upper and lower case produces two different results on the printed output? According to Python syntax, the keyword print should always be lowercase. So when we changed its case in Code 1, Python didn't recognize it, resulting in a NameError. When we fixed the casing in Code 2, we got the expected results.

Why is Python case sensitive?

Python is known as a case-sensitive language because it distinguishes between upper and lower case characters during execution. Even if the characters are the same, Python will treat the two terms as different when case changes. If we try to retrieve the value using different case, we will get an error.

The fundamental reason why Python is built this way is that it has applicability in various fields. We do not want to limit the number of identifiers and symbols that can be used, so case sensitivity is allowed. In fact, most high-level programming languages, such as Java, C, C++, and JavaScript, are case-sensitive.

Variable naming conventions in Python: When should you use uppercase or lowercase?

When writing Python code, we need to follow specific variable naming conventions. These are optional, but they make our code clearer and readable.

  • To improve readability, variable and function names should use lowercase letters and be separated by underscores. For example, input_number = 10.

  • Package and module names should also use lowercase letters. For example, import math.

  • The first letter of each word in the class name should be capitalized. They should not be separated by underscores. For example, ExampleClass.

  • Constants should be all uppercase and use underscore to separate words. For example, PI = 3.1416.

The translation of

NOTE

is:

NOTE

The above naming conventions are highly recommended for good coding practice, but please note that not following them at all will not result in any errors.

In Python, How do you ignore cases?

In most cases, the username used to log into the website is not case-sensitive. If my username is tutorials−point. Even if I enter Tutorials−Point or TUTORIALS−POINT, I should be able to log in. How can we force Python to ignore case when checking equality? To change the case of a string, we can utilize Python’s .upper() and .lower() functions.

  • upper() − This function converts all characters in the specified string to uppercase.

  • lower() − This function converts all characters in the specified string to lowercase.

Suppose we need to create a login page where the password is case-sensitive but the username is not case-sensitive. We will take the username and password entered by the user, convert the username to uppercase (or lowercase), and compare it to the desired username, which is also converted to uppercase (or lowercase). We don't need to convert the password to uppercase or lowercase as it is case sensitive.

Python will check if the username matches by characters only, ignoring the case of the input and expected strings. Password checking, on the other hand, will include character and case matching. Let's put this into code -

Example

的中文翻译为:

示例

下面的程序减慢了区分大小写和不区分大小写之间的差异 -

input_username = "Tutorials-Point"
gvn_username = "tutorials-point"

input_password = "sampleP@SSword"
gvn_password = "sampleP@SSword"

# here we are converting the input_username into lowercase  
print("Case 1: Case Ignored(case-insensitive)")
if (input_username.lower() == gvn_username.lower() and input_password == gvn_password):
    print("You are logged in Successfully!!")
else:
    print("Incorrect Username or Password")

print()

# here we are directly checking whether the input_username and password
# are equal to the gvn_username and gvn_password
print("Case 2: Case Not Ignored(case-sensitive)")
if (input_username == gvn_username and input_password == gvn_password):
    print("You are logged in Successfully!!")
else:
    print("Incorrect Username or Password")

输出

在执行上述程序时,将生成以下输出 

Case 1: Case Ignored(case-insensitive)
You are logged in Successfully!!

Case 2: Case Not Ignored(case-sensitive)
Incorrect Username or Password

案例1中,通过使用.lower()函数,忽略了用户名的大小写。因此,即使用户输入的用户名和记录中的用户名的大小写不同,登录仍然成功。在案例2中,我们不使用.lower()或.upper()方法。因此,大小写不被忽略,相等性检查考虑了两个用户名的大小写。由于两个用户名的大小写不同,登录失败。

NOTE

的翻译为:

注意

我们在上面的示例中简化了登录问题,假设只有一个有效的用户名和密码组合。我们没有使用.lower().upper()来忽略密码的大小写,因为密码始终区分大小写

结论

我们希望你不再对Python大小写敏感的最重要方面感到困惑。你现在熟悉了一些良好的Python大小写敏感的命名规范。你现在明白了在Python中如何忽略大小写进行大小写不敏感的字符串比较。

The above is the detailed content of Is Python case-sensitive or case-insensitive?. For more information, please follow other related articles on the PHP Chinese website!

Statement
This article is reproduced at:tutorialspoint. If there is any infringement, please contact admin@php.cn delete
How do you create multi-dimensional arrays using NumPy?How do you create multi-dimensional arrays using NumPy?Apr 29, 2025 am 12:27 AM

Create multi-dimensional arrays with NumPy can be achieved through the following steps: 1) Use the numpy.array() function to create an array, such as np.array([[1,2,3],[4,5,6]]) to create a 2D array; 2) Use np.zeros(), np.ones(), np.random.random() and other functions to create an array filled with specific values; 3) Understand the shape and size properties of the array to ensure that the length of the sub-array is consistent and avoid errors; 4) Use the np.reshape() function to change the shape of the array; 5) Pay attention to memory usage to ensure that the code is clear and efficient.

Explain the concept of 'broadcasting' in NumPy arrays.Explain the concept of 'broadcasting' in NumPy arrays.Apr 29, 2025 am 12:23 AM

BroadcastinginNumPyisamethodtoperformoperationsonarraysofdifferentshapesbyautomaticallyaligningthem.Itsimplifiescode,enhancesreadability,andboostsperformance.Here'showitworks:1)Smallerarraysarepaddedwithonestomatchdimensions.2)Compatibledimensionsare

Explain how to choose between lists, array.array, and NumPy arrays for data storage.Explain how to choose between lists, array.array, and NumPy arrays for data storage.Apr 29, 2025 am 12:20 AM

ForPythondatastorage,chooselistsforflexibilitywithmixeddatatypes,array.arrayformemory-efficienthomogeneousnumericaldata,andNumPyarraysforadvancednumericalcomputing.Listsareversatilebutlessefficientforlargenumericaldatasets;array.arrayoffersamiddlegro

Give an example of a scenario where using a Python list would be more appropriate than using an array.Give an example of a scenario where using a Python list would be more appropriate than using an array.Apr 29, 2025 am 12:17 AM

Pythonlistsarebetterthanarraysformanagingdiversedatatypes.1)Listscanholdelementsofdifferenttypes,2)theyaredynamic,allowingeasyadditionsandremovals,3)theyofferintuitiveoperationslikeslicing,but4)theyarelessmemory-efficientandslowerforlargedatasets.

How do you access elements in a Python array?How do you access elements in a Python array?Apr 29, 2025 am 12:11 AM

ToaccesselementsinaPythonarray,useindexing:my_array[2]accessesthethirdelement,returning3.Pythonuseszero-basedindexing.1)Usepositiveandnegativeindexing:my_list[0]forthefirstelement,my_list[-1]forthelast.2)Useslicingforarange:my_list[1:5]extractselemen

Is Tuple Comprehension possible in Python? If yes, how and if not why?Is Tuple Comprehension possible in Python? If yes, how and if not why?Apr 28, 2025 pm 04:34 PM

Article discusses impossibility of tuple comprehension in Python due to syntax ambiguity. Alternatives like using tuple() with generator expressions are suggested for creating tuples efficiently.(159 characters)

What are Modules and Packages in Python?What are Modules and Packages in Python?Apr 28, 2025 pm 04:33 PM

The article explains modules and packages in Python, their differences, and usage. Modules are single files, while packages are directories with an __init__.py file, organizing related modules hierarchically.

What is docstring in Python?What is docstring in Python?Apr 28, 2025 pm 04:30 PM

Article discusses docstrings in Python, their usage, and benefits. Main issue: importance of docstrings for code documentation and accessibility.

See all articles

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

SecLists

SecLists

SecLists is the ultimate security tester's companion. It is a collection of various types of lists that are frequently used during security assessments, all in one place. SecLists helps make security testing more efficient and productive by conveniently providing all the lists a security tester might need. List types include usernames, passwords, URLs, fuzzing payloads, sensitive data patterns, web shells, and more. The tester can simply pull this repository onto a new test machine and he will have access to every type of list he needs.

WebStorm Mac version

WebStorm Mac version

Useful JavaScript development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

Dreamweaver Mac version

Dreamweaver Mac version

Visual web development tools

Atom editor mac version download

Atom editor mac version download

The most popular open source editor