0% found this document useful (0 votes)
11 views8 pages

Python Basics: Syntax and Operators

The document discusses common syntax errors in Python related to string literals and the use of operators. It explains the difference between the '*' and '**' operators, the impossibility of displaying integers with leading zeros, and the distinction between string and integer types. Additionally, it includes programming exercises demonstrating basic operations, formatted output, and suggestions for improving code robustness.

Uploaded by

stephensoncory56
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
11 views8 pages

Python Basics: Syntax and Operators

The document discusses common syntax errors in Python related to string literals and the use of operators. It explains the difference between the '*' and '**' operators, the impossibility of displaying integers with leading zeros, and the distinction between string and integer types. Additionally, it includes programming exercises demonstrating basic operations, formatted output, and suggestions for improving code robustness.

Uploaded by

stephensoncory56
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd

Programming Assignment Unit 1

PART 1

A. If you are trying to print your name, what happens if you leave out one of the quotation

marks or both, and why?

1. >>> print ("cory)

Output:

SyntaxError: unterminated string literal (detected at line 1)

The code above produced a syntax error that indicates unterminated string literal. As the rule of

python language states, all strings must be enclosed in quotation (“ ” or ‘’)

Eg

Print (“cory”)

Screenshot:

2. >>> print (cory)

Output:

print (cory)

NameError: name 'cory' is not defined


The above error occurred because without the quotations, python (py) does not recognize “cory”

as a string . In some situations, py see it to be a variable therefore treats it as such however, the

error “NameError: name 'cory' is not defined” returns because cory has not been defined

therefore it is not recognized by py.

Screenshot:

3. >>> print (cory")

Output:

SyntaxError: unterminated string literal (detected at line 1)

This ha been explained in number 1 above.

B. What is the difference between * and ** operators in Python? Explain with the help of

an example.

The “*” known as the multiplication is an operator that is used to perform multiplication

arithmetic in py where as “**” known as exponentiation is used for exponentiation of numbers

Mathematical representation Python representation

34 >>>3**4
= 3x3x3x3 Output

= 81 81

C. In Python, is it possible to display an integer like 09? Justify your answer.

It is not possible this is because py does not retain leading zero thus it is not meaningful for

numeric calculations therefore, py will return a syntax error if this happens.

Screenshot:

Code

>>> print 09

D. Run the commands type('67') and type(67). What is the difference in the output and

why?

>>> type (‘67’)

Output:
<class 'str'>

The above code is used to show the type of value the interpreter displays. In this case, the class

off value been output is a string. This is due to the double quote therefore (‘67’) is a string. On

the other hand,

>>>type (67)

Output:

<class 'int'>

the interpreter recognizes this class of value as an integer therefore (67) is an integer

Screenshot:

Part 2

Write a Python program for each of the following questions a to d.


a. To multiply your age by 2 and display it. For example, if your age is 16, so 16 * 2 = 32

Code:

#This program will multipy me age by 2

>>>26*2

Output

52

Screenshot:

b. Display the name of the city, country, and continent you are living in.

Code:

#This program will display the name of the city, country, and continent I am living in.

print ('City: Accra','' ,'','Country: Ghana','','','Continent: Africa')

Output

City: Accra Country: Ghana Continent: Africa

Screenshot
c. To display the examination schedule (i.e., the starting and the ending day) of

this term.

Code:

>>># This program display the examination schedule (i.e., the starting and the ending

day) of this term.

>>>print ('Examination schedule','','starting : Jan 9 2025','','ending : Jan 12 2025')

Output:

Examination schedule starting : Jan 9 2025 ending : Jan 12 2025

Screenshot:

d. Display the temperature of your country on the day the assignment is attempted by you

Code:

>>>print ('County: Ghana','','Temp: 28 degree celsius')

Output:

County: Ghana Temp: 28 degree Celsius

Screenshot:
These exercises showcase Python's ease of use for performing mathematical operations,

string manipulations, and formatted output. While the solutions effectively fulfill the

tasks, adopting more modern formatting techniques. Additionally, learning to incorporate

error handling or interactive input would make the programs more dynamic and robust.

References:
 Python Software Foundation. (n.d.). NameError. In the Python Standard Library: Built-in

exceptions. Retrieved November 18, 2024, from

[Link]

 Downey, A. (2015). Think Python: How to think like a computer scientist. Green Tree

Press. [Link]

Common questions

Powered by AI

Python offers distinct advantages for tasks involving mathematical operations and string manipulation due to its straightforward syntax and extensive standard library. Assignments demonstrate Python's capability to perform complex calculations (e.g., exponentiation with '**') and flexible string handling with minimal code. Python's readability and the ability to handle both numbers and strings seamlessly make it suitable for a wide range of applications, from simple scripts to complex data analysis .

In Python, attempting to print a string with improperly closed quotation marks results in syntax errors. Leaving out both quotation marks, as in print(cory), Python interprets 'cory' as a variable name rather than a string, leading to a NameError because 'cory' is undefined . In contrast, leaving only one quotation mark, as in print("cory), triggers a SyntaxError due to an unterminated string literal, since Python requires strings to be enclosed in both starting and ending quotation marks .

Executing type('67') in Python outputs <class 'str'> because the value is enclosed in quotes, making it a string. Conversely, type(67) outputs <class 'int'> since it's a numeric value without quotes, recognized as an integer by Python. The difference arises from how Python interprets quotes as string delimiters .

Integer '67' and string "67" are recognized differently in Python due to their inherent data types. As an integer, '67' can participate in arithmetic operations, such as addition or multiplication. Conversely, the string "67" is used in context with text manipulations like concatenation. The string type interprets numerical digits as characters, thus cannot be directly incorporated in numerical calculations without conversion .

Python's robust exception handling system, including specific errors like NameError, enhances its effectiveness as a programming language by providing clear feedback on what went wrong, facilitating debugging. For beginners, such precise error messages align closely with logical mistakes made in early learning stages, thereby accelerating the learning process. Experienced programmers benefit from Python's structured error feedback to quickly identify and resolve complex issues, improving development efficiency and software quality .

Python cannot display integers with leading zeros like '09' because it does not recognize them as meaningful for numeric calculations; leading zeros in integers are not retained, triggering a syntax error. This is because leading zeros were originally used to signal octal literals, which is no longer supported in Python 3.x, leading to a syntax error when a number with leading zero is provided .

In Python, the '*' operator is used for multiplication arithmetic, meaning it multiplies values together, e.g., 3 * 4 = 12. On the other hand, '**' is the exponentiation operator, used to raise a number to the power of another, e.g., 3 ** 4 = 3 * 3 * 3 * 3 = 81 .

Python's strict enforcement of string representation, such as requiring correct and complete quotation marks, enhances code reliability by preventing ambiguous syntax that could lead to runtime errors. By mandating clear declaration of strings and distinguishing them from variables, Python minimizes the risk of logic errors and facilitates accurate debugging. These conventions ensure that programs execute as intended, with errors clearly flagged, improving both code maintainability and developer productivity .

Python handles incorrect syntax related to variable names by raising exceptions such as NameError when a variable is referenced that hasn't been assigned a value. This typically occurs if a name is used without being declared or if it is misspelled. If the syntax structure does not adhere to Python's naming conventions or if the code logic does not define the variable, a NameError is produced, as Python cannot find a definition for the unknown name .

To enhance string handling in Python, adopting modern formatting techniques such as f-strings can be suggested. F-strings allow for simpler formatting by embedding expressions within string literals using curly braces and the prefix 'f', leading to improved readability and efficiency over older methods like '%' formatting and 'str.format()' . Incorporating error handling and user input also increases program robustness and interactivity, making them more dynamic .

You might also like