Python: Difference between revisions

From bibbleWiki
Jump to navigation Jump to search
No edit summary
Line 24: Line 24:
<syntaxhighlight lang="python">
<syntaxhighlight lang="python">
help(math)
help(math)
</syntaxhighlight>
= Scalar Types, Operators and Control =
== Types ==
* int (42)
* float (4.2)
* NoneType (None)
* bool ( True, False) 0 = False !=0 = True
== Operators ==
* == value equality
* != value inequality
* < less-than
* > greater-than
* <= less-than or equal
* >= greater-than or equal
== Control ==
=== if statementes ===
<syntaxhighlight lang="python">
if True:
    print("Its true")
h = 42
if h > 50:
    print("Greater than 50")
elif h < 20:
    print("Less than 20")
else:
    print("Other")
</syntaxhighlight>
=== while loops ===
<syntaxhighlight lang="python">
while c != 0:
    print(c)
    c -= 1 // c = c-1
    print("Its true")
while True:
    response = input()
    if int(response) % 7 == 0:
      break
</syntaxhighlight>
</syntaxhighlight>

Revision as of 04:36, 15 July 2020

Intro

Python 2 and 3 differences

print "fred" // OK Python 2
print("fred") // Not OK Python 2

Whitespace

Uses full colon and four spaces instead of brackets e.g.

for i in range(5):
    x = i * 10
    print(x)

Rules

  • Prefer four spaces
  • Never mix spaces and tabs
  • Be consistent on consecutive lines
  • Only deviate to improve readability

Help

help(object) gives help. e.g. for the module math

help(math)

Scalar Types, Operators and Control

Types

  • int (42)
  • float (4.2)
  • NoneType (None)
  • bool ( True, False) 0 = False !=0 = True

Operators

  • == value equality
  • != value inequality
  • < less-than
  • > greater-than
  • <= less-than or equal
  • >= greater-than or equal

Control

if statementes

if True: 
    print("Its true")

h = 42
if h > 50: 
    print("Greater than 50")
elif h < 20:
    print("Less than 20")
else:
    print("Other")

while loops

while c != 0: 
    print(c)
    c -= 1 // c = c-1
    print("Its true")

while True: 
    response = input()
    if int(response) % 7 == 0: 
       break