0% found this document useful (0 votes)
14 views4 pages

Python Commands Quick Reference Guide

This document serves as a quick guide to Python commands and syntax, covering input and output statements, variable assignments, and various operators. It also explains control structures such as conditional statements, loops, functions, and list operations, along with file handling methods. The guide highlights key differences between Python and other programming languages, particularly in list indexing.

Uploaded by

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

Python Commands Quick Reference Guide

This document serves as a quick guide to Python commands and syntax, covering input and output statements, variable assignments, and various operators. It also explains control structures such as conditional statements, loops, functions, and list operations, along with file handling methods. The guide highlights key differences between Python and other programming languages, particularly in list indexing.

Uploaded by

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

Quick Guide to Python Commands and Syntax

Input Statements:

Output Statements:

The variable x = 75.18

The value of y is: 750

The name of this course is: Calculus II

x = 75.2, y = 750, course is Calculus II

Arithmetic, Comparison, and Logical Operators:

Arithmetic Operators Comparison Operators Logical Operators


Addition + Equal == and
Subtraction  Not Equal != or
Multiplication * Less Than < not
Division / Greater Than >
Power ** Less Than or Equal To <=
Modulo % Greater Than or Equal To >=
Conditional Statements:

if Condition1:
# Python Commands to execute if Condition1 is TRUE
elif Condition2:
# Python Commands to execute if Condition1 is FALSE
# and Condition2 is TRUE
elif Condition3:
# Python Commands to execute if Condition1 is FALSE
# and Condition2 is FALSE
# and Condition3 is TRUE
else:
# Python Commands to execute if Conditions 1-3 are FALSE

For Loops:

Assume variable N is defined (an integer)


for k in range(N):
# Python Commands to execute a total of N times
# Counter index, k, starts at 0 and increments to N-1

Assume List is a list of numerical values


for k in List:
# Counter index, k, takes on each value in List starting
# with the first and ending with the last entry in List

While Loops:

while Condition:
# Python Commands will execute again and again as long as
# Condition is true

Functions:

Basic Syntax:

Calling a Function or Functions from another module:


Create another module called [Link] (see below) that imports any necessary functions then
calls the function(s). Run [Link] and respond to prompts.
Lists:

In Python, the first entry in a list or array is indexed as 0.


This is different from MATLAB where the first entry in an array
is indexed as 1!

Creating 1-d Lists and 2-d Lists:

List_1d = [2, 7, 6, 42, 73]

List_2d = [[1, 5, 7], [2, 4, 6], [10, 14, 18]]

Suppose L1 is a 1-d List of numbers with at least 5 values

L1[0] # 1st entry in the list, L1

L1[3] # 4th entry in the list, L1

L1[1:4] # Pulls out 2nd 3rd, and 4th entries from List, L1

L1[2] = 5 # Replaces the 3rd entry of list, L1, with a 5

N = len(L1) # N = the number of entries in list, L1

[Link](12) # Puts a 12 at the end of the list, L1

del L1[1] # Deletes 2nd entry in the list, L1

Suppose L2 is a 2-d List of numbers with 5 rows and 3 columns

L2[1][2] # Entry in row 2, column 3 of list, L2


Reading and Writing to Files:

Open a file to read (r), or write (w), or read and write (w+):

fid = open('[Link]','r')

fid = open('[Link]','w')

fid = open('[Link]','w+')

Read from a file :

List = [Link]()

OR

for line in fid:

Write to a file:

[Link](<string to write>) #Can only write strings!

Close the file:

[Link]()

Common questions

Powered by AI

Functions in Python provide numerous advantages, including code reusability, abstraction, and improved readability. By encapsulating tasks within functions, developers can reuse code across different parts of a program without duplicating logic. This supports abstraction by hiding complex implementations within easily understandable function calls. Additionally, defining functions enhances modularity by breaking a program into separate, logically independent modules, making it easier to manage, debug, and test individual components without affecting others. These principles are foundational for developing scalable and maintainable software projects .

Python's logical operators ('and', 'or', 'not') are useful for constructing complex conditional statements. For instance, in a customer eligibility program, you might check if a person is eligible for a discount using 'if age >= 65 and is_member:'. In this scenario, the 'and' operator combines two conditions: the person's age and membership status. The program will execute the block under this condition only if both conditions are true, influencing flow by ensuring stricter criteria are met before applying the discount .

In Python, list indexing starts at 0, meaning the first element of a list is accessed using the index 0. For example, accessing the first element of the list L1 would use 'L1[0]'. In contrast, MATLAB indexes lists (arrays) starting at 1. This difference is significant in programming when translating code or algorithms from MATLAB to Python, as it requires altering index references to accommodate this base difference during list manipulation. It's crucial for avoiding off-by-one errors and ensuring that data is accessed or modified correctly in loops or functions involving iterative processes .

A 'while' loop is preferred over a 'for' loop when the number of iterations is not known beforehand and the loop needs to continue until a specific condition changes. For example, 'while' loops are optimal for reading data until reaching an 'end-of-file' marker or for waiting for an event to occur. In 'while' loops, the condition determines whether or not to continue executing the loop's block. If the condition evaluates to True, the loop's body will execute; if False, the loop will terminate. This makes 'while' loops suitable for situations where iterations depend directly on the fulfillment of certain conditions .

Python's list slicing operation is used to extract a specific section of a list by specifying start and end indices in square brackets, like 'list[start:end]'. The slice includes the element at the start index but excludes the element at the end index. Performing 'L1[1:4]' on the list L1 = [3, 6, 9, 12, 15] would yield the sublist [6, 9, 12], since these are the elements at indices 1, 2, and 3 .

The modulo operator (%) in Python returns the remainder of a division operation. For example, given an expression like '7 % 3', the result would be 1, because when 7 is divided by 3, the remainder is 1. A practical use case for the modulo operator in a loop is to determine if a number is even or odd within an iteration. For instance, in a loop iterating over a range, you might use 'if k % 2 == 0' to execute certain commands only when k is even .

Conditional statements in Python use 'if', 'elif', and 'else' keywords to execute specific code blocks based on logical conditions. An 'if' statement tests a condition and executes the associated block if True. 'Elif' allows testing further conditions if the initial if condition is False, effectively functioning as further checks; 'else' provides a default action if none of the preceding conditions is True. For example, a flow controlling temperature feedback might have 'if temperature < 0', 'elif temperature <= 100', and 'else' conditions to respectively manage freezing, normal, and boiling scenarios, executing appropriate responses based on the logical outcome .

To read and print each line from a file in Python, you can use a 'for' loop combined with the 'open' function. You first open the file using 'fid = open('FileName.txt','r')' to initiate reading mode. Then iterate through each line with 'for line in fid:', printing each line within the loop using 'print(line)'. Finally, it's important to close the file with 'fid.close()' to free up resources .

List manipulation in Python involves modifying lists using operations like 'append', 'delete', and 'indexing'. 'Append' adds elements to the end of the list, useful when gathering data incrementally. For example, 'L1.append(12)' adds 12 to L1. 'Delete' removes elements, which is crucial when cleansing data; 'del L1[1]' removes the second item in L1. Indexing retrieves elements, allowing for specific data access, such as extracting subsets with 'L1[1:4]'. Combined, these operations enable dynamic and flexible data management, essential in applications like data processing, user interaction history tracking, and real-time system monitoring .

A Python function is a block of reusable code designed to perform a single, specific task. Functions are defined using the 'def' keyword, followed by a function name, parameters, and a block of code. To organize and execute functions in a separate module, they must first be defined in that module. You can then import the module in another Python script and call the functions as needed. For example, create a file named 'my_module.py', define a function within it, and then in another file (e.g., 'Main.py'), use 'import my_module' to access and run the function .

You might also like