Python- Day7- Variables

Nidhi Ashtikar
7 min readAug 7, 2024

--

We have done some projects in the past but some of us have understood and were able to do those projects, It must be difficult for a few of us, So I am trying to get that issue resolved., so that we all will be on the same track and we must enjoy our learning journey.
Without Learning A B C D we cannot understand Apple as Apple, I am keeping things simple and starting all over from Basic to advanced.

Running Python Scripts:

  • Python scripts have a .py extension.
  • The editor runs the file through the Python interpreter.
  • The interpreter reads the program and executes commands, such as print()

Syntax Highlighting:

  • The editor visually differentiates parts of the code (e.g., functions, strings).
  • This feature helps in writing and understanding programs.

Using Variables:

  • Variables store data values in a program.

Example:

message = "Hello Python world!"
print(message)
  • The variable message holds the text "Hello Python world!".

Updating Variables:

  • Variables can be reassigned new values.

Example :

message = "Hello Python Crash Course world!"
print(message)
  • The program can print different messages by changing the variable’s value.

Naming and Using Variables:

Naming Rules:

Variable names can include letters, numbers, and underscores.
They must start with a letter or an underscore, not a number.

Example: message_1 is valid, but 1_message is not.

Spaces and Underscores:

Spaces are not allowed in variable names.
Use underscores to separate words in a variable name.

Example: greeting_message is valid, but greeting message is not.

Avoid Keywords and Function Names:

Do not use Python keywords or built-in function names as variable names.

Example: Avoid using print as a variable name.

Descriptive Names:

Variable names should be short yet descriptive.

Examples: name is better than n, student_name is better than s_n, and name_length is better than length_of_persons_name.

Avoid Confusing Characters:

Be cautious with lowercase l and uppercase O as they can be confused with the numbers 1 and 0.

Best Practices:

  • Use lowercase letters for variable names at this stage.
  • Uppercase letters have special meanings in variable names, which will be discussed in later chapters.

Avoiding Name Errors When Using Variables :

Mistakes are Common: All programmers make mistakes regularly.

Responding to Errors: Efficient error handling is crucial for good programmers.

Purposeful Error Example: Example code with an intentional error:

message = "Hello Python Crash Course reader!"
print(mesage) # Misspelled variable name

Tracebacks:

  • When an error occurs, Python provides a traceback.
  • A traceback helps identify where the error occurred in the code.

Example Traceback:

  • Error message example:
Traceback (most recent call last):
File "hello_world.py", line 2, in <module>
print(mesage)
NameError: name 'mesage' is not defined. Did you mean: 'message'?

Interpreting Tracebacks: Indicates the file and line number where the error occurred.
Provides the type of error (e.g., NameError) and suggests corrections.

Common Errors: Name errors usually result from misspelling variable names or not defining them.

Consistent Naming: Ensure variable names are spelled consistently throughout the code.

Typo Example: Correctly spelled code runs successfully:

mesage = "Hello Python Crash Course reader!"
print(mesage)

Simple Typos:

  • Many errors are single-character typos.
    Experienced programmers also spend time fixing such errors.

Learning from Mistakes:

  • Recognize that errors are part of the learning process.
    Maintain a positive attitude and move on when errors occur.

Variables Are Labels:

Concept of Variables: Variables can be considered labels assigned to values, rather than boxes storing values.

Internal Representation: Understanding the accurate representation of variables helps in identifying unexpected behavior in code.

Practice Programming: The best way to learn new programming concepts is through practice and experimentation.

File Naming Conventions: Use standard Python conventions for filenames: lowercase letters and underscores (e.g., simple_message.py, simple_messages.py).

Assign a message to a variable, and print that message. Then change the value of the variable to a new message, and print the new message.

# simple_messages.py

message = "This is the first message."
print(message)

message = "This is the new message."
print(message)

Strings :

Definition: A string is a series of characters enclosed in quotes.
Strings can use single or double quotes.
Example: "This is a string." or 'This is also a string.'

Quotes Flexibility: Allows inclusion of quotes and apostrophes within strings.
Example: 'I told my friend, "Python is my favorite language!"'

Changing Case: Use methods to change the case of a string.

  • Example: name.title() converts "ada lovelace" to "Ada Lovelace".
  • Other methods: name.upper( ) (uppercase) and name.lower() (lowercase).

Methods Explanation: Methods are actions Python can perform on data, indicated by a dot (.) followed by parentheses.

  • Example: name.title(), name.upper(), name.lower().\

Using Variables in Strings: Use f-strings to insert variables into strings.

  • Syntax: f"{variable}".

Example :

first_name = "ada"
last_name = "lovelace"
full_name = f"{first_name} {last_name}"
print(full_name)

Formatted Strings: f-strings format strings by replacing variable names with their values.

  • Example: f"Hello, {full_name.title()}!"
    results in "Hello, Ada Lovelace!".

Assigning Messages to Variables: You can assign a composed message to a variable for simplicity.

Example :

message = f"Hello, {full_name.title()}!"
print(message)

Adding Whitespace to Strings with Tabs or Newlines :

Definition : Whitespace: Nonprinting characters like spaces, tabs, and end-of-line symbols.

Tabs: Use \t to add a tab.

  • Example: print("\tPython") → Output: Python

Newlines: Use \n to add a newline.

  • Example: print("Languages:\nPython\nC\nJavaScript")
Languages:
Python
C
JavaScript

Combining Tabs and Newlines: Combine \n and \t for formatting.

  • Example: print("Languages:\n\tPython\n\tC\n\tJavaScript")
Languages:
Python
C
JavaScript

Whitespace helps organize output for better readability.

Stripping Whitespace :

Extra whitespace can make strings look similar to humans but different to programs.
Whitespace matters when comparing strings, such as user logins.

Removing Whitespace: Use rstrip() to remove whitespace from the right.

favorite_language = 'python '
favorite_language = favorite_language.rstrip() # 'python'

Permanent Removal: To remove whitespace permanently, reassign the stripped value to the variable.

Other Methods:

  • lstrip(): Removes whitespace from the left.
  • strip(): Removes whitespace from both sides.
favorite_language = ' python '
favorite_language = favorite_language.strip() # 'python'

Stripping functions are useful for cleaning up user input before storage.

Removing Prefixes :

Common task: Remove a prefix from a string (e.g., https:// from a URL).

Using removeprefix(): Method: string.removeprefix(prefix).

nostarch_url = 'https://nostarch.com'
simple_url = nostarch_url.removeprefix('https://')
# Result: 'nostarch.com'

Method Behavior: removeprefix() does not change the original string.

  • Assign the result to a new variable or reassign it to the original variable to keep the updated value.

Browsers may use methods like removeprefix() to display URLs without the prefix.

Avoiding Syntax Errors with Strings:

Syntax errors occur when Python cannot recognize a section of code as valid.
Incorrect use of quotes, such as mismatched or missing quotes.

Correctly uses double quotes to include an apostrophe:

message = "One of Python's strengths is its diverse community."
print(message)

Output: One of Python's strengths is its diverse community.'

Incorrectly uses single quotes with an apostrophe:

message = 'One of Python's strengths is its diverse community.'
print(message)

Error: ‘SyntaxError: unterminated string literal'

Error Detection: Syntax errors often occur due to mismatched quotes or incorrect syntax.
Your editor’s syntax highlighting can help identify these errors.

Troubleshooting: Syntax errors can be frustrating and less specific; check for mismatched quotes or other syntax issues.

Exercise :

Personal Message: Use a variable to represent a person’s name, and print a message to that person. Your message should be simple, such as, “Hello Eric, would you like to learn some Python today?”

# personal_message.py
name = "Eric"
print(f"Hello {name}, would you like to learn some Python today?")

Name Cases : Use a variable to represent a person’s name, and then print that person’s name in lowercase, uppercase, and title case.

# name_cases.py
name = "Eric"
print(name.lower()) # lowercase
print(name.upper()) # uppercase
print(name.title()) # title case

Famous Quote : Find a quote from a famous person you admire. Print the quote and the name of its author. Your output should look something like the following, including the quotation marks:
Albert Einstein once said, “A person who never made a mistake never tried anything new.”

# famous_quote.py
print('Albert Einstein once said, “A person who never made a mistake never tried anything new.”')

Famous Quote 2 : Repeat Exercise 2–5, but this time, represent the famous person’s name using a variable called famous_person. Then compose your message and represent it with a new variable called message. Print your message.

# famous_quote_2.py
famous_person = "Albert Einstein"
message = f'{famous_person} once said, “A person who never made a mistake never tried anything new.”'
print(message)

Stripping Names : Use a variable to represent a person’s name, and include some whitespace characters at the beginning and end of the name. Make sure you use each character combination, “\t” and “\n”, at least once. Print the name once, so the whitespace around the name is displayed. Then print the name using each of the three stripping functions, lstrip(), rstrip(), and strip().

# stripping_names.py
name = "\t\n Eric \n\t"
print(f"Original name: '{name}'")
print(f"After lstrip: '{name.lstrip()}'")
print(f"After rstrip: '{name.rstrip()}'")
print(f"After strip: '{name.strip()}'")

File Extensions : Python has a removesuffix() method that works exactly like removeprefix(). Assign the value ‘python_notes.txt’ to a variable called filename. Then use the removesuffix() method to display the filename without the file extension, like some file browsers do.

# file_extensions.py
filename = 'python_notes.txt'
print(filename.removesuffix('.txt'))

If you found this guide helpful then do click on 👏 the button.

Follow for more Learning like this 😊

If there’s a specific topic you’re curious about, feel free to drop a personal note or comment. I’m here to help you explore whatever interests you!

Thanks for spending your valuable time learning to enhance your knowledge!

--

--

Nidhi Ashtikar
Nidhi Ashtikar

Written by Nidhi Ashtikar

Experienced AWS DevOps professional with a passion for writing insightful articles.

No responses yet