


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}")
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!

Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

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

Hot Article

Hot Tools

Notepad++7.3.1
Easy-to-use and free code editor

SublimeText3 Chinese version
Chinese version, very easy to use

Zend Studio 13.0.1
Powerful PHP integrated development environment

Dreamweaver CS6
Visual web development tools

SublimeText3 Mac version
God-level code editing software (SublimeText3)

Hot Topics











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 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 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.

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 SpringBoot project default run configuration list in Idea using IntelliJ...

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.

About SpringCloudAlibaba microservices modular development using SpringCloud...

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.
