search
HomeBackend DevelopmentPython TutorialPython hourglass graph drawing: How to avoid variable undefined errors?

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!

Statement
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
Python's Hybrid Approach: Compilation and Interpretation CombinedPython's Hybrid Approach: Compilation and Interpretation CombinedMay 08, 2025 am 12:16 AM

Pythonusesahybridapproach,combiningcompilationtobytecodeandinterpretation.1)Codeiscompiledtoplatform-independentbytecode.2)BytecodeisinterpretedbythePythonVirtualMachine,enhancingefficiencyandportability.

Learn the Differences Between Python's 'for' and 'while' LoopsLearn the Differences Between Python's 'for' and 'while' LoopsMay 08, 2025 am 12:11 AM

ThekeydifferencesbetweenPython's"for"and"while"loopsare:1)"For"loopsareidealforiteratingoversequencesorknowniterations,while2)"while"loopsarebetterforcontinuinguntilaconditionismetwithoutpredefinediterations.Un

Python concatenate lists with duplicatesPython concatenate lists with duplicatesMay 08, 2025 am 12:09 AM

In Python, you can connect lists and manage duplicate elements through a variety of methods: 1) Use operators or extend() to retain all duplicate elements; 2) Convert to sets and then return to lists to remove all duplicate elements, but the original order will be lost; 3) Use loops or list comprehensions to combine sets to remove duplicate elements and maintain the original order.

Python List Concatenation Performance: Speed ComparisonPython List Concatenation Performance: Speed ComparisonMay 08, 2025 am 12:09 AM

ThefastestmethodforlistconcatenationinPythondependsonlistsize:1)Forsmalllists,the operatorisefficient.2)Forlargerlists,list.extend()orlistcomprehensionisfaster,withextend()beingmorememory-efficientbymodifyinglistsin-place.

How do you insert elements into a Python list?How do you insert elements into a Python list?May 08, 2025 am 12:07 AM

ToinsertelementsintoaPythonlist,useappend()toaddtotheend,insert()foraspecificposition,andextend()formultipleelements.1)Useappend()foraddingsingleitemstotheend.2)Useinsert()toaddataspecificindex,thoughit'sslowerforlargelists.3)Useextend()toaddmultiple

Are Python lists dynamic arrays or linked lists under the hood?Are Python lists dynamic arrays or linked lists under the hood?May 07, 2025 am 12:16 AM

Pythonlistsareimplementedasdynamicarrays,notlinkedlists.1)Theyarestoredincontiguousmemoryblocks,whichmayrequirereallocationwhenappendingitems,impactingperformance.2)Linkedlistswouldofferefficientinsertions/deletionsbutslowerindexedaccess,leadingPytho

How do you remove elements from a Python list?How do you remove elements from a Python list?May 07, 2025 am 12:15 AM

Pythonoffersfourmainmethodstoremoveelementsfromalist:1)remove(value)removesthefirstoccurrenceofavalue,2)pop(index)removesandreturnsanelementataspecifiedindex,3)delstatementremoveselementsbyindexorslice,and4)clear()removesallitemsfromthelist.Eachmetho

What should you check if you get a 'Permission denied' error when trying to run a script?What should you check if you get a 'Permission denied' error when trying to run a script?May 07, 2025 am 12:12 AM

Toresolvea"Permissiondenied"errorwhenrunningascript,followthesesteps:1)Checkandadjustthescript'spermissionsusingchmod xmyscript.shtomakeitexecutable.2)Ensurethescriptislocatedinadirectorywhereyouhavewritepermissions,suchasyourhomedirectory.

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

Safe Exam Browser

Safe Exam Browser

Safe Exam Browser is a secure browser environment for taking online exams securely. This software turns any computer into a secure workstation. It controls access to any utility and prevents students from using unauthorized resources.

SublimeText3 Linux new version

SublimeText3 Linux new version

SublimeText3 Linux latest version

MinGW - Minimalist GNU for Windows

MinGW - Minimalist GNU for Windows

This project is in the process of being migrated to osdn.net/projects/mingw, you can continue to follow us there. MinGW: A native Windows port of the GNU Compiler Collection (GCC), freely distributable import libraries and header files for building native Windows applications; includes extensions to the MSVC runtime to support C99 functionality. All MinGW software can run on 64-bit Windows platforms.

DVWA

DVWA

Damn Vulnerable Web App (DVWA) is a PHP/MySQL web application that is very vulnerable. Its main goals are to be an aid for security professionals to test their skills and tools in a legal environment, to help web developers better understand the process of securing web applications, and to help teachers/students teach/learn in a classroom environment Web application security. The goal of DVWA is to practice some of the most common web vulnerabilities through a simple and straightforward interface, with varying degrees of difficulty. Please note that this software

MantisBT

MantisBT

Mantis is an easy-to-deploy web-based defect tracking tool designed to aid in product defect tracking. It requires PHP, MySQL and a web server. Check out our demo and hosting services.