Python Basics: Hello World, Print Function, Operators, Input/Output, Data Types, Control Flow, and Simple Exercises
This tutorial introduces Python fundamentals, covering hello‑world output, the print function, arithmetic and logical operators, user input handling, string and list operations, tuples, dictionaries, conditional statements, ternary expressions, simple authentication, number‑guessing games, score classification, and while‑loop examples with complete code snippets.
01 - Hello World
Python relies on indentation; use four spaces per level. The following example demonstrates a simple hello‑world print and an indented if‑statement.
print('hello world!')
if 3 > 0:
print('OK')
print('yes')
x = 3; y = 4 # not recommended, should be on separate lines
print(x + y)02 - print Function
The print function can output multiple arguments, concatenate strings, customize separators, repeat characters, and suppress the trailing newline.
print('hello world!')
print('hello', 'world!') # prints with a space
print('hello' + 'world!') # concatenates without space
print('hello', 'world', sep='***') # uses *** as separator
print('#' * 50) # repeats character 50 times
print('how are you?', end='') # suppresses newline03 - Basic Operators
Demonstrates arithmetic, comparison, and logical operators with their precedence.
print(5 / 2) # 2.5
print(5 // 2) # integer division
print(5 % 2) # remainder
print(5 ** 3) # exponentiation
print(5 > 3) # True
print(3 > 5) # False
print(20 > 10 > 5) # chained comparison
print(20 > 10 and 10 > 5) # equivalent logical expression
print(not 20 > 10) # False04 - input
Shows how to read user input and convert types.
number = input("请输入数字:") # input reads a string
print(number)
print(type(number)) # shows <class 'str'>
print(number + 10) # TypeError
print(int(number) + 10) # converts to int
print(number + str(10)) # concatenates as strings05 - Basic I/O Exercise
username = input('username: ')
print('welcome', username) # default space separator
print('welcome ' + username) # explicit space06 - String Basics
Illustrates quoting, escaping, multi‑line strings, slicing, and common string operations.
sentence = 'tom\'s pet is a cat' # escape single quote
sentence2 = "tom's pet is a cat"
sentence3 = "tom said:\"hello world!\""
sentence4 = 'tom said:"hello world"'
# Triple quotes for multi‑line string
words = """
hello
world
abcd
"""
print(words)
py_str = 'python'
len(py_str)
py_str[0]
'python'[0]
py_str[-1]
py_str[2:4]
py_str[2:]
py_str[:2]
py_str[:]
py_str[::2]
py_str[1::2]
py_str[::-1]
py_str + ' is good'
py_str * 3
't' in py_str
'th' in py_str
'to' in py_str
'to' not in py_str07 - List Basics
alist = [10, 20, 30, 'bob', 'alice', [1,2,3]]
len(alist)
alist[-1] # last element
alist[-1][-1] # nested list element
[1,2,3][-1]
alist[-2][2]
alist[3:5] # ['bob', 'alice']
10 in alist
'o' in alist
100 not in alist
alist[-1] = 100 # modify
alist.append(200) # add element08 - Tuple Basics
atuple = (10, 20, 30, 'bob', 'alice', [1,2,3])
len(atuple)
10 in atuple
atuple[2]
atuple[3:5]
# atuple[-1] = 100 # error, tuple is immutable09 - Dictionary Basics
# key‑value mapping, unordered
adict = {'name': 'bob', 'age': 23}
len(adict)
'bob' in adict # False, checks keys
'name' in adict # True
adict['email'] = '[email protected]' # add new key
adict['age'] = 25 # update existing key10 - Basic Truthiness
if 3 > 0:
print('yes')
print('ok')
if 10 in [10, 20, 30]:
print('ok')
if -0.0:
print('yes') # False for zero
if [1, 2]:
print('yes') # True for non‑empty list
if ' ':
print('yes') # True for non‑empty string11 - Conditional Expression (Ternary)
a = 10
b = 20
if a < b:
smaller = a
else:
smaller = b
print(smaller)
s = a if a < b else b # equivalent
print(s)12 - Login Check Exercise
import getpass
username = input('username: ')
password = getpass.getpass('password: ')
if username == 'bob' and password == '123456':
print('Login successful')
else:
print('Login incorrect')13 - Number Guessing (Basic)
import random
num = random.randint(1, 10)
answer = int(input('guess a number: '))
if answer > num:
print('猜大了')
elif answer < num:
print('猜小了')
else:
print('猜对了')
print('the number:', num)14 - Score Classification 1
score = int(input('分数:'))
if score >= 90:
print('优秀')
elif score >= 80:
print('好')
elif score >= 70:
print('良')
elif score >= 60:
print('及格')
else:
print('你要努力了')15 - Score Classification 2
score = int(input('分数:'))
if score >= 60 and score < 70:
print('及格')
elif 70 <= score < 80:
print('良')
elif 80 <= score < 90:
print('好')
elif score >= 90:
print('优秀')
else:
print('你要努力了')16 - Rock Paper Scissors
import random
all_choices = ['石头', '剪刀', '布']
computer = random.choice(all_choices)
player = input('请出拳:')
print("Your choice: %s, Computer's choice: %s" % (player, computer))
if player == '石头':
if computer == '石头':
print('平局')
elif computer == '剪刀':
print('You WIN!!!')
else:
print('You LOSE!!!')
elif player == '剪刀':
if computer == '石头':
print('You LOSE!!!')
elif computer == '剪刀':
print('平局')
else:
print('You WIN!!!')
else:
if computer == '石头':
print('You WIN!!!')
elif computer == '剪刀':
print('You LOSE!!!')
else:
print('平局')17 - Improved Rock Paper Scissors
import random
all_choices = ['石头', '剪刀', '布']
win_list = [['石头', '剪刀'], ['剪刀', '布'], ['布', '石头']]
prompt = "(0) 石头\n(1) 剪刀\n(2) 布\n请选择 (0/1/2): "
computer = random.choice(all_choices)
ind = int(input(prompt))
player = all_choices[ind]
print("Your choice: %s, Computer's choice: %s" % (player, computer))
if player == computer:
print('\033[32;1m 平局、033[0m')
elif [player, computer] in win_list:
print('\033[31;1mYou WIN!!!\033[0m')
else:
print('\033[31;1mYou LOSE!!!\033[0m')18 - Guess Number Until Correct
import random
num = random.randint(1, 10)
running = True
while running:
answer = int(input('guess the number: '))
if answer > num:
print('猜大了')
elif answer < num:
print('猜小了')
else:
print('猜对了')
running = False19 - Guess Number with 5 Attempts
import random
num = random.randint(1, 10)
counter = 0
while counter < 5:
answer = int(input('guess the number: '))
if answer > num:
print('猜大了')
elif answer < num:
print('猜小了')
else:
print('猜对了')
break
counter += 1
else:
print('the number is:', num)20 - While Loop Summation to 100
sum100 = 0
counter = 1
while counter < 101:
sum100 += counter
counter += 1
print(sum100)Follow the QR code to get free Python learning resources, including e‑books, tutorials, project samples, and source code.
Click the link to read the original article for more details.
Python Programming Learning Circle
A global community of Chinese Python developers offering technical articles, columns, original video tutorials, and problem sets. Topics include web full‑stack development, web scraping, data analysis, natural language processing, image processing, machine learning, automated testing, DevOps automation, and big data.
How this landed with the community
Was this worth your time?
0 Comments
Thoughtful readers leave field notes, pushback, and hard-won operational detail here.