Home Backend Development Python Tutorial Python hourglass graph drawing: How to avoid variable undefined errors?

Python hourglass graph drawing: How to avoid variable undefined errors?

Apr 01, 2025 pm 06:27 PM
python git

Python hourglass graph drawing: How to avoid variable undefined errors?

Getting started with Python: Draw hourglass graphics and perform input verification

This article will explain how to fix undefined variable errors encountered by a Python novice when writing an hourglass graph drawing program. The goal of the program is to draw an hourglass pattern composed of sym characters based on the integer n and character sym entered by the user. There is a NameError error in the original code, which prompts that sym variable is not defined. Let's analyze and solve this problem.

The original code mainly contains two functions: is_integer_string is used to verify whether the input is an integer, print_hourglass is used to draw the hourglass pattern. However, problems occur when processing user input, resulting in sym variable undefined when the print_hourglass function is called.

The original code tries to read both n and sym using map(int, input().split()) . This assumes that the user enters two integers separated by spaces. But in reality, sym should be a character or string, not an integer. Therefore, map(int, input().split()) throws ValueError exception and sym is not assigned correctly.

The improved code is as follows:

 def is_integer_string(s):
    if not s.isdigit() and (s[0] != '-' or not s[1:].isdigit()):
        return False
    return True

def print_hourglass(n, sym):
    i = 1
    while n >= i * i:
        print(' ' * (i - 1) sym * (i * 2 -1)) # Modify the formula to make the hourglass more symmetrical print(' ' * (i - 1) sym * ((i 1) * 2 -1)) # Modify the formula to make the hourglass more symmetrical i = 2
    while i > 0:
        print(' ' * (i - 1) sym * (i * 2 -1)) # Modify the formula to make the hourglass more symmetrical i -= 2

try:
    n_input = input("Please enter the integer n:")
    if is_integer_string(n_input):
        n = int(n_input)
        sym = input("Please enter the character sym:")
        print_hourglass(n, sym)
    else:
        print("The input n is not an integer")
except ValueError:
    print("Input error, please re-enter")
except Exception as e:
    print(f"Error occurred: {e}")
Copy after login

The improved code first corrected the is_integer_string function so that it can handle negative numbers correctly. More importantly, it processes the inputs of n and sym separately. First read n , verify whether it is an integer, and then read sym to avoid errors caused by map function. In this way, the sym variable gets the correct assignment before print_hourglass function call, thus solving the NameError error. The code also makes more robust error handling of inputs and adds more user-friendly prompts. At the same time, the formula for calculating the number of characters in print_hourglass function was also corrected to make the hourglass graph more symmetric. Finally, a more general except block was added to catch other possible exceptions.

The above is the detailed content of Python hourglass graph drawing: How to avoid variable undefined errors?. For more information, please follow other related articles on the PHP Chinese website!

Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn

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

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

Hot Topics

Java Tutorial
1664
14
PHP Tutorial
1266
29
C# Tutorial
1239
24
PHP and Python: Different Paradigms Explained PHP and Python: Different Paradigms Explained Apr 18, 2025 am 12:26 AM

PHP is mainly procedural programming, but also supports object-oriented programming (OOP); Python supports a variety of paradigms, including OOP, functional and procedural programming. PHP is suitable for web development, and Python is suitable for a variety of applications such as data analysis and machine learning.

Golang vs. Python: Performance and Scalability Golang vs. Python: Performance and Scalability Apr 19, 2025 am 12:18 AM

Golang is better than Python in terms of performance and scalability. 1) Golang's compilation-type characteristics and efficient concurrency model make it perform well in high concurrency scenarios. 2) Python, as an interpreted language, executes slowly, but can optimize performance through tools such as Cython.

Python vs. C  : Learning Curves and Ease of Use Python vs. C : Learning Curves and Ease of Use Apr 19, 2025 am 12:20 AM

Python is easier to learn and use, while C is more powerful but complex. 1. Python syntax is concise and suitable for beginners. Dynamic typing and automatic memory management make it easy to use, but may cause runtime errors. 2.C provides low-level control and advanced features, suitable for high-performance applications, but has a high learning threshold and requires manual memory and type safety management.

The top ten free platform recommendations for real-time data on currency circle markets are released The top ten free platform recommendations for real-time data on currency circle markets are released Apr 22, 2025 am 08:12 AM

Cryptocurrency data platforms suitable for beginners include CoinMarketCap and non-small trumpet. 1. CoinMarketCap provides global real-time price, market value, and trading volume rankings for novice and basic analysis needs. 2. The non-small quotation provides a Chinese-friendly interface, suitable for Chinese users to quickly screen low-risk potential projects.

How to set the default run configuration list of SpringBoot projects in Idea for team members to share? How to set the default run configuration list of SpringBoot projects in Idea for team members to share? Apr 19, 2025 pm 11:24 PM

How to set the SpringBoot project default run configuration list in Idea using IntelliJ...

Python vs. C  : Understanding the Key Differences Python vs. C : Understanding the Key Differences Apr 21, 2025 am 12:18 AM

Python and C each have their own advantages, and the choice should be based on project requirements. 1) Python is suitable for rapid development and data processing due to its concise syntax and dynamic typing. 2)C is suitable for high performance and system programming due to its static typing and manual memory management.

When building a microservice architecture using Spring Cloud Alibaba, do you have to manage each module in a parent-child engineering structure? When building a microservice architecture using Spring Cloud Alibaba, do you have to manage each module in a parent-child engineering structure? Apr 19, 2025 pm 08:09 PM

About SpringCloudAlibaba microservices modular development using SpringCloud...

Laravel vs. Python (with Frameworks): A Comparative Analysis Laravel vs. Python (with Frameworks): A Comparative Analysis Apr 21, 2025 am 12:15 AM

Laravel is suitable for projects that teams are familiar with PHP and require rich features, while Python frameworks depend on project requirements. 1.Laravel provides elegant syntax and rich features, suitable for projects that require rapid development and flexibility. 2. Django is suitable for complex applications because of its "battery inclusion" concept. 3.Flask is suitable for fast prototypes and small projects, providing great flexibility.

See all articles