ModdersCentral

Full Version: Python Basics
You're currently viewing a stripped down version of our content. View the full version with proper formatting.
comments:

Code:
#comments begin with a hash

writing text to screen:

Code:
print("This line will be displayed.")
adding these lines to the top of the text editor keeps your lecturer happy:
Code:
#Name of program
#today's date
#your name
you could even make it better by putting this:
Code:
#  File:        
#  Purpose:    
#  Programmer:  
#  Course:    
#  Date:




declaring (numbers):

Code:
myvar1 = 1

declaring strings:

Code:
myvar1 = "some text here"

if statement:

Code:
x = 1
if x == 1:
    print("x is 1.")# indented four spaces
arrays
Code:
a = ['item0', 'item1', 'item2', 'item3', 'item4']
for i in range(len(a)):
    print i, a[i]
functions:
Code:
def add_numbers(x,y):
   return  x + y

num1 = 5
num2 = 6

print("The sum is", add_numbers(num1, num2))

classes
Code:
class Person():
    def __init__(self, first_name, last_name):
        self._firstname = first_name
        self._lastname = last_name

    def getFirstname(self):  
        return self._firstname

    def getLastname(self):  
        return self._lastname

    def setFirstname(self,newFirstname):
        self._firstname = newFirstname

    def setLastname(self,newLastname):
        self._lastname = newLastname


person1 = Person("john","Doe")  
person1.setFirstname("johnny")
print(person1.getFirstname())
number check
Code:
number = input("Enter a number ")
if number.isdigit()==True:
    print("You entered a number")
else:
    print("You didn't enter a number")
invalid input
Code:
number=input("Please enter a number: ")
if len(number)==0:
    print("Please enter a number")
else:
    print("Welcome to the program")
Range Check
Code:
number=int(input("Please enter a number between 1 and 100: "))
if number>0 and number<= 100:
    print("You entered a valid number")
else:
    print("You must enter a number between 1 and 100")
regex
Code:
import re
email = input("Enter an email address: ")
pattern = "^[A-Za-z0-9]+\@[A-Za-z0-9]+\.[A-Za-z0-9]+$"
emailMatch = re.match(pattern, email)
if emailMatch:
    print("This is a valid email format")
else:
    print("This is an invalid email format")
www.000webhost.com