PuTTY and Python - Operators, Expressions: Difference between pages

From Computer Science at Indiana State University
(Difference between pages)
Jump to navigation Jump to search
m 1 revision imported
 
wiki_previous>Jkinne
 
Line 1: Line 1:
= Quick PuTTY Howto =
Following are terse descriptions for Python3 operators.  For more information, see your Python reading material.


== Download and Install ==
=Operators=
The following are a basic set of operators that most will intuitively know what they do.
* '''Comments:''' <code>#</code> is used to demarcate comments - anything after a # on a line is ignored by the python interpreter.
* '''Arithmetic operators:''' <code>+ - * / //</code>
** Note that / is floating point division (3/2 is 1.5), while // is integer division (3//2 is rounded down to 1).
* '''Assignment operators:''' <code> =</code>
* '''Comparison operators:''' <code> < <= == != >= ></code>
** Note that == tests if two values are equal, != tests if they are not equal (3 != 2 will be True, 3 == 2 will be False).
* '''Logical operators:''' <code>and or not</code>
* '''Membership operators:''' <code>in, not in</code>


Use a web browser to browse to http://www.chiark.greenend.org.uk/~sgtatham/putty/download.html and click on the "putty.exe" link for "Windows on Intel x86". Save the file executable to your desktop (you may have to move it from your downloads directory to your desktop if you use Firefox.) You should then see an icon like:
==More Operators==
The following are more operators.  These may not be obvious.  Some examples are given, but you may need to read through your Python text to understand these.
* '''Arithmetic operators:''' <code>% **</code>
** % is remainder (10 % 3 is 1, 17 % 3 is 2), and ** is exponentiation (10**3 is 1000, 2**3 is 8).
* '''Assignment operators:''' <code> += -= *= /= //= %= **= &= |= ^= >>= <<=</code>
** Each of these is shorthand. For example, <code>x += 3</code> is a shorthand for <code>x = x + 3</code>
* '''Identity operators:''' <code>is, is not</code>
** Tests whether two objects are the same, not just whether the values are the same. For simple variables/expressions, <code>is</code> will be the same as ==, but for lists/tuples/dictionaries <code>is</code> only gives True if the two things being compared are actually the same object (not just the same values).
* '''Bitwise operators:''' <code>& | ^ ~ << >></code>
** These operate on the bits of a number. You need to understand binary before you can understand these. Examples: 12 & 8 evaluates to 8, 12 | 7 evaluates to 15, 12 ^ 8 evaluates to 4, ~7 evaluates to -8 (same as -7-1), 3 << 2 evaluates to 12, 12 >> 1 evaluates to 6.
* '''Brackets:''' <code>[ : ]</code>
** Square brackets are used to pull individual elements from strings, lists, tuples, and dictionaries.  If <code>A = (1, 2, 'hello', 'hi', 10, 5)</code> then <code>A[0]</code> is the first item (which is 1) and <code>A[1]</code> is the second (which is 2).  The : is used inside of square brackets to obtain a ''slice'' of elements (some chunk of them). <code>A[2:4]</code> would be a tuple that starts with the third element of A and include 2 of the elements (so it would be ('hello', 'hi')).
* '''Parenthesis:''' <code> ( , )</code>
** Parenthesis as part of math expressions are used for enforcing a desired order of operations.
** Parenthesis immediately after a function name are used for either defining or calling a function. In both cases, the <code>,</code> is used to separate parameters.


[[File:Putty_Icon.png|The putty desktop icon]]
==Expressions==
There are many rules to keep in mind for how expressions are evaluated by Python.  The following are some of the rules you need to remember, and some examples to put into python to see what they evaluate to
* '''Operator precedence''' - inside of parenthesis first, then exponentiation, then multiplication/division/remainder, then addition/subtraction, then assignment.  Full list of operator precedence - [https://docs.python.org/3/reference/expressions.html#operator-precedence at python.org].
** <code>1 + 2 * 3</code>
** <code>1 + 2 * 9 ** 0.5</code>
** <code>(1 + 2) * 3</code>
* '''0-based indexing''' - index into string/list/tuple starts at 0
** <code>'hello'[0]</code>
** <code>(1, 2, 3)[1]</code>
* '''Slices''' - <code>x[i:j+1]</code> evaluates to a subsequence of x starting at index i and ending at index j
** <code>'hello'[1:3]</code>
** <code>[1, 2, 3, 4, 5][2:4]</code>
* '''String constants''' - anything inside of single quotes or double quotes, and + for strings is concatenation
** <code>'hi' + ' there'</code>
** <code>"2" + '3'</code>
** <code>str(2) + str(3)</code>
** <code>2 + 3</code>
** Triple single or double quotes can also be used, mainly to easily give string constants that are multiple lines long -
<pre>
message = '''
This message is more than one
line long.
'''
</pre>
* '''Boolean operators''' - note that <code>and</code> is higher precedence than <code>or</code> and that compound Boolean expression should be made out of complete Boolean expressions that are and'ed, or'ed together.  To check whether a variable x is 'a' or 'A', you need <code>if x == 'a' or x == 'A':</code>. If you tried using <code>if x == 'a' or 'A':</code> this always evaluates to True (because the part after the or, 'A', is considered to be True [anything that is not 0, '', or None - is True]).
* '''Immutability''' - string and tuple variables are immutable, they cannot be changed.  This also means that any string/tuple methods do not change the value of the string but only return a new string/tuple.
x = 'Hello'
x.upper()
print(x)
x = x.upper()
print(x)</code>


on your desktop.
==Data Types and Literals==
A "literal", when used in the context of programming, is a basic value that is contained within a program. The value of the literal is, literally, the value that it seems to be. The following are the basic data types in Python, and examples of literals for each.
* '''Integer''' - literals are numbers that do not have decimal points and are not contained in quotes. Note that integer arithmetic in Python is ''arbitrary precision'', meaning that Python integers have no maximum value (a very nice feature). Integers can be given in binary, octal, or hexadecimal using a leading <code>0b</code>, <code>0o</code>, or <code>0x</code>. <code>_</code> can be used within the digits to make grouping of digits easier to read. Examples of integer literals: <code>1234</code>, <code>-1234</code>, <code>16</code>, <code>0b10000</code>, <code>0o20</code>, <code>0x10</code>, <code>1_000_000_000</code>
* '''Floating point''' - literals are numbers that have a decimal point. Python does ''not'' use arbitrary precision with floating point arithmetic (meaning that there are limits to how large floating point numbers can be, and how many digits of precision). Scientific notation can be used. Examples of integer literals: <code>1234.0</code>, <code>3.14159</code>, <code>1_000_000.0</code>, <code>1e6</code>
* '''String''' - text data, which is between matching <code>'single quotes'</code>, <code>"double quotes"</code>, <code><nowiki>'''triple single quotes'''</nowiki></code>, or <code>"""triple double quotes"""</code>. Optionally, a <code>r</code> or <code>f</code> can be given before the quotes, to give a ''raw string'' or ''format string''.  raw strings treat escape characters literally, and format strings evaluate python expressions inside of <code>{ }</code>.  Other examples of string literals: <code>'1234'</code>, <code>'True'</code>, <code>'x = 3'</code>, <code>r'\n is normally a newline but not in raw strings'</code>, <code>f'5*5 = {5*5}'</code>
* '''Boolean''' - literals are <code>True</code> and <code>False</code>
* '''None''' - <code>None</code> is a special value in Python that is its own type.
* '''Tuple''' - a ''container type'', specified with matching (), that is ''immutable''.  Examples: <code>('a', 'b', 'c')</code>, <code>('a', )</code>
* '''List''' - a container type, specified with matching [], that ''is'' mutable.  Examples: <code>['a', 'b', 'c']</code>, <code>['a', ]</code>
* '''Dictionary''' - a container type where each item has a ''key'' used for looking up the item and a ''value'' that is stored with the key, specified with matching {} where each item is given as key:value.  Examples: <code>{'name': 'Alice', 'age': 42}</code>, <code>{'h1': 97, 'h2': 100, 'exams': [95, 34, 77]}</code>
* '''Set''' - a container type where there are no duplicates of items, specified with matching {} where each item is just a value (not a key:value as in dictionaries).  Examples: <code>{'orange', 'apple', 'banana'}</code>, <code>{99, 98, 96}</code>


== Startup and Configuration ==
==Other==
Here we give additional operators and punctuation that have meaning in python, but which we don't go into here because they are not commonly used in beginning python. For each of these you should just know that they exist and remember the description of what they mean. If you need to use them or need to understand code that uses them, you should ask the internet for examples and explanation.
* <code>\</code> can be used to break a long line into multiple lines while having python still regard them as a single logical line.
* <code>@</code> is used to make decorator functions.
* <code>:</code> and <code>-></code> can be used to annotate function definitions.
* <code>:=</code> can be used to assign a value within an expression.


The first time you run PuTTY, you will be prompted with a security warning:
==Assignment==
A typical "assignment" is to require a student to be able to correctly evaluate arbitrary expressions involving the operators.  You can think of this building up in complexity.
* Literal expressions - you should be able to identify the data type and value of any literal expression. The basic data types in Python are - integer, floating point, string, Boolean, tuple, list, dictionary, set, None.
* Binary operators - you should be able to evaluate an expression that has just two operands (e.g., 'hello' + 'cat').
* Larger expressions - you should be able to evaluate larger expressions using the python rules for order of operations (e.g., '3' + '5' * 4)


[[File:Security.png]]
A practice quiz that you can take is here - '''[https://indstate.instructure.com/courses/12565/quizzes/228160?module_item_id=1145792 Python Operators and Expressions Quiz]'''.


Un-check the "Always ask before opening this file" to never see the warning again. Then click "Run" to run PuTTY for the first time.
'''Pass rating check''' If you are assigned this quiz in a course, you should be able to score 100% on the quiz.
 
When you start PuTTY you will be presented with the Configuration menu:
 
[[File:Putty1.png|Configuration Menu]]
 
Under the Terminal/Keyboard settings, change the Backspace key to send "Control-H". You may want to change the font size (set under Window/Appearance) or the default number of rows and columns to display (set under Window). Any changes you would like to make permanent will need to be saved as a session under the Saved Session menu (under "Session", the first menu you see when you start PuTTY), by either creating a new session or clicking on "Default settings" and then clicking the Save button.
 
If you're going to be connecting to cs.indstate.edu often, you may want to set it in the Host Name field before saving the default settings as well.
 
== Connecting to cs.indstate.edu ==
 
The cs.indstate.edu server is the primary server for the CS department and which houses most of the accounts you will use. There may be other servers that you may be granted access to. To access the CS server, enter "cs.indstate.edu" into the Host Name (or IP address) field and make sure that the Port is "22" and the Connection type is "SSH", then click the "Open" button below to connect to the server.
 
Upon connecting the server for the first time you will be prompted with a PuTTY Security Alert box indicating that the host key hasn't been cached.
 
[[File:Putty-Key.png|Accepting the Host Key]]
 
Click on the "Yes" button to accept the host key and continue to connect to the server. At some point it may be the case that the server is upgraded and the host key is changed. This message will appear again indicating that the new host key does not match the cached version. You will need to remove the cached key to eliminate this message. Read the instructions below to remove old cached host keys.
 
Once connected you will see a terminal window with a "login as:" prompt, enter your CS account username at the prompt and hit enter.
 
[[File:Terminal.png|The Terminal Window]]
 
If you enter the wrong username or enter it incorrectly, you will have to close the window and restart PuTTY to try again. After entering your username, you will then be prompted for your password. You will not see anything as you type your password. Once you have successfully entered your password, you will be logged into the system and will be presented with a terminal prompt where you can enter Linux commands.
 
== Using the terminal interface ==
 
PuTTY operates just like a normal X terminal or Konsole window that you might use in the Unix lab. PuTTY can be used with either a xterm or vt100 terminal type ('''set term=xterm''' or '''set term=vt100''' if you use the tcsh shell or '''export TERM=xterm''' or '''export TERM=vt100''' if you use bash.) To make your terminal type permanent, edit your '''~/.cshrc''' (tcsh) or '''~/.bashrc''' (bash). Some commands will output to an "alternate" screen when the xterm terminal type is selected, such as "less", which disappears when the program exits. This can be annoying if you want the output to remain on the screen after you close the program. Using vt100 for your terminal type will usually prevent these programs from using this alternate screen, at the cost of some additional features provided by the xterm terminal type, such as additional colors and the ability to use your mouse. However, you may also be able to use "xterm1" which should give you all the normal xterm capabilities without the alternate screen.
 
When you are done with your session use the "logout" or "exit" commands to end your session. Your PuTTY screen should then close.
 
== Removing Stored SSH keys ==
 
To remove old cached host keys from PuTTY you will need to use the Windows Registry Editor (regedit.exe), which you will have to use the start menu to search for and run.
 
Browse the registry to the '''Computer\HKEY_CURRENT_USER\Software\SimonTatham\PuTTY\SshHostKeys''' section and right click and select "Delete" all entries that end with the name of the problem host.
 
[[File:Regedit.png|The Windows Registry Editor]]
 
== X Windows with Xming via PuTTY ==
 
X Windows applications can be run through the network via PuTTY if one has a working X server installed on their Window machine. To use X on Windows download and install the Xming X server and fonts provided here:
 
[http://cs.indstate.edu/FAQ/PuTTY/Xming/Xming-fonts-7-5-0-93-setup.exe Xming-fonts-7-5-0-93-setup.exe]
 
[http://cs.indstate.edu/FAQ/PuTTY/Xming/Xming-mesa-6-9-0-31-setup.exe Xming-mesa-6-9-0-31-setup.exe]
 
Or from http://www.straightrunning.com/xmingnotes/ Select the Xming-fonts and the Xming-mesa packages found under the "Public Domain Releases" section for the free version of Xming.
 
When installing the fonts, you probably do not need the Cryrillic fonts, but you should install all the rest.
 
When installing the Xming server, you do not need most of the extras as you already have PuTTY installed.
 
[[File:Xming-Install.png|The Xming Installer]]
 
Once you have completed installation you may have a desktop icon that looks like:
 
[[File:Xming-Icon.png|The Xming Desktop Icon]]
 
When you start Xming you likely will not see anything (except the standard Windows security message the first time you run Xming. You can see that the X server is running by looking at the hidden icons in the lower right side of your desktop toolbar.
 
[[File:Xming-running.png|The windows toolbar]]
 
To stop the X server, open the hidden icon menu and right click on the Xming icon and select "Exit".
 
While the X server is running PuTTY can be used to run X windows applications by forwarding the X. To forward X11 connections in PuTTY, in the configuration menu, go to Connection\SSH\X11 and click the "Enable X11 Forwarding" checkbox.
 
[[File:X-forward.png|Enabling X Forwarding in PuTTY]]
 
Then you can connect to cs.indstate.edu and run X11 applications. Note that X requires a high-bandwidth, low-latency connection and probably will not work suitably over a slow internet connection. X works best on local networks.

Revision as of 18:01, 7 September 2022

Following are terse descriptions for Python3 operators. For more information, see your Python reading material.

Operators

The following are a basic set of operators that most will intuitively know what they do.

  • Comments: # is used to demarcate comments - anything after a # on a line is ignored by the python interpreter.
  • Arithmetic operators: + - * / //
    • Note that / is floating point division (3/2 is 1.5), while // is integer division (3//2 is rounded down to 1).
  • Assignment operators: =
  • Comparison operators: < <= == != >= >
    • Note that == tests if two values are equal, != tests if they are not equal (3 != 2 will be True, 3 == 2 will be False).
  • Logical operators: and or not
  • Membership operators: in, not in

More Operators

The following are more operators. These may not be obvious. Some examples are given, but you may need to read through your Python text to understand these.

  • Arithmetic operators: % **
    • % is remainder (10 % 3 is 1, 17 % 3 is 2), and ** is exponentiation (10**3 is 1000, 2**3 is 8).
  • Assignment operators: += -= *= /= //= %= **= &= |= ^= >>= <<=
    • Each of these is shorthand. For example, x += 3 is a shorthand for x = x + 3
  • Identity operators: is, is not
    • Tests whether two objects are the same, not just whether the values are the same. For simple variables/expressions, is will be the same as ==, but for lists/tuples/dictionaries is only gives True if the two things being compared are actually the same object (not just the same values).
  • Bitwise operators: & | ^ ~ << >>
    • These operate on the bits of a number. You need to understand binary before you can understand these. Examples: 12 & 8 evaluates to 8, 12 | 7 evaluates to 15, 12 ^ 8 evaluates to 4, ~7 evaluates to -8 (same as -7-1), 3 << 2 evaluates to 12, 12 >> 1 evaluates to 6.
  • Brackets: [ : ]
    • Square brackets are used to pull individual elements from strings, lists, tuples, and dictionaries. If A = (1, 2, 'hello', 'hi', 10, 5) then A[0] is the first item (which is 1) and A[1] is the second (which is 2). The : is used inside of square brackets to obtain a slice of elements (some chunk of them). A[2:4] would be a tuple that starts with the third element of A and include 2 of the elements (so it would be ('hello', 'hi')).
  • Parenthesis: ( , )
    • Parenthesis as part of math expressions are used for enforcing a desired order of operations.
    • Parenthesis immediately after a function name are used for either defining or calling a function. In both cases, the , is used to separate parameters.

Expressions

There are many rules to keep in mind for how expressions are evaluated by Python. The following are some of the rules you need to remember, and some examples to put into python to see what they evaluate to

  • Operator precedence - inside of parenthesis first, then exponentiation, then multiplication/division/remainder, then addition/subtraction, then assignment. Full list of operator precedence - at python.org.
    • 1 + 2 * 3
    • 1 + 2 * 9 ** 0.5
    • (1 + 2) * 3
  • 0-based indexing - index into string/list/tuple starts at 0
    • 'hello'[0]
    • (1, 2, 3)[1]
  • Slices - x[i:j+1] evaluates to a subsequence of x starting at index i and ending at index j
    • 'hello'[1:3]
    • [1, 2, 3, 4, 5][2:4]
  • String constants - anything inside of single quotes or double quotes, and + for strings is concatenation
    • 'hi' + ' there'
    • "2" + '3'
    • str(2) + str(3)
    • 2 + 3
    • Triple single or double quotes can also be used, mainly to easily give string constants that are multiple lines long -
message = '''
This message is more than one 
line long.
'''
  • Boolean operators - note that and is higher precedence than or and that compound Boolean expression should be made out of complete Boolean expressions that are and'ed, or'ed together. To check whether a variable x is 'a' or 'A', you need if x == 'a' or x == 'A':. If you tried using if x == 'a' or 'A': this always evaluates to True (because the part after the or, 'A', is considered to be True [anything that is not 0, , or None - is True]).
  • Immutability - string and tuple variables are immutable, they cannot be changed. This also means that any string/tuple methods do not change the value of the string but only return a new string/tuple.
x = 'Hello'
x.upper()
print(x)
x = x.upper()
print(x)

Data Types and Literals

A "literal", when used in the context of programming, is a basic value that is contained within a program. The value of the literal is, literally, the value that it seems to be. The following are the basic data types in Python, and examples of literals for each.

  • Integer - literals are numbers that do not have decimal points and are not contained in quotes. Note that integer arithmetic in Python is arbitrary precision, meaning that Python integers have no maximum value (a very nice feature). Integers can be given in binary, octal, or hexadecimal using a leading 0b, 0o, or 0x. _ can be used within the digits to make grouping of digits easier to read. Examples of integer literals: 1234, -1234, 16, 0b10000, 0o20, 0x10, 1_000_000_000
  • Floating point - literals are numbers that have a decimal point. Python does not use arbitrary precision with floating point arithmetic (meaning that there are limits to how large floating point numbers can be, and how many digits of precision). Scientific notation can be used. Examples of integer literals: 1234.0, 3.14159, 1_000_000.0, 1e6
  • String - text data, which is between matching 'single quotes', "double quotes", '''triple single quotes''', or """triple double quotes""". Optionally, a r or f can be given before the quotes, to give a raw string or format string. raw strings treat escape characters literally, and format strings evaluate python expressions inside of { }. Other examples of string literals: '1234', 'True', 'x = 3', r'\n is normally a newline but not in raw strings', f'5*5 = {5*5}'
  • Boolean - literals are True and False
  • None - None is a special value in Python that is its own type.
  • Tuple - a container type, specified with matching (), that is immutable. Examples: ('a', 'b', 'c'), ('a', )
  • List - a container type, specified with matching [], that is mutable. Examples: ['a', 'b', 'c'], ['a', ]
  • Dictionary - a container type where each item has a key used for looking up the item and a value that is stored with the key, specified with matching {} where each item is given as key:value. Examples: {'name': 'Alice', 'age': 42}, {'h1': 97, 'h2': 100, 'exams': [95, 34, 77]}
  • Set - a container type where there are no duplicates of items, specified with matching {} where each item is just a value (not a key:value as in dictionaries). Examples: {'orange', 'apple', 'banana'}, {99, 98, 96}

Other

Here we give additional operators and punctuation that have meaning in python, but which we don't go into here because they are not commonly used in beginning python. For each of these you should just know that they exist and remember the description of what they mean. If you need to use them or need to understand code that uses them, you should ask the internet for examples and explanation.

  • \ can be used to break a long line into multiple lines while having python still regard them as a single logical line.
  • @ is used to make decorator functions.
  • : and -> can be used to annotate function definitions.
  • := can be used to assign a value within an expression.

Assignment

A typical "assignment" is to require a student to be able to correctly evaluate arbitrary expressions involving the operators. You can think of this building up in complexity.

  • Literal expressions - you should be able to identify the data type and value of any literal expression. The basic data types in Python are - integer, floating point, string, Boolean, tuple, list, dictionary, set, None.
  • Binary operators - you should be able to evaluate an expression that has just two operands (e.g., 'hello' + 'cat').
  • Larger expressions - you should be able to evaluate larger expressions using the python rules for order of operations (e.g., '3' + '5' * 4)

A practice quiz that you can take is here - Python Operators and Expressions Quiz.

Pass rating check If you are assigned this quiz in a course, you should be able to score 100% on the quiz.